Atmosphere Websocket
Since Camel 2.14
Both producer and consumer are supported
The Atmosphere-Websocket component provides Websocket based endpoints for a servlet communicating with external clients over Websocket (as a servlet accepting websocket connections from external clients). This component uses the Atmosphere library to support the Websocket transport in various Servlet containers.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-atmosphere-websocket</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Atmosphere Websocket component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
Whether to keep the exception out of the response when an exchange fails on a consumer: the response is the 500 status code with an empty body. It is the default of the muteException option of the endpoints. | true | boolean | |
The default servletName of the endpoints: the name of the CamelHttpTransportServlet that receives the requests of the consumers, as its servlet name in the servlet container, such as the servlet-name in web.xml. | CamelServlet | String | |
Whether to bind the parts of a multipart/form-data request as attachments on the Camel message, keyed by the part (form field) name and with the part headers as attachment headers. The parts are read with HttpServletRequest.getParts(), which the Servlet API allows only for a servlet with a multipart configuration (MultipartConfig, or multipart-config in web.xml), so configure one for the CamelHttpTransportServlet. Enabling it turns on disableStreamCache; an explicit disableStreamCache=false fails the endpoint creation. This is the default of the endpoints, also of the Rest DSL consumers. | false | boolean | |
The accepted extensions of uploaded file names, without the dot and separated by comma, such as txt,xml. A file part of a multipart request with another extension is not bound as an attachment (see attachmentMultipartBinding). The extension is all after the first dot of the submitted file name (tar.gz for report.tar.gz) and is compared ignoring case. When not set, or set to *, every file is accepted. This is the default of the endpoints, also of the Rest DSL consumers. | String | ||
A custom org.apache.camel.http.common.HttpRegistry that connects the consumers to the CamelHttpTransportServlet instances. When not set, each consumer registers in the shared registry of its servletName, where the CamelHttpTransportServlet of that name registers itself. | HttpRegistry | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Whether to allow Java serialization of a message body with Content-Type application/x-java-serialized-object: a consumer deserializes such a request body and can write a Java object as such a response, and the HTTP producer deserializes such a response body. When not allowed, such a body that is received is dropped (null). This is turned off by default: if you enable it, be aware that Java deserializes the data that the other side sends, which can be a security risk. | false | boolean | |
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
To use a custom HttpBinding for the consumers of this component, which reads the HTTP servlet request into the Camel message and writes the Camel message to the HTTP servlet response. The HTTP producer (camel-http) does not use it. | HttpBinding | ||
A shared HttpConfiguration with default options for the endpoints that this component creates; an option set on the endpoint takes precedence. Only the HTTP producer (camel-http) uses it, and only its authentication options (authMethod, which must be set, with the credentials) configure the HTTP client. The consumer components ignore it. | HttpConfiguration | ||
To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy | ||
Sets an ObjectInputFilter pattern (jdk.serialFilter syntax) applied when deserializing Java objects from requests or responses with Content-Type application/x-java-serialized-object (only used when allowJavaSerializedObject or transferException is enabled). When not set, the JVM-wide jdk.serialFilter is used if present; otherwise a default filter is applied that rejects java.net., allows java., javax.* and org.apache.camel.*, and rejects every other class. | String |
Endpoint Options
The Atmosphere Websocket endpoint is configured using URI syntax:
atmosphere-websocket:servicePath
With the following path and query parameters:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
If false, the consumer writes the response with a Content-Length header, which buffers the whole body first, instead of streaming it with chunked transfer encoding. The CamelHttpChunked message header overrides this option. | true | boolean | |
Whether to turn off the caching of the raw HTTP stream. By default the consumer (camel-servlet, camel-jetty) copies the request body into a stream cache, so it can be read more than once, and the producer (camel-http) does the same with the response body. When true, the message body is the raw input stream, which can only be read once: use it to stream a large payload directly to a file or another store, or in a proxy route that does not read the body. The producer then closes the response stream when the exchange completes. | false | boolean | |
Whether the producer sends the message to all the clients connected to this path. When false, it sends the message to the connections in the CamelAtmosphereWebsocketConnectionKeyList header, or else to the connection in the CamelAtmosphereWebsocketConnectionKey header. | false | boolean | |
If enabled and an exchange fails on the consumer, the consumer sends the exception back in the response as a Java serialized object, with Content-Type application/x-java-serialized-object, instead of its stack trace as text. It has no effect while muteException is enabled (the default). The exception must be serializable. It also makes the consumer deserialize a request body of that content type. This is turned off by default: if you enable it, be aware that Java deserializes the data that the client sends, which can be a security risk. | false | boolean | |
Whether the consumer receives messages as a stream: a text message as a java.io.Reader and a binary message as a java.io.InputStream, instead of a String or a byte array. The producer does not use this option. | false | boolean | |
To use a custom HeaderFilterStrategy to filter the headers that are mapped between the Camel message and the HTTP request and response. | HeaderFilterStrategy | ||
To use a custom HttpBinding that reads the HTTP servlet request into the Camel message and writes the Camel message to the HTTP servlet response. The options muteException, logException, transferException, eagerCheckContentAvailable and mapHttpMessage* of the endpoint only configure the binding that Camel creates, not a custom one. | HttpBinding | ||
Whether the consumer uses the Servlet asynchronous support: the request is put in asynchronous mode (AsyncContext), the route runs on another thread of the container, and the response is written when the exchange completes. Only camel-jetty uses this option; camel-servlet takes it from the async init parameter of the CamelHttpTransportServlet. | false | boolean | |
Comma-separated list of the HTTP methods that the consumer accepts, such as GET,POST. A request with another method gets the 405 Method Not Allowed response. | String | ||
Whether to log the exception, with its stack trace at ERROR level, when an exchange fails on the consumer and muteException keeps it out of the response. | false | boolean | |
Whether the consumer also serves the requests to paths below its own path (its path used as a URI prefix), when no consumer matches the request path exactly. | false | boolean | |
Whether to keep the exception out of the response when an exchange fails on the consumer: the response is the 500 status code with an empty body. When false, the response body is the stack trace of the exception as text (or the serialized exception with transferException). | true | boolean | |
The buffer size, in bytes, of the HTTP servlet response (ServletResponse.setBufferSize), which is also the size of the buffer used to copy the response body. When not set, the default of the servlet container is used. | Integer | ||
The name of the CamelHttpTransportServlet that receives the requests of this consumer: its servlet name in the servlet container, such as the servlet-name in web.xml. | CamelServlet | String | |
Whether to bind the parts of a multipart/form-data request as attachments on the Camel message, keyed by the part (form field) name and with the part headers as attachment headers. The parts are read with HttpServletRequest.getParts(), which the Servlet API allows only for a servlet with a multipart configuration (MultipartConfig, or multipart-config in web.xml), so configure one for the CamelHttpTransportServlet. Enabling it turns on disableStreamCache; an explicit disableStreamCache=false fails the endpoint creation. | false | boolean | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
Whether to check that the request input stream has data available when the request has no Content-Length header; the message body is null when no data is available right away. Turn it on for HTTP clients that do not stream the body. A request with Content-Length 0 always has a null body. | false | boolean | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
The accepted extensions of uploaded file names, without the dot and separated by comma, such as txt,xml. A file part of a multipart request with another extension is not bound as an attachment (see attachmentMultipartBinding). The extension is all after the first dot of the submitted file name (tar.gz for report.tar.gz) and is compared ignoring case. When not set, or set to *, every file is accepted. | String | ||
If this option is true then the HTTP request body is mapped to the IN message body. If this option is false then the request body is not read and the message body is null, and no attachments, Java serialized objects or form fields are mapped. | true | boolean | |
Whether to map the fields of a POST request with an application/x-www-form-urlencoded body to Camel message headers. It only applies when mapHttpMessageBody and mapHttpMessageHeaders are true too. | true | boolean | |
Whether to map the HTTP request headers and the request parameters (such as the query parameters) to Camel message headers, filtered by the headerFilterStrategy. When false, only the CamelHttp* headers (method, URI, URL, path and query) and Content-Type are set. | true | boolean | |
Whether the consumer routes HTTP OPTIONS requests. When false, the consumer answers an OPTIONS request itself, with status 200 and an Allow header that lists the HTTP methods it accepts. | false | boolean | |
Whether the consumer accepts HTTP TRACE requests and routes them. When false, a TRACE request gets the 405 Method Not Allowed response. | false | boolean | |
If true, the producer ignores the CamelHttpUri header and calls the URL of the endpoint, as a proxy or bridge route needs (the CamelHttpPath and CamelHttpQuery headers still apply). It also sends the request body as is, even with a gzip Content-Encoding, does not send headers that repeat the query parameters, and keeps no cookies. Set throwExceptionOnFailure to false as well to pass every response back to the caller. On a consumer it keeps a gzip request body compressed. | false | boolean | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean |
Message Headers
The Atmosphere Websocket component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelAtmosphereWebsocketConnectionKey (common) Constant: | The key of the WebSocket connection. The consumer sets it on every exchange; the producer sends the message to this connection when sendToAll is false and the CamelAtmosphereWebsocketConnectionKeyList header is not set. | String | |
CamelAtmosphereWebsocketConnectionKeyList (common) Constant: | The keys of the WebSocket connections that the producer sends the message to, when sendToAll is false. On the exchange that reports an undelivered message (the CamelAtmosphereWebsocketErrorType header), the consumer sets it to the keys that match no open connection. | List | |
CamelAtmosphereWebsocketEventType (consumer) Constant: | The type of the connection event: 1 for open (ONOPEN_EVENT_TYPE), 0 for close (ONCLOSE_EVENT_TYPE) or -1 for error (ONERROR_EVENT_TYPE). The consumer routes these events only when the events init parameter of the CamelWebSocketServlet is true. | int | |
CamelAtmosphereWebsocketErrorType (consumer) Constant: | Set to 1 (MESSAGE_NOT_SENT_ERROR_TYPE) on the exchange that the consumer routes when the producer has no open connection for some of the connection keys: the body is the message and the CamelAtmosphereWebsocketConnectionKeyList header has those keys. A write that fails on an open connection is only logged. | int | |
| Constant: | The HTTP method of the request, such as GET or POST. | String | |
CamelServletContextPath (consumer) Constant: | The path of the endpoint that received the request (the contextPath of the endpoint URI), for example /hello for servlet:hello. | String | |
| Constant: | The path of the request after the web application context path, the servlet path and the path of the endpoint (CamelServletContextPath), as received (not URL-decoded). | String | |
| Constant: | The query string of the request (not URL-decoded), or null when it has none. | String | |
| Constant: | The URI of the request without the query string (HttpServletRequest.getRequestURI()), from the web application context path on. | String | |
| Constant: | The URL of the request without the query string, with the scheme, host and port (HttpServletRequest.getRequestURL()). | String | |
CamelHttpCharacterEncoding (consumer) Constant: | The charset that the request declares (HttpServletRequest.getCharacterEncoding()). Set only when the request has one. | String | |
| Constant: | The Content-Type of the request. In the reply, the Content-Type of the response. | String | |
CamelHttpResponseCode (consumer) Constant: | The HTTP status code of the response. When it is not set, the response is 200, 204 when the reply has no body, or 500 when the exchange failed. | Integer | |
| Constant: | Whether the response is written in chunked mode (Transfer-Encoding: chunked), overriding the chunked option. | Boolean | |
| Constant: | The Content-Encoding of the request, which is copied to the reply. When the Content-Encoding of the reply contains gzip, the response body is written compressed with GZIP, unless bridgeEndpoint is enabled. | String |
Message Body
The message body at each side of the Atmosphere Websocket component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| A String for a text message, a byte array for a binary one; null for the open, close and error events (the servlet init parameter events=true). A message the producer could not deliver comes back with the CamelAtmosphereWebsocketErrorType header. The consumer does not reply.
|
Producer input |
| Text or a Reader as a text message, bytes or an InputStream as a binary one; other bodies as their toString. No body sends nothing. Sent to all peers with sendToAll, otherwise to the connection key headers. |
Producer output |
| The body is kept. |
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Reading and Writing Data over Websocket
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
In the route below, Camel will read from the specified websocket connection.
-
Java
-
XML
-
YAML
from("atmosphere-websocket:///servicepath")
.to("direct:next"); <route>
<from uri="atmosphere-websocket:///servicepath"/>
<to uri="direct:next"/>
</route> - route:
from:
uri: atmosphere-websocket:///servicepath
steps:
- to:
uri: direct:next Producer Example
In the route below, Camel will write to the specified websocket connection.
-
Java
-
XML
-
YAML
from("direct:next")
.to("atmosphere-websocket:///servicepath"); <route>
<from uri="direct:next"/>
<to uri="atmosphere-websocket:///servicepath"/>
</route> - route:
from:
uri: direct:next
steps:
- to:
uri: atmosphere-websocket:///servicepath