This is an automated email from the ASF dual-hosted git repository.
davsclaus 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 27efa340d2df CAMEL-26922: camel-atmosphere-websocket - the open, close
and error events carry the query parameters of their own connection (#29845)
27efa340d2df is described below
commit 27efa340d2df785022a74cc27043416b7f790fa1
Author: Claus Ibsen <[email protected]>
AuthorDate: Sun Nov 15 23:07:38 2026 +0100
CAMEL-26922: camel-atmosphere-websocket - the open, close and error events
carry the query parameters of their own connection (#29845)
* CAMEL-26922: camel-atmosphere-websocket - the open, close and error e…
…vents carry the query parameters of their own connection
The query parameters on the open, close and error event exchanges (servlet
init-param events=true) came from the last HTTP request that the servlet
handled, not from the websocket connection of the event. With the JSR 356
transport the parameters of the connection did not reach its events, and
the values were not URL-decoded.
The handler now takes the query parameters from the request that opened the
connection, keeps them by connection key until the connection closes, and
sets them on every event of that connection. Names and values are
URL-decoded.
* CAMEL-26922: camel-atmosphere-websocket - docs wording of the connect…
…ion key header
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Claus Ibsen <[email protected]>
---
.../docs/atmosphere-websocket-component.adoc | 11 ++
.../main/docs/atmosphere-websocket-component.adoc | 11 ++
.../atmosphere/websocket/WebsocketConsumer.java | 19 ++-
.../atmosphere/websocket/WebsocketHandler.java | 19 ++-
.../WebsocketEventQueryParameterTest.java | 141 +++++++++++++++++++++
.../websocket/WebsocketQueryParameterTest.java | 7 +
.../WebsocketRoute1WithInitParamTest.java | 35 ++---
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 10 ++
8 files changed, 224 insertions(+), 29 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/atmosphere-websocket-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/atmosphere-websocket-component.adoc
index 2ba2242b6d68..a48929cc2ff2 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/atmosphere-websocket-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/atmosphere-websocket-component.adoc
@@ -45,6 +45,17 @@ An atmopshere-websocket endpoint can either write data to
the socket or
read from the socket, depending on whether the endpoint is configured as
the producer or the consumer, respectively.
+== Connection Events
+
+When the init-param `events` of the `CamelWebSocketServlet` is set to `true`,
the consumer also routes an exchange,
+without a body, when a websocket connection opens, closes or fails. The
`CamelAtmosphereWebsocketEventType` header
+holds the type of the event (`1` open, `0` close, `-1` error), and the
`CamelAtmosphereWebsocketConnectionKey` header
+holds the key of the connection.
+
+The query parameters of the request that opened the connection are set as
headers on the events of that
+connection, with their names and values URL-decoded. The header filter
strategy of the endpoint applies, so for
+example a parameter whose name starts with `Camel` is not set as a header.
+
== Examples
=== Consumer Example
diff --git
a/components/camel-atmosphere-websocket/src/main/docs/atmosphere-websocket-component.adoc
b/components/camel-atmosphere-websocket/src/main/docs/atmosphere-websocket-component.adoc
index 2ba2242b6d68..a48929cc2ff2 100644
---
a/components/camel-atmosphere-websocket/src/main/docs/atmosphere-websocket-component.adoc
+++
b/components/camel-atmosphere-websocket/src/main/docs/atmosphere-websocket-component.adoc
@@ -45,6 +45,17 @@ An atmopshere-websocket endpoint can either write data to
the socket or
read from the socket, depending on whether the endpoint is configured as
the producer or the consumer, respectively.
+== Connection Events
+
+When the init-param `events` of the `CamelWebSocketServlet` is set to `true`,
the consumer also routes an exchange,
+without a body, when a websocket connection opens, closes or fails. The
`CamelAtmosphereWebsocketEventType` header
+holds the type of the event (`1` open, `0` close, `-1` error), and the
`CamelAtmosphereWebsocketConnectionKey` header
+holds the key of the connection.
+
+The query parameters of the request that opened the connection are set as
headers on the events of that
+connection, with their names and values URL-decoded. The header filter
strategy of the endpoint applies, so for
+example a parameter whose name starts with `Camel` is not set as a header.
+
== Examples
=== Consumer Example
diff --git
a/components/camel-atmosphere-websocket/src/main/java/org/apache/camel/component/atmosphere/websocket/WebsocketConsumer.java
b/components/camel-atmosphere-websocket/src/main/java/org/apache/camel/component/atmosphere/websocket/WebsocketConsumer.java
index 2042987b35cb..f3ff15ea204c 100644
---
a/components/camel-atmosphere-websocket/src/main/java/org/apache/camel/component/atmosphere/websocket/WebsocketConsumer.java
+++
b/components/camel-atmosphere-websocket/src/main/java/org/apache/camel/component/atmosphere/websocket/WebsocketConsumer.java
@@ -17,6 +17,8 @@
package org.apache.camel.component.atmosphere.websocket;
import java.io.IOException;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -43,7 +45,6 @@ import org.atmosphere.websocket.WebSocketProtocol;
*/
public class WebsocketConsumer extends ServletConsumer {
private boolean enableEventsResending;
- private Map<String, String> queryMap = new HashMap<>();
private AtmosphereFramework framework;
private final AtmosphereFrameworkInitializer initializer;
@@ -81,7 +82,6 @@ public class WebsocketConsumer extends ServletConsumer {
}
void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
- this.queryMap = getQueryMap(request.getQueryString());
framework.doCometSupport(AtmosphereRequestImpl.wrap(request),
AtmosphereResponseImpl.wrap(response));
}
@@ -97,7 +97,7 @@ public class WebsocketConsumer extends ServletConsumer {
getAsyncProcessor().process(exchange, cb);
}
- public void sendEventNotification(String connectionKey, int eventType) {
+ public void sendEventNotification(String connectionKey, int eventType,
Map<String, String> queryParameters) {
final Exchange exchange = createExchange(true);
// set header
@@ -105,7 +105,7 @@ public class WebsocketConsumer extends ServletConsumer {
exchange.getIn().setHeader(WebsocketConstants.EVENT_TYPE, eventType);
HeaderFilterStrategy headerFilterStrategy =
getEndpoint().getHeaderFilterStrategy();
- for (Map.Entry<String, String> param : queryMap.entrySet()) {
+ for (Map.Entry<String, String> param : queryParameters.entrySet()) {
if (headerFilterStrategy == null
||
!headerFilterStrategy.applyFilterToExternalHeaders(param.getKey(),
param.getValue(), exchange)) {
exchange.getIn().setHeader(param.getKey(), param.getValue());
@@ -144,9 +144,18 @@ public class WebsocketConsumer extends ServletConsumer {
}
// a parameter without a value (?foo or ?foo=) gets an empty
value, and a value may contain =
String[] nameval = param.split("=", 2);
- map.put(nameval[0], nameval.length > 1 ? nameval[1] : "");
+ map.put(decode(nameval[0]), nameval.length > 1 ?
decode(nameval[1]) : "");
}
}
return map;
}
+
+ private static String decode(String text) {
+ try {
+ return URLDecoder.decode(text, StandardCharsets.UTF_8);
+ } catch (IllegalArgumentException e) {
+ // not valid URL encoding, so keep the text as is
+ return text;
+ }
+ }
}
diff --git
a/components/camel-atmosphere-websocket/src/main/java/org/apache/camel/component/atmosphere/websocket/WebsocketHandler.java
b/components/camel-atmosphere-websocket/src/main/java/org/apache/camel/component/atmosphere/websocket/WebsocketHandler.java
index 8be84fffbf6f..92aee087d536 100644
---
a/components/camel-atmosphere-websocket/src/main/java/org/apache/camel/component/atmosphere/websocket/WebsocketHandler.java
+++
b/components/camel-atmosphere-websocket/src/main/java/org/apache/camel/component/atmosphere/websocket/WebsocketHandler.java
@@ -17,10 +17,13 @@
package org.apache.camel.component.atmosphere.websocket;
import java.util.List;
+import java.util.Map;
import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
import org.atmosphere.cpr.AtmosphereConfig;
import org.atmosphere.cpr.AtmosphereRequest;
+import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.websocket.WebSocket;
import org.atmosphere.websocket.WebSocketProcessor.WebSocketException;
import org.atmosphere.websocket.WebSocketProtocol;
@@ -32,6 +35,8 @@ public class WebsocketHandler implements WebSocketProtocol {
protected WebsocketConsumer consumer;
protected WebSocketStore store;
+ // the query parameters of the request that opened each connection, by
connection key
+ private final Map<String, Map<String, String>> queryParameters = new
ConcurrentHashMap<>();
@Override
public void configure(AtmosphereConfig config) {
@@ -44,6 +49,9 @@ public class WebsocketHandler implements WebSocketProtocol {
String connectionKey = store.getConnectionKey(webSocket);
sendEventNotification(connectionKey,
WebsocketConstants.ONCLOSE_EVENT_TYPE);
store.removeWebSocket(webSocket);
+ if (connectionKey != null) {
+ queryParameters.remove(connectionKey);
+ }
LOG.debug("websocket closed");
}
@@ -59,6 +67,9 @@ public class WebsocketHandler implements WebSocketProtocol {
LOG.debug("opening websocket");
String connectionKey = UUID.randomUUID().toString();
store.addWebSocket(connectionKey, webSocket);
+ if (consumer.isEnableEventsResending()) {
+ queryParameters.put(connectionKey,
WebsocketConsumer.getQueryMap(getQueryString(webSocket)));
+ }
sendEventNotification(connectionKey,
WebsocketConstants.ONOPEN_EVENT_TYPE);
LOG.debug("websocket opened");
}
@@ -95,7 +106,13 @@ public class WebsocketHandler implements WebSocketProtocol {
private void sendEventNotification(final String connectionKey, final int
eventType) {
if (consumer.isEnableEventsResending()) {
- consumer.sendEventNotification(connectionKey, eventType);
+ Map<String, String> params = connectionKey != null ?
queryParameters.get(connectionKey) : null;
+ consumer.sendEventNotification(connectionKey, eventType, params !=
null ? params : Map.of());
}
}
+
+ private static String getQueryString(WebSocket webSocket) {
+ AtmosphereResource resource = webSocket.resource();
+ return resource != null ? resource.getRequest().getQueryString() :
null;
+ }
}
diff --git
a/components/camel-atmosphere-websocket/src/test/java/org/apache/camel/component/atmosphere/websocket/WebsocketEventQueryParameterTest.java
b/components/camel-atmosphere-websocket/src/test/java/org/apache/camel/component/atmosphere/websocket/WebsocketEventQueryParameterTest.java
new file mode 100644
index 000000000000..f91d6a58aa69
--- /dev/null
+++
b/components/camel-atmosphere-websocket/src/test/java/org/apache/camel/component/atmosphere/websocket/WebsocketEventQueryParameterTest.java
@@ -0,0 +1,141 @@
+/*
+ * 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.atmosphere.websocket;
+
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Message;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.infra.common.http.WebsocketTestClient;
+import org.awaitility.Awaitility;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+/**
+ * The open, close and error events of a connection carry the query parameters
of the request that opened that
+ * connection.
+ */
+public class WebsocketEventQueryParameterTest extends
WebsocketCamelRouterWithInitParamTestSupport {
+
+ @Test
+ void openEventHasQueryParametersOfItsConnection() {
+ MockEndpoint mock = getMockEndpoint("mock:events");
+
+ WebsocketTestClient clientA = connect("?client=a");
+ awaitEvents(mock, 1);
+ WebsocketTestClient clientB = connect("?client=b");
+ awaitEvents(mock, 2);
+
+ Message openA = event(mock, WebsocketConstants.ONOPEN_EVENT_TYPE, 0);
+ Message openB = event(mock, WebsocketConstants.ONOPEN_EVENT_TYPE, 1);
+ assertEquals("a", openA.getHeader("client"));
+ assertEquals("b", openB.getHeader("client"));
+ assertNotEquals(openA.getHeader(WebsocketConstants.CONNECTION_KEY),
openB.getHeader(WebsocketConstants.CONNECTION_KEY));
+
+ clientA.close();
+ clientB.close();
+ }
+
+ @Test
+ void closeEventHasQueryParametersOfItsConnection() {
+ MockEndpoint mock = getMockEndpoint("mock:events");
+
+ WebsocketTestClient clientA = connect("?client=a");
+ awaitEvents(mock, 1);
+ WebsocketTestClient clientB = connect("?client=b");
+ awaitEvents(mock, 2);
+ clientA.close();
+ awaitEvents(mock, 3);
+
+ Message openA = event(mock, WebsocketConstants.ONOPEN_EVENT_TYPE, 0);
+ Message closeA = event(mock, WebsocketConstants.ONCLOSE_EVENT_TYPE, 0);
+ assertEquals(openA.getHeader(WebsocketConstants.CONNECTION_KEY),
closeA.getHeader(WebsocketConstants.CONNECTION_KEY));
+ assertEquals("a", closeA.getHeader("client"));
+
+ clientB.close();
+ }
+
+ @Test
+ void plainHttpRequestDoesNotChangeEventHeaders() throws Exception {
+ MockEndpoint mock = getMockEndpoint("mock:events");
+
+ WebsocketTestClient clientA = connect("?client=a");
+ awaitEvents(mock, 1);
+
+ try (HttpClient client = HttpClient.newHttpClient()) {
+ HttpRequest request =
HttpRequest.newBuilder(URI.create("http://localhost:" + PORT +
"/events?client=other"))
+ .build();
+ client.send(request, HttpResponse.BodyHandlers.ofString());
+ }
+
+ clientA.close();
+ awaitEvents(mock, 2);
+
+ Message closeA = event(mock, WebsocketConstants.ONCLOSE_EVENT_TYPE, 0);
+ assertEquals("a", closeA.getHeader("client"));
+ }
+
+ @Test
+ void queryParameterValuesAreUrlDecoded() {
+ MockEndpoint mock = getMockEndpoint("mock:events");
+
+ WebsocketTestClient client =
connect("?name=John+Doe&city=S%C3%A3o+Paulo");
+ awaitEvents(mock, 1);
+
+ Message open = event(mock, WebsocketConstants.ONOPEN_EVENT_TYPE, 0);
+ assertEquals("John Doe", open.getHeader("name"));
+ assertEquals("S\u00e3o Paulo", open.getHeader("city"));
+
+ client.close();
+ }
+
+ private static WebsocketTestClient connect(String query) {
+ WebsocketTestClient client = new WebsocketTestClient("ws://localhost:"
+ PORT + "/events" + query);
+ client.connect();
+ return client;
+ }
+
+ private static void awaitEvents(MockEndpoint mock, int count) {
+ Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() ->
mock.getReceivedCounter() >= count);
+ }
+
+ private static Message event(MockEndpoint mock, int eventType, int index) {
+ List<Message> events = mock.getReceivedExchanges().stream()
+ .map(Exchange::getIn)
+ .filter(m ->
Integer.valueOf(eventType).equals(m.getHeader(WebsocketConstants.EVENT_TYPE)))
+ .toList();
+ return events.get(index);
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ public void configure() {
+ from("atmosphere-websocket:///events").to("mock:events");
+ }
+ };
+ }
+}
diff --git
a/components/camel-atmosphere-websocket/src/test/java/org/apache/camel/component/atmosphere/websocket/WebsocketQueryParameterTest.java
b/components/camel-atmosphere-websocket/src/test/java/org/apache/camel/component/atmosphere/websocket/WebsocketQueryParameterTest.java
index f769aaeb99ae..6d302d10d0f6 100644
---
a/components/camel-atmosphere-websocket/src/test/java/org/apache/camel/component/atmosphere/websocket/WebsocketQueryParameterTest.java
+++
b/components/camel-atmosphere-websocket/src/test/java/org/apache/camel/component/atmosphere/websocket/WebsocketQueryParameterTest.java
@@ -47,6 +47,13 @@ public class WebsocketQueryParameterTest extends
WebsocketCamelRouterWithInitPar
assertEquals(Map.of("flag", "", "empty", "", "eq", "a=b", "param",
"value"), map);
}
+ @Test
+ void testQueryMapDecodesNamesAndValues() {
+ Map<String, String> map =
WebsocketConsumer.getQueryMap("name=John%20Doe&city=S%C3%A3o+Paulo&a%26b=c%3Dd&bad=%zz");
+
+ assertEquals(Map.of("name", "John Doe", "city", "S\u00e3o Paulo",
"a&b", "c=d", "bad", "%zz"), map);
+ }
+
@Test
void testQueryMapNoQuery() {
assertTrue(WebsocketConsumer.getQueryMap(null).isEmpty());
diff --git
a/components/camel-atmosphere-websocket/src/test/java/org/apache/camel/component/atmosphere/websocket/WebsocketRoute1WithInitParamTest.java
b/components/camel-atmosphere-websocket/src/test/java/org/apache/camel/component/atmosphere/websocket/WebsocketRoute1WithInitParamTest.java
index a10f061ff070..116b0dab2f7a 100644
---
a/components/camel-atmosphere-websocket/src/test/java/org/apache/camel/component/atmosphere/websocket/WebsocketRoute1WithInitParamTest.java
+++
b/components/camel-atmosphere-websocket/src/test/java/org/apache/camel/component/atmosphere/websocket/WebsocketRoute1WithInitParamTest.java
@@ -19,6 +19,7 @@ package org.apache.camel.component.atmosphere.websocket;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.infra.common.http.WebsocketTestClient;
import org.junit.jupiter.api.Test;
@@ -42,8 +43,16 @@ public class WebsocketRoute1WithInitParamTest extends
WebsocketCamelRouterWithIn
}
@Test
- void testPassParametersWebsocketOnOpen() {
- assertDoesNotThrow(() ->
runtTest("/hola1?param1=value1¶m2=value2"));
+ void testPassParametersWebsocketOnOpen() throws Exception {
+ MockEndpoint mock = getMockEndpoint("mock:hola1");
+ mock.expectedMessageCount(2);
+
mock.message(0).header(WebsocketConstants.EVENT_TYPE).isEqualTo(WebsocketConstants.ONOPEN_EVENT_TYPE);
+ mock.message(0).header("param1").isEqualTo("value1");
+ mock.message(0).header("param2").isEqualTo("value2");
+
+ runtTest("/hola1?param1=value1¶m2=value2");
+
+ mock.assertIsSatisfied();
}
// START SNIPPET: payload
@@ -59,11 +68,7 @@ public class WebsocketRoute1WithInitParamTest extends
WebsocketCamelRouterWithIn
});
// route for events resending enabled
-
from("atmosphere-websocket:///hola1").to("log:info").process(new Processor() {
- public void process(final Exchange exchange) {
- checkPassedParameters(exchange);
- }
- });
+
from("atmosphere-websocket:///hola1").to("log:info").to("mock:hola1");
}
};
}
@@ -83,21 +88,5 @@ public class WebsocketRoute1WithInitParamTest extends
WebsocketCamelRouterWithIn
}
}
- private static void checkPassedParameters(Exchange exchange) {
- Object connectionKey =
exchange.getIn().getHeader(WebsocketConstants.CONNECTION_KEY);
- Object eventType =
exchange.getIn().getHeader(WebsocketConstants.EVENT_TYPE);
- Object msg = exchange.getIn().getBody();
-
- assertNull(msg);
- assertNotNull(connectionKey);
-
- if (eventType instanceof Integer &&
eventType.equals(WebsocketConstants.ONOPEN_EVENT_TYPE)) {
-
- String param1 = (String) exchange.getIn().getHeader("param1");
- String param2 = (String) exchange.getIn().getHeader("param2");
-
- assertTrue(param1.equals("value1") && param2.equals("value2"));
- }
- }
// END SNIPPET: payload
}
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index f63eebcf15e1..f1e4eecc6569 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -335,6 +335,16 @@ Apache MINA SSHD leaves it off by default, so a small
request, such as one that
listing, could wait for the server to acknowledge the previous reply. The
`org.apache.sshd.config.tcp-nodelay` system
property no longer applies to the connections of `mina-sftp`.
+=== camel-atmosphere-websocket - events carry the query parameters of their
own connection
+
+With the `events` init-param of `CamelWebSocketServlet` set to `true`, the
open, close and error event exchanges now carry
+the query parameters of the request that opened their websocket connection,
with the names and values URL-decoded.
+This is also the case with the JSR 356 transport, which Atmosphere uses on
current servlet containers, where the
+parameters of the connection did not reach its events before. Before, the
event headers came from the last HTTP request
+that the servlet handled for the endpoint, and their values were not
URL-decoded, so a route that used these headers
+can see different values. `WebsocketConsumer.sendEventNotification` takes the
query parameters of the connection as a
+third argument.
+
=== camel-master - the consumer keeps the leadership until its delegated
consumer has stopped
When a `master:` consumer stops (its route stops, or the CamelContext shuts
down), it now stops the delegated consumer