Camel Components

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, *.yaml files, 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

bridgeErrorHandler (consumer)

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

muteException (consumer)

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

servletName (consumer)

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

attachmentMultipartBinding (consumer (advanced))

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

fileNameExtWhitelist (consumer (advanced))

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

httpRegistry (consumer (advanced))

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

lazyStartProducer (producer)

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

allowJavaSerializedObject (advanced)

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

autowiredEnabled (advanced)

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

httpBinding (advanced)

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

httpConfiguration (advanced)

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

headerFilterStrategy (filter)

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message.

HeaderFilterStrategy

deserializationFilter (security)

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:

Path Parameters

Name Description Default Type

servicePath (common)

Required The path of the WebSocket endpoint, relative to the URL mapping of the CamelWebSocketServlet in the servlet container. A producer sends to the clients connected to the consumer with the same path.

String

Query Parameters

Name Description Default Type

chunked (common)

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

disableStreamCache (common)

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

sendToAll (common)

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

transferException (common)

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

useStreaming (common)

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

headerFilterStrategy (common (advanced))

To use a custom HeaderFilterStrategy to filter the headers that are mapped between the Camel message and the HTTP request and response.

HeaderFilterStrategy

httpBinding (common (advanced))

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

async (consumer)

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

httpMethodRestrict (consumer)

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

logException (consumer)

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

matchOnUriPrefix (consumer)

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

muteException (consumer)

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

responseBufferSize (consumer)

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

servletName (consumer)

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

attachmentMultipartBinding (consumer (advanced))

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

bridgeErrorHandler (consumer (advanced))

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

eagerCheckContentAvailable (consumer (advanced))

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

exceptionHandler (consumer (advanced))

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

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

fileNameExtWhitelist (consumer (advanced))

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

mapHttpMessageBody (consumer (advanced))

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

mapHttpMessageFormUrlEncodedBody (consumer (advanced))

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

mapHttpMessageHeaders (consumer (advanced))

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

optionsEnabled (consumer (advanced))

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

traceEnabled (consumer (advanced))

Whether the consumer accepts HTTP TRACE requests and routes them. When false, a TRACE request gets the 405 Method Not Allowed response.

false

boolean

bridgeEndpoint (producer)

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

lazyStartProducer (producer (advanced))

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: CONNECTION_KEY

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: CONNECTION_KEY_LIST

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: EVENT_TYPE

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: ERROR_TYPE

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

CamelHttpMethod (consumer)

Constant: HTTP_METHOD

The HTTP method of the request, such as GET or POST.

String

CamelServletContextPath (consumer)

Constant: SERVLET_CONTEXT_PATH

The path of the endpoint that received the request (the contextPath of the endpoint URI), for example /hello for servlet:hello.

String

CamelHttpPath (consumer)

Constant: HTTP_PATH

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

CamelHttpQuery (consumer)

Constant: HTTP_QUERY

The query string of the request (not URL-decoded), or null when it has none.

String

CamelHttpUri (consumer)

Constant: HTTP_URI

The URI of the request without the query string (HttpServletRequest.getRequestURI()), from the web application context path on.

String

CamelHttpUrl (consumer)

Constant: HTTP_URL

The URL of the request without the query string, with the scheme, host and port (HttpServletRequest.getRequestURL()).

String

CamelHttpCharacterEncoding (consumer)

Constant: HTTP_CHARACTER_ENCODING

The charset that the request declares (HttpServletRequest.getCharacterEncoding()). Set only when the request has one.

String

Content-Type (consumer)

Constant: CONTENT_TYPE

The Content-Type of the request. In the reply, the Content-Type of the response.

String

CamelHttpResponseCode (consumer)

Constant: HTTP_RESPONSE_CODE

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

CamelHttpChunked (consumer)

Constant: HTTP_CHUNKED

Whether the response is written in chunked mode (Transfer-Encoding: chunked), overriding the chunked option.

Boolean

Content-Encoding (consumer)

Constant: CONTENT_ENCODING

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

text, bytes or null

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.

  • With useStreaming=true: stream or null

Producer input

null, text, bytes or stream

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

unchanged

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