This is an automated email from the ASF dual-hosted git repository.

jamesnetherton pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 824080960f1 CAMEL-18981: Add capability to vertx-websocket server for 
capturing peer connect / disconnect events
824080960f1 is described below

commit 824080960f11bccb34907fdd56bcfd788647b618
Author: James Netherton <[email protected]>
AuthorDate: Wed Feb 8 10:40:03 2023 +0000

    CAMEL-18981: Add capability to vertx-websocket server for capturing peer 
connect / disconnect events
---
 .../VertxWebsocketEndpointConfigurer.java          |   6 ++
 .../VertxWebsocketEndpointUriFactory.java          |   3 +-
 .../component/vertx/websocket/vertx-websocket.json |   4 +-
 .../websocket/VertxWebsocketConfiguration.java     |  13 +++
 .../vertx/websocket/VertxWebsocketConstants.java   |   4 +-
 .../vertx/websocket/VertxWebsocketConsumer.java    |  28 +++++-
 .../vertx/websocket/VertxWebsocketEvent.java       |  42 +++++++++
 .../vertx/websocket/VertxWebsocketHost.java        |   9 ++
 .../vertx/websocket/VertxWebSocketEventTest.java   | 103 +++++++++++++++++++++
 9 files changed, 206 insertions(+), 6 deletions(-)

diff --git 
a/components/camel-vertx/camel-vertx-websocket/src/generated/java/org/apache/camel/component/vertx/websocket/VertxWebsocketEndpointConfigurer.java
 
b/components/camel-vertx/camel-vertx-websocket/src/generated/java/org/apache/camel/component/vertx/websocket/VertxWebsocketEndpointConfigurer.java
index 171b587c15f..0b0e2639731 100644
--- 
a/components/camel-vertx/camel-vertx-websocket/src/generated/java/org/apache/camel/component/vertx/websocket/VertxWebsocketEndpointConfigurer.java
+++ 
b/components/camel-vertx/camel-vertx-websocket/src/generated/java/org/apache/camel/component/vertx/websocket/VertxWebsocketEndpointConfigurer.java
@@ -35,6 +35,8 @@ public class VertxWebsocketEndpointConfigurer extends 
PropertyConfigurerSupport
         case "exceptionHandler": 
target.setExceptionHandler(property(camelContext, 
org.apache.camel.spi.ExceptionHandler.class, value)); return true;
         case "exchangepattern":
         case "exchangePattern": 
target.setExchangePattern(property(camelContext, 
org.apache.camel.ExchangePattern.class, value)); return true;
+        case "firewebsocketconnectionevents":
+        case "fireWebSocketConnectionEvents": 
target.getConfiguration().setFireWebSocketConnectionEvents(property(camelContext,
 boolean.class, value)); return true;
         case "lazystartproducer":
         case "lazyStartProducer": 
target.setLazyStartProducer(property(camelContext, boolean.class, value)); 
return true;
         case "maxreconnectattempts":
@@ -71,6 +73,8 @@ public class VertxWebsocketEndpointConfigurer extends 
PropertyConfigurerSupport
         case "exceptionHandler": return 
org.apache.camel.spi.ExceptionHandler.class;
         case "exchangepattern":
         case "exchangePattern": return org.apache.camel.ExchangePattern.class;
+        case "firewebsocketconnectionevents":
+        case "fireWebSocketConnectionEvents": return boolean.class;
         case "lazystartproducer":
         case "lazyStartProducer": return boolean.class;
         case "maxreconnectattempts":
@@ -108,6 +112,8 @@ public class VertxWebsocketEndpointConfigurer extends 
PropertyConfigurerSupport
         case "exceptionHandler": return target.getExceptionHandler();
         case "exchangepattern":
         case "exchangePattern": return target.getExchangePattern();
+        case "firewebsocketconnectionevents":
+        case "fireWebSocketConnectionEvents": return 
target.getConfiguration().isFireWebSocketConnectionEvents();
         case "lazystartproducer":
         case "lazyStartProducer": return target.isLazyStartProducer();
         case "maxreconnectattempts":
diff --git 
a/components/camel-vertx/camel-vertx-websocket/src/generated/java/org/apache/camel/component/vertx/websocket/VertxWebsocketEndpointUriFactory.java
 
b/components/camel-vertx/camel-vertx-websocket/src/generated/java/org/apache/camel/component/vertx/websocket/VertxWebsocketEndpointUriFactory.java
index 163e74fa89c..4d183895da1 100644
--- 
a/components/camel-vertx/camel-vertx-websocket/src/generated/java/org/apache/camel/component/vertx/websocket/VertxWebsocketEndpointUriFactory.java
+++ 
b/components/camel-vertx/camel-vertx-websocket/src/generated/java/org/apache/camel/component/vertx/websocket/VertxWebsocketEndpointUriFactory.java
@@ -21,7 +21,7 @@ public class VertxWebsocketEndpointUriFactory extends 
org.apache.camel.support.c
     private static final Set<String> SECRET_PROPERTY_NAMES;
     private static final Set<String> MULTI_VALUE_PREFIXES;
     static {
-        Set<String> props = new HashSet<>(18);
+        Set<String> props = new HashSet<>(19);
         props.add("allowedOriginPattern");
         props.add("bridgeErrorHandler");
         props.add("clientOptions");
@@ -29,6 +29,7 @@ public class VertxWebsocketEndpointUriFactory extends 
org.apache.camel.support.c
         props.add("consumeAsClient");
         props.add("exceptionHandler");
         props.add("exchangePattern");
+        props.add("fireWebSocketConnectionEvents");
         props.add("host");
         props.add("lazyStartProducer");
         props.add("maxReconnectAttempts");
diff --git 
a/components/camel-vertx/camel-vertx-websocket/src/generated/resources/org/apache/camel/component/vertx/websocket/vertx-websocket.json
 
b/components/camel-vertx/camel-vertx-websocket/src/generated/resources/org/apache/camel/component/vertx/websocket/vertx-websocket.json
index 94dbf67af3c..dacb80e6c57 100644
--- 
a/components/camel-vertx/camel-vertx-websocket/src/generated/resources/org/apache/camel/component/vertx/websocket/vertx-websocket.json
+++ 
b/components/camel-vertx/camel-vertx-websocket/src/generated/resources/org/apache/camel/component/vertx/websocket/vertx-websocket.json
@@ -33,7 +33,8 @@
   "headers": {
     "CamelVertxWebsocket.connectionKey": { "kind": "header", "displayName": 
"", "group": "common", "label": "", "required": false, "javaType": "String", 
"deprecated": false, "deprecationNote": "", "autowired": false, "secret": 
false, "description": "Sends the message to the client with the given 
connection key. You can use a comma separated list of keys to send a message to 
multiple clients", "constantName": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConstants#CONNECTION_KEY"
 },
     "CamelVertxWebsocket.sendToAll": { "kind": "header", "displayName": "", 
"group": "producer", "label": "producer", "required": false, "javaType": 
"boolean", "deprecated": false, "deprecationNote": "", "autowired": false, 
"secret": false, "description": "Sends the message to all clients which are 
currently connected. You can use the sendToAll option on the endpoint instead 
of using this header.", "constantName": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConstants#SEND_T [...]
-    "CamelVertxWebsocket.remoteAddress": { "kind": "header", "displayName": 
"", "group": "consumer", "label": "consumer", "required": false, "javaType": 
"io.vertx.core.net.SocketAddress", "deprecated": false, "deprecationNote": "", 
"autowired": false, "secret": false, "description": "The remote address.", 
"constantName": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConstants#REMOTE_ADDRESS"
 }
+    "CamelVertxWebsocket.remoteAddress": { "kind": "header", "displayName": 
"", "group": "consumer", "label": "consumer", "required": false, "javaType": 
"io.vertx.core.net.SocketAddress", "deprecated": false, "deprecationNote": "", 
"autowired": false, "secret": false, "description": "The remote address.", 
"constantName": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConstants#REMOTE_ADDRESS"
 },
+    "CamelVertxWebsocket.event": { "kind": "header", "displayName": "", 
"group": "consumer", "label": "consumer", "required": false, "javaType": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketEvent", "enum": [ 
"CLOSE", "ERROR", "MESSAGE", "OPEN" ], "deprecated": false, "deprecationNote": 
"", "autowired": false, "secret": false, "description": "The WebSocket event 
that triggered the message exchange.", "constantName": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketCo [...]
   },
   "properties": {
     "host": { "kind": "path", "displayName": "Host", "group": "common", 
"label": "", "required": true, "type": "string", "javaType": 
"java.lang.String", "deprecated": false, "deprecationNote": "", "autowired": 
false, "secret": false, "configurationClass": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConfiguration", 
"configurationField": "configuration", "description": "WebSocket hostname, such 
as localhost or a remote host when in client mode." },
@@ -41,6 +42,7 @@
     "path": { "kind": "path", "displayName": "Path", "group": "common", 
"label": "", "required": false, "type": "string", "javaType": 
"java.lang.String", "deprecated": false, "autowired": false, "secret": false, 
"configurationClass": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConfiguration", 
"configurationField": "configuration", "description": "WebSocket path to use." 
},
     "allowedOriginPattern": { "kind": "parameter", "displayName": "Allowed 
Origin Pattern", "group": "consumer", "label": "consumer", "required": false, 
"type": "string", "javaType": "java.lang.String", "deprecated": false, 
"autowired": false, "secret": false, "configurationClass": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConfiguration", 
"configurationField": "configuration", "description": "Regex pattern to match 
the origin header sent by WebSocket clients" },
     "consumeAsClient": { "kind": "parameter", "displayName": "Consume As 
Client", "group": "consumer", "label": "consumer", "required": false, "type": 
"boolean", "javaType": "boolean", "deprecated": false, "autowired": false, 
"secret": false, "defaultValue": false, "configurationClass": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConfiguration", 
"configurationField": "configuration", "description": "When set to true, the 
consumer acts as a WebSocket client, creating exchang [...]
+    "fireWebSocketConnectionEvents": { "kind": "parameter", "displayName": 
"Fire Web Socket Connection Events", "group": "consumer", "label": "consumer", 
"required": false, "type": "boolean", "javaType": "boolean", "deprecated": 
false, "autowired": false, "secret": false, "defaultValue": false, 
"configurationClass": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConfiguration", 
"configurationField": "configuration", "description": "Whether the server 
consumer will create a mes [...]
     "maxReconnectAttempts": { "kind": "parameter", "displayName": "Max 
Reconnect Attempts", "group": "consumer", "label": "consumer", "required": 
false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": 
false, "secret": false, "defaultValue": 0, "configurationClass": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConfiguration", 
"configurationField": "configuration", "description": "When consumeAsClient is 
set to true this sets the maximum number of allow [...]
     "reconnectInitialDelay": { "kind": "parameter", "displayName": "Reconnect 
Initial Delay", "group": "consumer", "label": "consumer", "required": false, 
"type": "integer", "javaType": "int", "deprecated": false, "autowired": false, 
"secret": false, "defaultValue": 0, "configurationClass": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConfiguration", 
"configurationField": "configuration", "description": "When consumeAsClient is 
set to true this sets the initial delay in mill [...]
     "reconnectInterval": { "kind": "parameter", "displayName": "Reconnect 
Interval", "group": "consumer", "label": "consumer", "required": false, "type": 
"integer", "javaType": "int", "deprecated": false, "autowired": false, 
"secret": false, "defaultValue": 1000, "configurationClass": 
"org.apache.camel.component.vertx.websocket.VertxWebsocketConfiguration", 
"configurationField": "configuration", "description": "When consumeAsClient is 
set to true this sets the interval in milliseconds at [...]
diff --git 
a/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConfiguration.java
 
b/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConfiguration.java
index 1d13ff2dc46..517db2dc311 100644
--- 
a/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConfiguration.java
+++ 
b/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConfiguration.java
@@ -62,6 +62,8 @@ public class VertxWebsocketConfiguration {
     private String clientSubProtocols;
     @UriParam(label = "security")
     private SSLContextParameters sslContextParameters;
+    @UriParam(label = "consumer")
+    private boolean fireWebSocketConnectionEvents;
 
     /**
      * The WebSocket URI address to use.
@@ -234,4 +236,15 @@ public class VertxWebsocketConfiguration {
     public String getClientSubProtocols() {
         return clientSubProtocols;
     }
+
+    /**
+     * Whether the server consumer will create a message exchange when a new 
WebSocket peer connects or disconnects
+     */
+    public void setFireWebSocketConnectionEvents(boolean 
fireWebSocketConnectionEvents) {
+        this.fireWebSocketConnectionEvents = fireWebSocketConnectionEvents;
+    }
+
+    public boolean isFireWebSocketConnectionEvents() {
+        return fireWebSocketConnectionEvents;
+    }
 }
diff --git 
a/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConstants.java
 
b/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConstants.java
index 1df5ba129a2..98fd0692e71 100644
--- 
a/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConstants.java
+++ 
b/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConstants.java
@@ -23,7 +23,6 @@ public final class VertxWebsocketConstants {
 
     public static final String DEFAULT_VERTX_SERVER_HOST = 
NetServerOptions.DEFAULT_HOST;
     public static final int DEFAULT_VERTX_SERVER_PORT = 
NetServerOptions.DEFAULT_PORT;
-    public static final String DEFAULT_VERTX_SERVER_PATH = "/";
 
     @Metadata(description = "Sends the message to the client with the given 
connection key. You can\n" +
                             "use a comma separated list of keys to send a 
message to multiple clients",
@@ -35,6 +34,9 @@ public final class VertxWebsocketConstants {
     public static final String SEND_TO_ALL = "CamelVertxWebsocket.sendToAll";
     @Metadata(label = "consumer", description = "The remote address.", 
javaType = "io.vertx.core.net.SocketAddress")
     public static final String REMOTE_ADDRESS = 
"CamelVertxWebsocket.remoteAddress";
+    @Metadata(label = "consumer", description = "The WebSocket event that 
triggered the message exchange.",
+              javaType = 
"org.apache.camel.component.vertx.websocket.VertxWebsocketEvent")
+    public static final String EVENT = "CamelVertxWebsocket.event";
 
     private VertxWebsocketConstants() {
     }
diff --git 
a/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConsumer.java
 
b/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConsumer.java
index 61b4f9e4c6d..39cd8de9db0 100644
--- 
a/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConsumer.java
+++ 
b/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketConsumer.java
@@ -18,6 +18,7 @@ package org.apache.camel.component.vertx.websocket;
 
 import java.util.Map;
 
+import io.vertx.core.http.ServerWebSocket;
 import io.vertx.core.net.SocketAddress;
 import io.vertx.core.net.impl.ConnectionBase;
 import io.vertx.ext.web.RoutingContext;
@@ -63,7 +64,7 @@ public class VertxWebsocketConsumer extends DefaultConsumer {
     public void onMessage(String connectionKey, Object message, SocketAddress 
remote, RoutingContext routingContext) {
         Exchange exchange = createExchange(true);
         exchange.getMessage().setBody(message);
-        populateExchangeHeaders(exchange, connectionKey, remote, 
routingContext);
+        populateExchangeHeaders(exchange, connectionKey, remote, 
routingContext, VertxWebsocketEvent.MESSAGE);
 
         // use default consumer callback
         AsyncCallback cb = defaultConsumerCallback(exchange, true);
@@ -77,18 +78,39 @@ public class VertxWebsocketConsumer extends DefaultConsumer 
{
         }
 
         Exchange exchange = createExchange(false);
-        populateExchangeHeaders(exchange, connectionKey, remote, 
routingContext);
+        populateExchangeHeaders(exchange, connectionKey, remote, 
routingContext, VertxWebsocketEvent.ERROR);
 
         getExceptionHandler().handleException("Error processing exchange", 
exchange, cause);
         releaseExchange(exchange, false);
     }
 
+    public void onOpen(String connectionKey, SocketAddress remote, 
RoutingContext routingContext, ServerWebSocket webSocket) {
+        Exchange exchange = createExchange(true);
+        populateExchangeHeaders(exchange, connectionKey, remote, 
routingContext, VertxWebsocketEvent.OPEN);
+        exchange.getMessage().setBody(webSocket);
+
+        // use default consumer callback
+        AsyncCallback cb = defaultConsumerCallback(exchange, true);
+        getAsyncProcessor().process(exchange, cb);
+    }
+
+    public void onClose(String connectionKey, SocketAddress remote, 
RoutingContext routingContext) {
+        Exchange exchange = createExchange(true);
+        populateExchangeHeaders(exchange, connectionKey, remote, 
routingContext, VertxWebsocketEvent.CLOSE);
+
+        // use default consumer callback
+        AsyncCallback cb = defaultConsumerCallback(exchange, true);
+        getAsyncProcessor().process(exchange, cb);
+    }
+
     protected void populateExchangeHeaders(
-            Exchange exchange, String connectionKey, SocketAddress remote, 
RoutingContext routingContext) {
+            Exchange exchange, String connectionKey, SocketAddress remote, 
RoutingContext routingContext,
+            VertxWebsocketEvent event) {
         Message message = exchange.getMessage();
         Map<String, Object> headers = message.getHeaders();
         message.setHeader(VertxWebsocketConstants.REMOTE_ADDRESS, remote);
         message.setHeader(VertxWebsocketConstants.CONNECTION_KEY, 
connectionKey);
+        message.setHeader(VertxWebsocketConstants.EVENT, event);
         routingContext.queryParams()
                 .forEach((name, value) -> 
VertxWebsocketHelper.appendHeader(headers, name, value));
         routingContext.pathParams()
diff --git 
a/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketEvent.java
 
b/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketEvent.java
new file mode 100644
index 00000000000..69c2d89ff69
--- /dev/null
+++ 
b/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketEvent.java
@@ -0,0 +1,42 @@
+/*
+ * 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.component.vertx.websocket;
+
+/**
+ * Events that may be fired during the lifecycle of a WebSocket
+ */
+public enum VertxWebsocketEvent {
+    /**
+     * The WebSocket connection was closed.
+     */
+    CLOSE,
+
+    /**
+     * An error was encountered with the WebSocket.
+     */
+    ERROR,
+
+    /**
+     * The WebSocket received a message.
+     */
+    MESSAGE,
+
+    /**
+     * The WebSocket connection was opened.
+     */
+    OPEN
+}
diff --git 
a/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketHost.java
 
b/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketHost.java
index b0e93b90936..411e32c4090 100644
--- 
a/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketHost.java
+++ 
b/components/camel-vertx/camel-vertx-websocket/src/main/java/org/apache/camel/component/vertx/websocket/VertxWebsocketHost.java
@@ -133,8 +133,17 @@ public class VertxWebsocketHost {
                                     LOG.debug("WebSocket peer {} disconnected 
from {}", connectionKey, socketAddress.host());
                                 }
                             }
+
+                            if 
(configuration.isFireWebSocketConnectionEvents()) {
+                                consumer.onClose(connectionKey, remote, 
routingContext);
+                            }
+
                             connectedPeers.remove(connectionKey);
                         });
+
+                        if (configuration.isFireWebSocketConnectionEvents()) {
+                            consumer.onOpen(connectionKey, remote, 
routingContext, webSocket);
+                        }
                     } else {
                         // the upgrade failed
                         routingContext.fail(toWebSocket.cause());
diff --git 
a/components/camel-vertx/camel-vertx-websocket/src/test/java/org/apache/camel/component/vertx/websocket/VertxWebSocketEventTest.java
 
b/components/camel-vertx/camel-vertx-websocket/src/test/java/org/apache/camel/component/vertx/websocket/VertxWebSocketEventTest.java
new file mode 100644
index 00000000000..ec581d33730
--- /dev/null
+++ 
b/components/camel-vertx/camel-vertx-websocket/src/test/java/org/apache/camel/component/vertx/websocket/VertxWebSocketEventTest.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.component.vertx.websocket;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import io.vertx.core.http.HttpServerOptions;
+import io.vertx.core.http.ServerWebSocket;
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.Message;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class VertxWebSocketEventTest extends VertxWebSocketTestSupport {
+
+    private static final String MESSAGE_BODY = "Hello World";
+    private ServerWebSocket webSocket;
+
+    @BindToRegistry("serverOptions")
+    public HttpServerOptions serverOptions() {
+        HttpServerOptions options = new HttpServerOptions();
+        options.setMaxWebSocketMessageSize(MESSAGE_BODY.length());
+        return options;
+    }
+
+    @Test
+    void webSocketEvents() throws Exception {
+        MockEndpoint mockEndpoint = getMockEndpoint("mock:result");
+        mockEndpoint.expectedBodiesReceived("WebSocket Open", "WebSocket 
Message", "WebSocket Error", "WebSocket Close");
+
+        template.sendBody("vertx-websocket:localhost:" + port + "/test", 
MESSAGE_BODY);
+
+        assertNotNull(webSocket);
+
+        // Trigger error event (message length > max allowed)
+        template.sendBody("vertx-websocket:localhost:" + port + "/test", 
MESSAGE_BODY + " Again");
+
+        // Trigger close event
+        CountDownLatch latch = new CountDownLatch(1);
+        webSocket.close(event -> latch.countDown());
+        assertTrue(latch.await(5, TimeUnit.SECONDS));
+
+        mockEndpoint.assertIsSatisfied();
+    }
+
+    @Override
+    protected RoutesBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                onException(IllegalStateException.class)
+                        .handled(true)
+                        .choice()
+                        .when(simple("${header.CamelVertxWebsocket.event} == 
'ERROR'"))
+                        .setBody().constant("WebSocket Error")
+                        .to("mock:result")
+                        .endChoice();
+
+                
fromF("vertx-websocket:localhost:%d/test?fireWebSocketConnectionEvents=true&serverOptions=#serverOptions&bridgeErrorHandler=true",
+                        port)
+                        .choice()
+                        .when(simple("${header.CamelVertxWebsocket.event} == 
'OPEN'"))
+                        .process(exchange -> {
+                            Message message = exchange.getMessage();
+                            webSocket = message.getBody(ServerWebSocket.class);
+                        })
+                        .setBody().constant("WebSocket Open")
+                        .to("mock:result")
+                        .endChoice()
+
+                        .when(simple("${header.CamelVertxWebsocket.event} == 
'MESSAGE'"))
+                        .setBody().constant("WebSocket Message")
+                        .to("mock:result")
+                        .endChoice()
+
+                        .when(simple("${header.CamelVertxWebsocket.event} == 
'CLOSE'"))
+                        .setBody().constant("WebSocket Close")
+                        .to("mock:result")
+                        .endChoice();
+            }
+        };
+    }
+}

Reply via email to