CometD
Since Camel 2.0
Both producer and consumer are supported
The Cometd component is a transport mechanism for working with the jetty implementation of the cometd/bayeux protocol.
Using this component in combination with the dojo toolkit library, it’s possible to push Camel messages directly into the browser using an AJAX-based mechanism.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cometd</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI format
cometd://host:port/channelName[?options]
The channelName represents a topic that can be subscribed to by the Camel endpoints.
cometd://localhost:8080/service/mychannel cometds://localhost:8443/service/mychannel
where cometds: represents an SSL configured endpoint.
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 CometD 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 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 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 | |
The list of BayeuxServer.Extension that can modify or drop the incoming and outgoing Bayeux messages. They are added to each CometD server that the component starts. | List | ||
The CometD SecurityPolicy that decides whether a client may handshake, create a channel, subscribe to a channel or publish to it. It is set on each CometD server that the component starts. | SecurityPolicy | ||
The SSL configuration of the cometds server, such as the keystore with its certificate. When set, sslKeystore, sslPassword and sslKeyPassword are not used. | SSLContextParameters | ||
The password of the keystore that sslKeystore points to, for the cometds server. Not used when SSL context parameters are configured. | String | ||
The path of the keystore file with the certificate and private key of the cometds server. Not used when SSL context parameters are configured. | String | ||
The password of the private key in the keystore that sslKeystore points to, for the cometds server. Not used when SSL context parameters are configured. | String | ||
Whether the cometds server uses the global SSL context parameters of the CamelContext when sslContextParameters is not set. | false | boolean |
Endpoint Options
The CometD endpoint is configured using URI syntax:
cometd:host:port/channelName
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The host name or IP address that the embedded Jetty server listens on. Use 0.0.0.0 to listen on all network interfaces; localhost accepts only local connections. | String | ||
Required The TCP port that the embedded Jetty server listens on. The producers and consumers with the same scheme, host and port share one server. | int | ||
Required The name of the Bayeux channel, which is the path of the URI, such as /channel/orders. The consumer receives the messages that clients publish to this channel, and the producer publishes to the clients that subscribe to it. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The comma-separated list of origins that the cross-origin filter allows, such as https://app.example.com. A * in an origin matches any characters, * alone allows every origin, and the filter allows credentials only when every origin is named without a *. Used only when crossOriginFilterOn is true. | * | String | |
A comma-separated list of transport names allowed by the CometD server (e.g. websocket, long-polling, callback-polling). callback-polling is the JSONP transport mechanism. This option applies to the shared CometD server on the host and port; the first endpoint to configure the server sets this value. | websocket,long-polling | String | |
The directory of static web resources that the server serves from the root path, with the prefix file: for the file system or classpath: for the classpath, such as classpath:webapp. Without a value the server serves no static resources. The first endpoint that starts the server of the host and port sets it. | String | ||
Whether the server adds the Jetty CrossOriginFilter, which answers the CORS requests of the origins in allowedOrigins. The filter is mapped to filterPath, so set that option too. The first endpoint that starts the server of the host and port sets it. | false | boolean | |
The servlet path pattern that the cross-origin filter is mapped to, such as /cometd/*. Used only when crossOriginFilterOn is true; without a value the filter applies to no request. | String | ||
The time in milliseconds that the server tells the clients to wait after a /meta/connect reply before they send the next /meta/connect request; 0 means at once. The first endpoint that starts the server of the host and port sets it. | int | ||
Passed to the CometD servlet as the JSONCommented parameter, which CometD 9 does not read, so it has no effect. | true | boolean | |
Passed to the CometD servlet as the logLevel parameter, which CometD 9 does not read, so it has no effect. Set the level of the org.cometd loggers in the logging configuration instead. Enum values:
| 1 | int | |
The time in milliseconds that the server waits for the next /meta/connect request of a client before it removes the session of that client. The first endpoint that starts the server of the host and port sets it. | 30000 | int | |
Passed to the CometD servlet as the multiFrameInterval parameter, which CometD 9 does not read, so it has no effect. | 1500 | int | |
The time in milliseconds that the server holds a /meta/connect request (the long poll of a client) while it has no message to deliver, before it replies. The first endpoint that starts the server of the host and port sets it. | 240000 | int | |
Whether the consumer adds the attributes of the CometD session of the publishing client as headers, one header per attribute name. Only String, Integer, Long, Double and Boolean values are added; the other attributes are skipped. | 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 | |
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 | ||
Whether the producer disconnects the local session of its CometD service after each message it publishes to the channel. CometD does not sweep local sessions, so they stay in the server until they are disconnected. | 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 | |
A custom HeaderFilterStrategy for the headers that are copied between the Camel message and the ext field of the Bayeux message, in both directions. | HeaderFilterStrategy |
Message Headers
The CometD component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The id of the CometD session of the client that published the message, set by the consumer. | String | |
| Constant: | The subscription field of the received Bayeux message, set by the consumer when the message has this field. | String |
Message Body
The message body at each side of the CometD 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 |
| The data of the Bayeux message, parsed from JSON: a String, a number or a boolean, a Map for an object, a List for an array, or null. From a cometd producer in the same JVM the body that producer sent, as is (a stream or a file as its text). |
Consumer reply |
| Only when the exchange is InOut (exchangePattern=InOut, or set in the route): the body the route ends with is sent back to the client that published, as JSON. A stream or a file is read as text, and null is sent as a JSON null. Bytes become an array of numbers; another object is sent as the text of its toString. |
Producer input |
| The data published to the channel, sent as JSON to the subscribed clients: text, a number or a boolean, a Map or a List. A stream or a file is read as text, and null is published as a JSON null. Bytes become an array of numbers; another object is sent as the text of its toString: convert it first. The headers go in the ext field of the message. |
Producer output |
|
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.
Examples
Below, you can find some examples of how to pass the parameters.
For file, for webapp resources located in the Web Application directory -→ cometd://localhost:8080?baseResource=file:./webapp.
For classpath, when, for example, the web resources are packaged inside the webapp folder -→ cometd://localhost:8080?baseResource=classpath:webapp
The following routes publish a message to the /channel/orders channel every five seconds, and receive the messages of that channel:
- route:
from:
uri: cometd://0.0.0.0:9099/channel/orders
steps:
- log:
message: "Received ${body}"
- route:
from:
uri: timer:publish
parameters:
period: 5000
steps:
- setBody:
expression:
simple:
expression: "Order ${exchangeId}"
- to:
uri: cometd://0.0.0.0:9099/channel/orders Allowed Transports and JSONP
By default, the CometD server allows websocket and long-polling transports (allowedTransports=websocket,long-polling), disabling the legacy JSONP (callback-polling) transport mechanism.
To allow JSONP clients, configure allowedTransports explicitly on the endpoint URI:
cometd://localhost:8080/service/mychannel?allowedTransports=websocket,long-polling,callback-polling Because allowedTransports configures the underlying Bayeux server for a given host and port, the setting applies to all endpoints sharing that server.
Authentication
You can configure custom SecurityPolicy and Extension’s to the `CometdComponent which allows you to use authentication as documented here
Setting up SSL for Cometd Component
Using the JSSE Configuration Utility
The Cometd component supports SSL/TLS configuration through the Camel JSSE Configuration Utility. This utility greatly decreases the amount of component-specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Cometd component. You need to configure SSL on the CometdComponent.x
-
Java
-
Spring XML
Programmatic configuration of the component:
KeyStoreParameters ksp = new KeyStoreParameters();
ksp.setResource("/users/home/server/keystore.jks");
ksp.setPassword("keystorePassword");
KeyManagersParameters kmp = new KeyManagersParameters();
kmp.setKeyStore(ksp);
kmp.setKeyPassword("keyPassword");
TrustManagersParameters tmp = new TrustManagersParameters();
tmp.setKeyStore(ksp);
SSLContextParameters scp = new SSLContextParameters();
scp.setKeyManagers(kmp);
scp.setTrustManagers(tmp);
CometdComponent commetdComponent = getContext().getComponent("cometds", CometdComponent.class);
commetdComponent.setSslContextParameters(scp); <camel:sslContextParameters
id="sslContextParameters">
<camel:keyManagers
keyPassword="keyPassword">
<camel:keyStore
resource="/users/home/server/keystore.jks"
password="keystorePassword"/>
</camel:keyManagers>
<camel:trustManagers>
<camel:keyStore
resource="/users/home/server/keystore.jks"
password="keystorePassword"/>
</camel:trustManagers>
</camel:sslContextParameters>
<bean id="cometd" class="org.apache.camel.component.cometd.CometdComponent">
<property name="sslContextParameters" ref="sslContextParameters"/>
</bean>
<to uri="cometds://127.0.0.1:443/service/test?baseResource=file:./target/test-classes/webapp&timeout=240000&interval=0&maxInterval=30000&multiFrameInterval=1500&jsonCommented=true&logLevel=2"/>...