You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by ac...@apache.org on 2018/12/13 08:35:09 UTC
[camel] 01/10: CAMEL-12954 adding camel-websocket-jsr356 module
This is an automated email from the ASF dual-hosted git repository.
acosentino pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git
commit aba406faebb239d85dd45557c34a4d46ad1a9b89
Author: Romain Manni-Bucau <rm...@gmail.com>
AuthorDate: Fri Nov 23 12:49:32 2018 +0100
CAMEL-12954 adding camel-websocket-jsr356 module
---
components/camel-websocket-jsr356/pom.xml | 98 ++++++++++
.../src/main/docs/websocket-jsr356-component.adoc | 40 ++++
.../apache/camel/jsr356/CamelServerEndpoint.java | 80 ++++++++
.../org/apache/camel/jsr356/ClientSessions.java | 151 +++++++++++++++
.../org/apache/camel/jsr356/JSR356Constants.java | 22 +++
.../org/apache/camel/jsr356/JSR356Consumer.java | 103 +++++++++++
.../org/apache/camel/jsr356/JSR356Endpoint.java | 75 ++++++++
.../org/apache/camel/jsr356/JSR356Producer.java | 90 +++++++++
.../camel/jsr356/JSR356WebSocketComponent.java | 100 ++++++++++
.../apache/camel/jsr356/ServletIntegration.java | 47 +++++
.../src/main/resources/META-INF/LICENSE.txt | 203 +++++++++++++++++++++
.../src/main/resources/META-INF/NOTICE.txt | 11 ++
.../javax.servlet.ServletContainerInitializer | 17 ++
.../services/org/apache/camel/component/jsr356 | 17 ++
.../apache/camel/jsr356/JSR356ConsumerTest.java | 115 ++++++++++++
.../apache/camel/jsr356/JSR356ProducerTest.java | 93 ++++++++++
components/pom.xml | 1 +
17 files changed, 1263 insertions(+)
diff --git a/components/camel-websocket-jsr356/pom.xml b/components/camel-websocket-jsr356/pom.xml
new file mode 100644
index 0000000..0d31019
--- /dev/null
+++ b/components/camel-websocket-jsr356/pom.xml
@@ -0,0 +1,98 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="
+ http://maven.apache.org/POM/4.0.0
+ http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <artifactId>components</artifactId>
+ <groupId>org.apache.camel</groupId>
+ <version>2.23.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>camel-websocket-jsr356</artifactId>
+ <description>Camel WebSocket using JSR356 (javax)</description>
+
+ <properties>
+ <tomcat.version>9.0.13</tomcat.version>
+
+ <camel.osgi.export.pkg>
+ org.apache.camel.component.jsr356.*;${camel.osgi.version}
+ </camel.osgi.export.pkg>
+ <camel.osgi.import.pkg>
+ !org.apache.camel.component.jsr356.*,
+ javax.websocket;version="[1.0,3)",
+ ${camel.osgi.import.defaults},
+ *
+ </camel.osgi.import.pkg>
+ <camel.osgi.export.service>org.apache.camel.spi.ComponentResolver;component=jsr356</camel.osgi.export.service>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-core</artifactId>
+ </dependency>
+ <dependency> <!-- standard API bundled @asf -->
+ <groupId>org.apache.tomcat</groupId>
+ <artifactId>tomcat-websocket-api</artifactId>
+ <version>${tomcat.version}</version>
+ <scope>provided</scope> <!-- assumed embedded in a container with it -->
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tomcat</groupId>
+ <artifactId>tomcat-servlet-api</artifactId>
+ <version>${tomcat.version}</version>
+ <scope>provided</scope>
+ <optional>true</optional>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.meecrowave</groupId>
+ <artifactId>meecrowave-junit</artifactId>
+ <version>1.2.4</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tomcat</groupId>
+ <artifactId>tomcat-websocket</artifactId>
+ <version>${tomcat.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.logging.log4j</groupId>
+ <artifactId>log4j-slf4j-impl</artifactId>
+ <version>2.11.1</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/components/camel-websocket-jsr356/src/main/docs/websocket-jsr356-component.adoc b/components/camel-websocket-jsr356/src/main/docs/websocket-jsr356-component.adoc
new file mode 100644
index 0000000..f84d8b2
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/docs/websocket-jsr356-component.adoc
@@ -0,0 +1,40 @@
+[[websocket-component]]
+== Websocket JSR356 Component
+
+*Available as of Camel version 2.23*
+
+The *jsr356* component provides websocket
+endpoints for communicating with clients using
+JSR356 (javax).
+
+
+### URI format
+
+To consume from the local instance on a particular `path` the messages:
+
+[source,java]
+----
+jsr356://${path}
+----
+
+To consume from a remote instance - i.e. Camel will be a client - on a particular `uri` the messages:
+
+[source,java]
+----
+jsr356://${uri}
+----
+
+You can append query options to the URI in the following format,
+`?option=value&option=value&...`
+
+### Websocket Options
+
+
+// component options: START
+[width="100%",cols="2,5,^1,2",options="header"]
+|===
+| Name | Description | Default | Type
+| *sessionCount* (consumer/producer) | Number of session to pool. | 1 | Integer > 0
+| *context* (consumer/producer) | The servlet context (path) to use if ambiguous to deploy locally endpoints. | - | String
+|===
+// component options: END
diff --git a/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/CamelServerEndpoint.java b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/CamelServerEndpoint.java
new file mode 100644
index 0000000..462cbe9
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/CamelServerEndpoint.java
@@ -0,0 +1,80 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.jsr356;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collection;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.BiConsumer;
+
+import javax.websocket.CloseReason;
+import javax.websocket.Endpoint;
+import javax.websocket.EndpointConfig;
+import javax.websocket.Session;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class CamelServerEndpoint extends Endpoint {
+ private final Logger log = LoggerFactory.getLogger(CamelServerEndpoint.class);
+
+ private final Collection<BiConsumer<Session, Object>> endpoints = new CopyOnWriteArrayList<>();
+
+ private Session session;
+
+ Collection<BiConsumer<Session, Object>> getEndpoints() {
+ return endpoints;
+ }
+
+ Session getSession() {
+ return session;
+ }
+
+ @Override
+ public void onOpen(final Session session, final EndpointConfig endpointConfig) {
+ this.session = session;
+ log.debug("Session opened #{}", session.getId());
+ session.addMessageHandler(InputStream.class, this::propagateExchange);
+ session.addMessageHandler(String.class, this::propagateExchange);
+ }
+
+ @Override
+ public void onClose(final Session session, final CloseReason closeReason) {
+ log.debug("Session closed #{}", session.getId());
+ }
+
+ @Override
+ public void onError(final Session session, final Throwable throwable) {
+ synchronized (session) {
+ if (session.isOpen()) {
+ try {
+ session.close(new CloseReason(CloseReason.CloseCodes.CLOSED_ABNORMALLY, "an exception occured"));
+ } catch (final IOException e) {
+ log.debug("Error closing session #{}", session.getId(), e);
+ }
+ }
+ }
+ log.debug("Error on session #{}", session.getId(), throwable);
+ }
+
+ private void propagateExchange(final Object message) {
+ synchronized (session) {
+ endpoints.forEach(consumer -> consumer.accept(session, message));
+ }
+ }
+}
diff --git a/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/ClientSessions.java b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/ClientSessions.java
new file mode 100644
index 0000000..929fa38
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/ClientSessions.java
@@ -0,0 +1,151 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.jsr356;
+
+import static java.util.concurrent.CompletableFuture.completedFuture;
+import static java.util.stream.Collectors.toList;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.stream.IntStream;
+
+import javax.websocket.ClientEndpointConfig;
+import javax.websocket.CloseReason;
+import javax.websocket.ContainerProvider;
+import javax.websocket.DeploymentException;
+import javax.websocket.Endpoint;
+import javax.websocket.EndpointConfig;
+import javax.websocket.Session;
+import javax.websocket.WebSocketContainer;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ClientSessions implements Closeable {
+ private final Logger log = LoggerFactory.getLogger(ClientSessions.class);
+
+ private final int expectedCount;
+ private final URI uri;
+ private final ClientEndpointConfig config;
+ private final WebSocketContainer container;
+ private final BlockingQueue<Session> sessions;
+ private final AtomicBoolean closed = new AtomicBoolean();
+ private final BiConsumer<Session, Object> onMessage;
+
+ ClientSessions(final int count, final URI uri, final ClientEndpointConfig config,
+ final BiConsumer<Session, Object> onMessage) {
+ this.uri = uri;
+ this.expectedCount = count;
+ this.config = config;
+ this.onMessage = onMessage;
+ this.sessions = new ArrayBlockingQueue<>(expectedCount);
+ // todo: grab it from the context?
+ this.container = ContainerProvider.getWebSocketContainer();
+ }
+
+ public void prepare() {
+ sessions.addAll(IntStream.range(0, expectedCount).mapToObj(idx -> doConnect()).collect(toList()));
+ }
+
+ public <T> CompletionStage<T> execute(final Function<Session, CompletionStage<T>> apply) {
+ try {
+ final Session session = sessions.take();
+ return apply.apply(session)
+ .handle((result, exception) -> {
+ sessions.offer(session);
+ if (exception != null) {
+ if (RuntimeException.class.isInstance(exception)) {
+ throw RuntimeException.class.cast(exception);
+ }
+ if (Error.class.isInstance(exception)) {
+ throw Error.class.cast(exception);
+ }
+ throw new IllegalStateException(exception);
+ }
+ return result;
+ });
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return completedFuture(null);
+ }
+ }
+
+ private Session doConnect() {
+ try {
+ final Session session = container.connectToServer(new Endpoint() {
+ @Override
+ public void onOpen(final Session session, final EndpointConfig endpointConfig) {
+ log.debug("Session opened #{}", session.getId());
+ }
+
+ @Override
+ public void onClose(final Session session, final CloseReason closeReason) {
+ sessions.remove(session);
+ log.debug("Session closed #{}", session.getId());
+ }
+
+ @Override
+ public void onError(final Session session, final Throwable throwable) {
+ if (session.isOpen()) {
+ try {
+ session.close(
+ new CloseReason(CloseReason.CloseCodes.CLOSED_ABNORMALLY, "an exception occured"));
+ } catch (final IOException e) {
+ log.debug("Error closing session #{}", session.getId(), e);
+ }
+ }
+ sessions.remove(session);
+ log.debug("Error on session #{}", session.getId(), throwable);
+
+ if (!closed.get()) { // try to repopulate it
+ sessions.offer(doConnect());
+ }
+ }
+ }, config, uri);
+ if (onMessage != null) {
+ session.addMessageHandler(InputStream.class, message -> onMessage.accept(session, message));
+ session.addMessageHandler(String.class, message -> onMessage.accept(session, message));
+ }
+ return session;
+ } catch (final DeploymentException | IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ @Override
+ public void close() {
+ closed.set(true);
+ sessions.forEach(it -> {
+ if (it.isOpen()) {
+ try {
+ it.close();
+ } catch (final IOException e) {
+ log.debug(e.getMessage(), e);
+ }
+ }
+ });
+ sessions.clear();
+ }
+}
diff --git a/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Constants.java b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Constants.java
new file mode 100644
index 0000000..7a07faa
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Constants.java
@@ -0,0 +1,22 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.jsr356;
+
+public interface JSR356Constants {
+ String SESSION = "jsr356.session";
+ String USE_INCOMING_SESSION = "jsr356.producer.session.incoming.use";
+}
diff --git a/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Consumer.java b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Consumer.java
new file mode 100644
index 0000000..eb562cb
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Consumer.java
@@ -0,0 +1,103 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.jsr356;
+
+import static java.util.Optional.ofNullable;
+
+import java.net.URI;
+import java.util.function.BiConsumer;
+
+import javax.websocket.ClientEndpointConfig;
+import javax.websocket.Session;
+import javax.websocket.server.ServerEndpointConfig;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.impl.DefaultConsumer;
+
+public class JSR356Consumer extends DefaultConsumer {
+ private final int sessionCount;
+ private final String context;
+ private ClientSessions manager;
+ private Runnable closeTask = null;
+
+ private final BiConsumer<Session, Object> onMessage = (session, message) -> {
+ final Exchange exchange = getEndpoint().createExchange();
+ exchange.getIn().setHeader(JSR356Constants.SESSION, session);
+ exchange.getIn().setBody(message);
+ getAsyncProcessor().process(exchange, doneSync -> {
+ if (exchange.getException() != null) {
+ getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
+ }
+ });
+ };;
+
+ JSR356Consumer(final JSR356Endpoint jsr356Endpoint, final Processor processor,
+ final int sessionCount, final String context) {
+ super(jsr356Endpoint, processor);
+ this.sessionCount = sessionCount;
+ this.context = context;
+ }
+
+ @Override
+ public JSR356Endpoint getEndpoint() {
+ return JSR356Endpoint.class.cast(super.getEndpoint());
+ }
+
+ @Override
+ protected void doStart() throws Exception {
+ super.doStart();
+ final String endpointKey = getEndpoint().getEndpointUri().substring("jsr356://".length());
+ if (endpointKey.contains("://")) { // we act as a client
+ final ClientEndpointConfig.Builder clientConfig = ClientEndpointConfig.Builder.create(); // todo: config
+ manager = new ClientSessions(sessionCount, URI.create(endpointKey), clientConfig.build(), onMessage);
+ manager.prepare();
+ } else {
+ final JSR356WebSocketComponent.ContextBag bag = JSR356WebSocketComponent.getContext(context);
+ final CamelServerEndpoint endpoint = bag.getEndpoints().get(endpointKey);
+ if (endpoint == null) {
+ // todo: make it customizable (the endpoint config)
+ final ServerEndpointConfig.Builder configBuilder = ServerEndpointConfig.Builder.create(CamelServerEndpoint.class,
+ endpointKey);
+ final CamelServerEndpoint serverEndpoint = new CamelServerEndpoint();
+ bag.getEndpoints().put(endpointKey, serverEndpoint);
+ closeTask = addObserver(serverEndpoint);
+ configBuilder.configurator(new ServerEndpointConfig.Configurator() {
+ @Override
+ public <T> T getEndpointInstance(final Class<T> clazz) {
+ return clazz.cast(serverEndpoint);
+ }
+ });
+ bag.getContainer().addEndpoint(configBuilder.build());
+ } else {
+ closeTask = addObserver(endpoint);
+ }
+ }
+ }
+
+ private Runnable addObserver(final CamelServerEndpoint endpoint) {
+ endpoint.getEndpoints().add(onMessage);
+ return () -> endpoint.getEndpoints().remove(onMessage);
+ }
+
+ @Override
+ protected void doStop() throws Exception {
+ ofNullable(manager).ifPresent(ClientSessions::close);
+ ofNullable(closeTask).ifPresent(Runnable::run);
+ super.doStop();
+ }
+}
diff --git a/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Endpoint.java b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Endpoint.java
new file mode 100644
index 0000000..2c232aa
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Endpoint.java
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.jsr356;
+
+import org.apache.camel.Consumer;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.impl.DefaultEndpoint;
+import org.apache.camel.spi.UriEndpoint;
+import org.apache.camel.spi.UriParam;
+import org.apache.camel.spi.UriPath;
+
+@UriEndpoint(
+ firstVersion = "2.23.0", scheme = "jsr356", title = "Javax Websocket",
+ syntax = "jsr356:/resourceUri", consumerClass = JSR356Consumer.class, label = "jsr356")
+public class JSR356Endpoint extends DefaultEndpoint {
+ @UriPath(description = "If a path (/foo) it will deploy locally the endpoint, " +
+ "if an uri it will connect to the corresponding server")
+ private String websocketPathOrUri;
+
+ @UriParam(description = "Used when the endpoint is in client mode to populate a pool of sessions")
+ private int sessionCount = 1;
+
+ @UriParam(description = "the servlet context to use (represented by its path)")
+ private String context;
+
+ private final JSR356WebSocketComponent component;
+
+ public JSR356Endpoint(final JSR356WebSocketComponent component, final String uri) {
+ super(uri, component);
+ this.component = component;
+ }
+
+ @Override
+ public JSR356WebSocketComponent getComponent() {
+ return JSR356WebSocketComponent.class.cast(super.getComponent());
+ }
+
+ @Override
+ public Consumer createConsumer(final Processor processor) {
+ return new JSR356Consumer(this, processor, sessionCount, context);
+ }
+
+ @Override
+ public Producer createProducer() {
+ return new JSR356Producer(this, sessionCount);
+ }
+
+ @Override
+ public boolean isSingleton() {
+ return true;
+ }
+
+ public int getSessionCount() {
+ return sessionCount;
+ }
+
+ public void setSessionCount(final int sessionCount) {
+ this.sessionCount = sessionCount;
+ }
+}
diff --git a/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Producer.java b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Producer.java
new file mode 100644
index 0000000..7b6ccef
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356Producer.java
@@ -0,0 +1,90 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.jsr356;
+
+import static java.util.Optional.ofNullable;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+import java.util.function.BiConsumer;
+
+import javax.websocket.ClientEndpointConfig;
+import javax.websocket.Session;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.Exchange;
+import org.apache.camel.impl.DefaultAsyncProducer;
+
+public class JSR356Producer extends DefaultAsyncProducer {
+ private final int sessionCount;
+ private ClientSessions manager;
+ private BiConsumer<Exchange, AsyncCallback> onExchange;
+
+ JSR356Producer(final JSR356Endpoint jsr356Endpoint, final int sessionCount) {
+ super(jsr356Endpoint);
+ this.sessionCount = sessionCount;
+ }
+
+ @Override
+ public JSR356Endpoint getEndpoint() {
+ return JSR356Endpoint.class.cast(super.getEndpoint());
+ }
+
+ @Override
+ public boolean process(final Exchange exchange, final AsyncCallback callback) {
+ final Session session = exchange.getIn().getHeader(JSR356Constants.SESSION, Session.class);
+ if (session != null && exchange.getIn().getHeader(JSR356Constants.USE_INCOMING_SESSION, false, Boolean.class)) {
+ synchronized (session) {
+ doSend(exchange, session);
+ }
+ } else {
+ onExchange.accept(exchange, callback);
+ }
+ return true;
+ }
+
+ @Override
+ protected void doStart() throws Exception {
+ super.doStart();
+ final String endpointKey = getEndpoint().getEndpointUri().substring("jsr356://".length());
+ if (!endpointKey.contains("://")) { // we act as a client in all cases here
+ throw new IllegalArgumentException("You should pass a client uri");
+ }
+ final ClientEndpointConfig.Builder clientConfig = ClientEndpointConfig.Builder.create();
+ manager = new ClientSessions(sessionCount, URI.create(endpointKey), clientConfig.build(), null);
+ manager.prepare();
+ onExchange = (ex, cb) -> manager.execute(session -> doSend(ex, session));
+ }
+
+ private CompletionStage<Object> doSend(final Exchange ex, final Session session) {
+ final CompletableFuture<Object> future = new CompletableFuture<>();
+ try {
+ getEndpoint().getComponent().sendMessage(session, ex.getIn().getBody());
+ } catch (final IOException e) {
+ ex.setException(e);
+ }
+ return future;
+ }
+
+ @Override
+ protected void doStop() throws Exception {
+ ofNullable(manager).ifPresent(ClientSessions::close);
+ super.doStop();
+ }
+}
diff --git a/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356WebSocketComponent.java b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356WebSocketComponent.java
new file mode 100644
index 0000000..5176419
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/JSR356WebSocketComponent.java
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.jsr356;
+
+import static java.util.Optional.ofNullable;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.websocket.Session;
+import javax.websocket.server.ServerContainer;
+
+import org.apache.camel.Endpoint;
+import org.apache.camel.impl.DefaultComponent;
+import org.apache.camel.spi.Metadata;
+
+public class JSR356WebSocketComponent extends DefaultComponent {
+ // didn't find a better way to handle that unless we can assume the CamelContext is in the ServletContext
+ private static final Map<String, ContextBag> SERVER_CONTAINERS = new ConcurrentHashMap<>();
+
+ @Metadata(label = "sessionCount")
+ protected int sessionCount;
+
+ @Override
+ protected Endpoint createEndpoint(final String uri, final String remaining, final Map<String, Object> parameters) {
+ return new JSR356Endpoint(this, uri);
+ }
+
+ public void sendMessage(final Session session, final Object message) throws IOException {
+ synchronized (session) {
+ // todo: handle async?
+ if (String.class.isInstance(message)) {
+ session.getBasicRemote().sendText(String.valueOf(message));
+ } else if (ByteBuffer.class.isInstance(message)) {
+ session.getBasicRemote().sendBinary(ByteBuffer.class.cast(message));
+ } else if (InputStream.class.isInstance(message)) {
+ int read;
+ final InputStream in = InputStream.class.cast(message);
+ final byte[] buffer = new byte[8192]; // todo: config
+ final OutputStream out = session.getBasicRemote().getSendStream();
+ while ((read = in.read(buffer)) >= 0) {
+ out.write(buffer, 0, read);
+ }
+ } else {
+ throw new IllegalArgumentException("Unsupported input: " + message);
+ }
+ }
+ }
+
+ public static void registerServer(final String contextPath, final ServerContainer container) {
+ SERVER_CONTAINERS.put(contextPath, new ContextBag(container));
+ }
+
+ public static void unregisterServer(final String contextPath) {
+ SERVER_CONTAINERS.remove(contextPath);
+ }
+
+ public static ContextBag getContext(final String context) {
+ return ofNullable(context)
+ .map(SERVER_CONTAINERS::get)
+ .orElseGet(() -> SERVER_CONTAINERS.size() == 1 ?
+ SERVER_CONTAINERS.values().iterator().next() : SERVER_CONTAINERS.get(""));
+ }
+
+ public static class ContextBag {
+ private final ServerContainer container;
+ private final Map<String, CamelServerEndpoint> endpoints = new HashMap<>();
+
+ private ContextBag(final ServerContainer container) {
+ this.container = container;
+ }
+
+ public ServerContainer getContainer() {
+ return container;
+ }
+
+ public Map<String, CamelServerEndpoint> getEndpoints() {
+ return endpoints;
+ }
+ }
+}
diff --git a/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/ServletIntegration.java b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/ServletIntegration.java
new file mode 100644
index 0000000..660b8b9
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/java/org/apache/camel/jsr356/ServletIntegration.java
@@ -0,0 +1,47 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.jsr356;
+
+import static java.util.Optional.ofNullable;
+
+import java.util.Set;
+
+import javax.servlet.ServletContainerInitializer;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+import javax.websocket.server.ServerContainer;
+
+public class ServletIntegration implements ServletContainerInitializer {
+ @Override
+ public void onStartup(final Set<Class<?>> c, final ServletContext ctx) {
+ ctx.addListener(new ServletContextListener() {
+ @Override
+ public void contextInitialized(final ServletContextEvent sce) {
+ final String contextPath = sce.getServletContext().getContextPath();
+ ofNullable(sce.getServletContext().getAttribute(ServerContainer.class.getName()))
+ .map(ServerContainer.class::cast)
+ .ifPresent(container -> JSR356WebSocketComponent.registerServer(contextPath, container));
+ }
+
+ @Override
+ public void contextDestroyed(final ServletContextEvent sce) {
+ JSR356WebSocketComponent.unregisterServer(sce.getServletContext().getContextPath());
+ }
+ });
+ }
+}
diff --git a/components/camel-websocket-jsr356/src/main/resources/META-INF/LICENSE.txt b/components/camel-websocket-jsr356/src/main/resources/META-INF/LICENSE.txt
new file mode 100644
index 0000000..6b0b127
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/resources/META-INF/LICENSE.txt
@@ -0,0 +1,203 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
diff --git a/components/camel-websocket-jsr356/src/main/resources/META-INF/NOTICE.txt b/components/camel-websocket-jsr356/src/main/resources/META-INF/NOTICE.txt
new file mode 100644
index 0000000..2e215bf
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/resources/META-INF/NOTICE.txt
@@ -0,0 +1,11 @@
+ =========================================================================
+ == NOTICE file corresponding to the section 4 d of ==
+ == the Apache License, Version 2.0, ==
+ == in this case for the Apache Camel distribution. ==
+ =========================================================================
+
+ This product includes software developed by
+ The Apache Software Foundation (http://www.apache.org/).
+
+ Please read the different LICENSE files present in the licenses directory of
+ this distribution.
diff --git a/components/camel-websocket-jsr356/src/main/resources/META-INF/services/javax.servlet.ServletContainerInitializer b/components/camel-websocket-jsr356/src/main/resources/META-INF/services/javax.servlet.ServletContainerInitializer
new file mode 100644
index 0000000..46f0334
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/resources/META-INF/services/javax.servlet.ServletContainerInitializer
@@ -0,0 +1,17 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+org.apache.camel.jsr356.ServletIntegration
diff --git a/components/camel-websocket-jsr356/src/main/resources/META-INF/services/org/apache/camel/component/jsr356 b/components/camel-websocket-jsr356/src/main/resources/META-INF/services/org/apache/camel/component/jsr356
new file mode 100644
index 0000000..60f541e
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/main/resources/META-INF/services/org/apache/camel/component/jsr356
@@ -0,0 +1,17 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+class=org.apache.camel.jsr356.JSR356WebSocketComponent
diff --git a/components/camel-websocket-jsr356/src/test/java/org/apache/camel/jsr356/JSR356ConsumerTest.java b/components/camel-websocket-jsr356/src/test/java/org/apache/camel/jsr356/JSR356ConsumerTest.java
new file mode 100644
index 0000000..2b84b96
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/test/java/org/apache/camel/jsr356/JSR356ConsumerTest.java
@@ -0,0 +1,115 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.jsr356;
+
+import java.io.IOException;
+import java.net.URI;
+
+import javax.enterprise.context.Dependent;
+import javax.websocket.ClientEndpointConfig;
+import javax.websocket.CloseReason;
+import javax.websocket.ContainerProvider;
+import javax.websocket.Endpoint;
+import javax.websocket.EndpointConfig;
+import javax.websocket.OnOpen;
+import javax.websocket.Session;
+import javax.websocket.WebSocketContainer;
+import javax.websocket.server.ServerEndpoint;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.apache.meecrowave.Meecrowave;
+import org.apache.meecrowave.junit.MeecrowaveRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestName;
+
+public class JSR356ConsumerTest extends CamelTestSupport {
+ @Rule
+ public final MeecrowaveRule servlet = new MeecrowaveRule(new Meecrowave.Builder() {{
+ randomHttpPort();
+ setScanningPackageIncludes("org.apache.camel.jsr356.JSR356ConsumerTest$"); // deploy test classes
+ }}, "");
+
+ @Rule
+ public final TestName testName = new TestName();
+
+ @Test
+ public void ensureClientModeReceiveProperlyExchanges() throws Exception {
+ final String message = ExistingServerEndpoint.class.getName() + "#" + testName.getMethodName();
+ final MockEndpoint mockEndpoint = getMockEndpoint("mock:" + testName.getMethodName());
+ mockEndpoint.expectedBodiesReceived(message);
+ ExistingServerEndpoint.self.doSend(); // to avoid lifecycle issue suring startup we send the message only here
+ mockEndpoint.assertIsSatisfied();
+ // note that this test leaks a connection
+ }
+
+ @Test
+ public void ensureServerModeReceiveProperlyExchanges() throws Exception {
+ final String message = getClass().getName() + "#" + testName.getMethodName();
+ final MockEndpoint mockEndpoint = getMockEndpoint("mock:" + testName.getMethodName());
+ mockEndpoint.expectedBodiesReceived(message);
+
+ final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
+ final Session session = container.connectToServer(new Endpoint() {
+ @Override
+ public void onOpen(final Session session, final EndpointConfig config) {
+ // no-op
+ }
+ }, ClientEndpointConfig.Builder.create().build(), URI.create("ws://localhost:" + servlet.getConfiguration().getHttpPort() + "/test"));
+ session.getBasicRemote().sendText(message);
+ session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "bye"));
+
+ mockEndpoint.assertIsSatisfied();
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ public void configure() {
+ from("jsr356:///test")
+ .id("camel_consumer_acts_as_server")
+ .convertBodyTo(String.class)
+ .to("mock:ensureServerModeReceiveProperlyExchanges");
+
+ from("jsr356://ws://localhost:" + servlet.getConfiguration().getHttpPort() + "/existingserver")
+ .id("camel_consumer_acts_as_client")
+ .convertBodyTo(String.class)
+ .to("mock:ensureClientModeReceiveProperlyExchanges");
+ }
+ };
+ }
+
+ @Dependent
+ @ServerEndpoint("/existingserver")
+ public static class ExistingServerEndpoint {
+ private static ExistingServerEndpoint self;
+
+ private Session session;
+
+ @OnOpen
+ public void onOpen(final Session session) {
+ this.session = session;
+ self = this;
+ }
+
+ void doSend() throws IOException {
+ session.getBasicRemote().sendText(getClass().getName() + "#ensureClientModeReceiveProperlyExchanges");
+ }
+ }
+}
diff --git a/components/camel-websocket-jsr356/src/test/java/org/apache/camel/jsr356/JSR356ProducerTest.java b/components/camel-websocket-jsr356/src/test/java/org/apache/camel/jsr356/JSR356ProducerTest.java
new file mode 100644
index 0000000..8e5a3de
--- /dev/null
+++ b/components/camel-websocket-jsr356/src/test/java/org/apache/camel/jsr356/JSR356ProducerTest.java
@@ -0,0 +1,93 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.jsr356;
+
+import static java.util.Collections.singletonList;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.concurrent.CountDownLatch;
+
+import javax.enterprise.context.Dependent;
+import javax.websocket.OnMessage;
+import javax.websocket.OnOpen;
+import javax.websocket.Session;
+import javax.websocket.server.ServerEndpoint;
+
+import org.apache.camel.Produce;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.apache.meecrowave.Meecrowave;
+import org.apache.meecrowave.junit.MeecrowaveRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestName;
+
+public class JSR356ProducerTest extends CamelTestSupport {
+ @Rule
+ public final MeecrowaveRule servlet = new MeecrowaveRule(new Meecrowave.Builder() {{
+ randomHttpPort();
+ setScanningPackageIncludes("org.apache.camel.jsr356.JSR356ProducerTest$"); // deploy test classes
+ }}, "");
+
+ @Rule
+ public final TestName testName = new TestName();
+
+ @Produce(uri = "direct:ensureServerModeSendsProperly")
+ private ProducerTemplate serverProducer;
+
+ @Test
+ public void ensureServerModeSendsProperly() throws Exception {
+ final String body = getClass().getName() + "#" + testName.getMethodName();
+ serverProducer.sendBody(body);
+ ExistingServerEndpoint.self.latch.await();
+ assertEquals(singletonList(body), ExistingServerEndpoint.self.messages);
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ public void configure() {
+ from("direct:ensureServerModeSendsProperly")
+ .id("camel_consumer_acts_as_client")
+ .convertBodyTo(String.class)
+ .to("jsr356://ws://localhost:" + servlet.getConfiguration().getHttpPort() + "/existingserver");
+ }
+ };
+ }
+
+ @Dependent
+ @ServerEndpoint("/existingserver")
+ public static class ExistingServerEndpoint {
+ private static ExistingServerEndpoint self;
+
+ private final Collection<String> messages = new ArrayList<>();
+ private final CountDownLatch latch = new CountDownLatch(1);
+
+ @OnOpen
+ public void onOpen(final Session session) {
+ self = this;
+ }
+
+ @OnMessage
+ public synchronized void onMessage(final String message) {
+ messages.add(message);
+ latch.countDown();
+ }
+ }
+}
diff --git a/components/pom.xml b/components/pom.xml
index 375a5d0..4175334 100644
--- a/components/pom.xml
+++ b/components/pom.xml
@@ -334,6 +334,7 @@
<module>camel-zipkin</module>
<module>camel-zookeeper</module>
<module>camel-zookeeper-master</module>
+ <module>camel-websocket-jsr356</module>
</modules>