此内容没有您所选择的语言版本。

Apache Camel Component Reference


Red Hat Fuse 7.5

Configuration reference for Camel components

Red Hat Fuse Documentation Team

Abstract

Apache Camel has over 100 components and each component is highly configurable. This guide describes the settings for each of the components.

Chapter 1. Components Overview

This chapter provides a summary of all the components available for Apache Camel.

1.1. Container types

Red Hat Fuse provides a variety of container types, into which you can deploy your Camel applications:

  • Spring Boot
  • Apache Karaf
  • JBoss Enterprise Application Platform (JBoss EAP)

In addition, a Camel application can run as containerless: that is, where a Camel application runs directly in the JVM, without any special container.

In some cases, Fuse might support a Camel component in one container, but not in the others. There are various reasons for this, but in some cases a component is not suitable for all container types. For example, the camel-ejb component is designed spcifically for Java EE (that is, JBoss EAP), and cannot be supported in the other container types.

1.2. Supported components

Note the following key:

Expand
SymbolDescription

Supported

Unsupported or not yet supported

Deprecated

Likely to be removed in a future release

Table 1.1, “Apache Camel Component Support Matrix” provides comprehensive details about which Camel components are supported in which containers.

Expand
Table 1.1. Apache Camel Component Support Matrix
ComponentTypeContainerlessSpring Boot 1.xSpring Boot 2.xKarafJBoss EAP

activemq-camel

Endpoint

camel-ahc

Endpoint

camel-ahc-ws

Endpoint

camel-ahc-wss

Endpoint

camel-amqp

Endpoint

camel-apns

Endpoint

camel-asn1

Data Format

camel-as2

Endpoint

camel-asterisk

Endpoint

camel-atmos

Endpoint

camel-atmosphere-websocket

Endpoint

camel-atom

Endpoint

camel-atomix

Endpoint

camel-avro

Endpoint

camel-avro

Data Format

camel-aws

Endpoint

camel-azure

Endpoint

camel-bam

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-barcode

Data Format

camel-base64

Data Format

camel-bean

Endpoint

camel-bean

Language

camel-bean-validator

Endpoint

camel-beanio

Data Format

camel-beanstalk

Endpoint

camel-binding

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-bindy

Endpoint

camel-bindy

Data Format

camel-blueprint

Endpoint

camel-bonita

Endpoint

camel-boon

Data Format

camel-box

Endpoint

camel-braintree

Endpoint

camel-browse

Endpoint

camel-cache

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-caffeine

Endpoint

camel-castor

Data Format

Deprecated

Deprecated

Deprecated

Deprecated

camel-cdi

Endpoint

Deprecated

camel-chronicle-engine

Endpoint

camel-chunk

Endpoint

camel-class

Endpoint

camel-cm-sms

Endpoint

camel-cmis

Endpoint

camel-coap

Endpoint

camel-cometd

Endpoint

camel-constant

Language

camel-context

Endpoint

Deprecated

camel-consul

Endpoint

camel-controlbus

Endpoint

camel-couchbase

Endpoint

camel-couchdb

Endpoint

camel-cql

Endpoint

camel-crypto

Endpoint

camel-crypto

Data Format

camel-crypto-cms

Endpoint

camel-csv

Data Format

camel-cxf

Endpoint

camel-cxf-transport

Endpoint

camel-dataformat

Endpoint

camel-dataset

Endpoint

camel-digitalocean

Endpoint

camel-direct

Endpoint

camel-direct-vm

Endpoint

camel-disruptor

Endpoint

camel-dns

Endpoint

camel-docker

Endpoint

camel-dozer

Endpoint

camel-drill

Endpoint

camel-dropbox

Endpoint

camel-eclipse

 

Deprecated

camel-ehcache

Endpoint

camel-ejb

Endpoint

camel-el

Language

Deprecated

camel-elasticsearch

Endpoint

camel-elasticsearch5

Endpoint

camel-elasticsearch-rest

Endpoint

camel-elsql

Endpoint

camel-etcd

Endpoint

camel-eventadmin

Endpoint

camel-exchangeProperty

Language

camel-exec

Endpoint

camel-facebook

Endpoint

camel-fhir

Data Format

camel-fhir

Endpoint

camel-file

Endpoint

camel-file

Language

camel-flatpack

Endpoint

camel-flatpack

Data Format

camel-flink

Endpoint

camel-fop

Endpoint

camel-freemarker

Endpoint

camel-ftp

Endpoint

camel-gae

Endpoint

Deprecated

camel-ganglia

Endpoint

camel-geocoder

Endpoint

camel-git

Endpoint

camel-github

Endpoint

camel-google-bigquery

Endpoint

camel-google-calendar

Endpoint

camel-google-drive

Endpoint

camel-google-mail

Endpoint

camel-google-pubsub

Endpoint

camel-google-sheets

Endpoint

camel-grape

Endpoint

camel-groovy

Language

camel-groovy-dsl

 

Deprecated

camel-grpc

Endpoint

camel-guava-eventbus

Endpoint

camel-guice

Endpoint

Deprecated

Deprecated

Deprecated

camel-gzip

Data Format

camel-hawtdb

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-hazelcast

Endpoint

camel-hbase

Endpoint

camel-hdfs

Endpoint

Deprecated

camel-hdfs2

Endpoint

camel-header

Language

camel-headersmap

 

camel-hessian

Data Format

Deprecated

Deprecated

Deprecated

Deprecated

Deprecated

camel-hipchat

Endpoint

camel-hl7

Data Format

camel-http

Endpoint

Deprecated

Deprecated

Deprecated

camel-http4

Endpoint

camel-hystrix

Endpoint

camel-ibatis

Endpoint

Deprecated

camel-ical

Data Format

camel-iec60870

Endpoint

camel-ignite

Endpoint

camel-imap

Endpoint

camel-infinispan

Endpoint

camel-influxdb

Endpoint

camel-ipfs

Endpoint

camel-irc

Endpoint

camel-ironmq

Endpoint

camel-jacksonxml

Data Format

camel-jasypt

Endpoint

camel-javaspace

Endpoint

Deprecated

camel-jaxb

Data Format

camel-jbpm

Endpoint

camel-jcache

Endpoint

camel-jcifs

Endpoint

camel-jclouds

Endpoint

camel-jcr

Endpoint

camel-jdbc

Endpoint

camel-jetty

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-jetty8

Endpoint

camel-jetty9

Endpoint

camel-jgroups

Endpoint

camel-jibx

Data Format

camel-jing

Endpoint

camel-jira

Endpoint

camel-jms

Endpoint

camel-jmx

Endpoint

camel-jolt

Endpoint

camel-josql

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-jpa

Endpoint

camel-jsch

Endpoint

camel-json-fastjson

Data Format

camel-json-gson

Data Format

camel-json-jackson

Data Format

camel-json-johnzon

Data Format

camel-json-validator

Endpoint

camel-json-xstream

Data Format

camel-jsonpath

Language

camel-jt400

Endpoint

camel-juel

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-jxpath

Language

Deprecated

camel-kafka

Endpoint

camel-kestrel

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-krati

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-kubernetes

Endpoint

camel-kura

 

camel-ldap

Endpoint

camel-ldif

Endpoint

camel-leveldb

Endpoint

camel-linkedin

Endpoint

camel-log

Endpoint

camel-lpr

Endpoint

camel-lra

 

camel-lucene

Endpoint

camel-lumberjack

Endpoint

camel-lzf

Data Format

camel-master

 

camel-mail

Endpoint

camel-metrics

Endpoint

camel-micrometer

Endpoint

camel-milo

Endpoint

camel-mime-multipart

Data Format

camel-mina

Endpoint

Deprecated

camel-mina2

Endpoint

camel-mllp

Endpoint

camel-mock

Endpoint

camel-mongodb

Endpoint

camel-mongodb-gridfs

Endpoint

camel-mongodb3

Endpoint

camel-mqtt

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

Deprecated

camel-msv

Endpoint

camel-mustache

Endpoint

camel-mvel

Endpoint

camel-mvel

Language

camel-mybatis

Endpoint

camel-nagios

Endpoint

camel-nats

Endpoint

camel-netty

Endpoint

Deprecated

Deprecated

Deprecated

camel-netty-http

Endpoint

Deprecated

Deprecated

Deprecated

camel-netty4

Endpoint

camel-netty4-http

Endpoint

camel-nsq

Endpoint

camel-ognl

Language

camel-olingo2

Endpoint

camel-olingo4

Endpoint

camel-openshift

Endpoint

Deprecated

camel-openstack

Endpoint

camel-opentracing

 

camel-optaplanner

Endpoint

camel-paho

Endpoint

camel-paxlogging

Endpoint

camel-pdf

Endpoint

camel-pgevent

Endpoint

camel-pgp

Data Format

camel-php

Language

Deprecated

Deprecated

Deprecated

Deprecated

camel-pop3

Endpoint

camel-printer

Endpoint

camel-properties

Endpoint

camel-protobuf

Data Format

camel-pubnub

Endpoint

camel-python

Language

Deprecated

Deprecated

Deprecated

Deprecated

camel-quartz

Endpoint

Deprecated

camel-quartz2

Endpoint

camel-quickfix

Endpoint

camel-rabbitmq

Endpoint

camel-reactive-streams

Endpoint

camel-reactor

 

camel-ref

Endpoint

camel-ref

Language

camel-rest

Endpoint

camel-rest-api

Endpoint

camel-rest-swagger

Endpoint

camel-restlet

Endpoint

camel-ribbon

 

camel-rmi

Endpoint

camel-routebox

Endpoint

Deprecated

camel-rss

Endpoint

camel-rss

Data Format

camel-ruby

Language

Deprecated

Deprecated

Deprecated

Deprecated

camel-rx

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-rxjava2

Endpoint

camel-saga

Endpoint

camel-salesforce

Endpoint

camel-sap

Endpoint

camel-sap-netweaver

Endpoint

camel-saxon

Endpoint

camel-scala

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-scheduler

Endpoint

camel-schematron

Endpoint

camel-scp

Endpoint

camel-scr

Endpoint

Deprecated

Deprecated

camel-script

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

Deprecated

camel-seda

Endpoint

camel-serialization

Data Format

camel-service

Endpoint

camel-servicenow

Endpoint

camel-servlet

Endpoint

camel-servletlistener

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-sftp

Endpoint

camel-shiro

Endpoint

camel-simple

Language

camel-sip

Endpoint

camel-sjms

Endpoint

camel-sjms2

Endpoint

camel-slack

Endpoint

camel-smpp

Endpoint

camel-snakeyaml

Endpoint

camel-snmp

Endpoint

camel-soapjaxb

Data Format

camel-solr

Endpoint

camel-spark

Endpoint

camel-spark-rest

Endpoint

camel-spel

Language

camel-splunk

Endpoint

camel-spring

Endpoint

camel-spring-batch

Endpoint

camel-spring-boot

Endpoint

camel-spring-cloud

 

camel-spring-cloud-consul

Endpoint

camel-spring-cloud-netflix

 

camel-spring-cloud-zookeeper

Endpoint

camel-spring-event

Endpoint

camel-spring-integration

Endpoint

camel-spring-javaconfig

Endpoint

camel-spring-ldap

Endpoint

camel-spring-redis

Endpoint

camel-spring-security

Endpoint

camel-spring-ws

Endpoint

camel-sql

Endpoint

camel-sql-stored

Endpoint

camel-ssh

Endpoint

camel-stax

Endpoint

camel-stomp

Endpoint

camel-stream

Endpoint

camel-string

Data Format

camel-string-template

Endpoint

camel-stub

Endpoint

camel-swagger

Endpoint

Deprecated

Deprecated

camel-swagger-java

Endpoint

camel-syslog

Data Format

camel-tagsoup

Endpoint

camel-tarfile

Data Format

camel-telegram

Endpoint

camel-thrift

Endpoint

camel-thrift

Data Format

camel-tika

Endpoint

camel-timer

Endpoint

camel-tokenize

Language

camel-twilio

Endpoint

camel-twitter

Endpoint

camel-undertow

Endpoint

camel-univocity-csv

Data Format

camel-univocity-fixed

Data Format

camel-univocity-tsv

Data Format

camel-urlrewrite

Endpoint

Deprecated

Deprecated

Deprecated

Deprecated

camel-validator

Endpoint

camel-velocity

Endpoint

camel-vertx

Endpoint

camel-vm

Endpoint

camel-weather

Endpoint

camel-web3j

Endpoint

camel-websocket

Endpoint

camel-wordpress

Endpoint

camel-xchange

Endpoint

camel-xmlbeans

Data Format

Deprecated

Deprecated

Deprecated

Deprecated

camel-xmljson

Data Format

Deprecated

Deprecated

Deprecated

Deprecated

Deprecated

camel-xmlrpc

Endpoint

camel-xmlrpc

Data Format

camel-xmlsecurity

Endpoint

camel-xmpp

Endpoint

camel-xpath

Language

camel-xquery

Endpoint

camel-xquery

Language

camel-xslt

Endpoint

camel-xstream

Data Format

camel-xtokenize

Language

camel-yaml-snakeyaml

Data Format

camel-yammer

Endpoint

camel-yql

Endpoint

camel-zendesk

Endpoint

camel-zip

Data Format

camel-zipfile

Data Format

camel-zipkin

Endpoint

camel-zookeeper

Endpoint

camel-zookeeper-master

Endpoint

Chapter 2. ActiveMQ

ActiveMQ Component

The ActiveMQ component allows messages to be sent to a JMS Queue or Topic; or messages to be consumed from a JMS Queue or Topic using Apache ActiveMQ.

This component is based on the Chapter 178, JMS Component and uses Spring’s JMS support for declarative transactions, using Spring’s JmsTemplate for sending and a MessageListenerContainer for consuming. All the options from the Chapter 178, JMS Component component also apply for this component.

To use this component, make sure you have the activemq.jar or activemq-core.jar on your classpath along with any Apache Camel dependencies such as camel-core.jar, camel-spring.jar and camel-jms.jar.

Transacted and caching

See section Transactions and Cache Levels below on JMS page if you are using transactions with JMS as it can impact performance.

URI format

activemq:[queue:|topic:]destinationName
Copy to Clipboard Toggle word wrap

Where destinationName is an ActiveMQ queue or topic name. By default, the destinationName is interpreted as a queue name. For example, to connect to the queue, FOO.BAR, use:

activemq:FOO.BAR
Copy to Clipboard Toggle word wrap

You can include the optional queue: prefix, if you prefer:

activemq:queue:FOO.BAR
Copy to Clipboard Toggle word wrap

To connect to a topic, you must include the topic: prefix. For example, to connect to the topic, Stocks.Prices, use:

activemq:topic:Stocks.Prices
Copy to Clipboard Toggle word wrap

Options

See Options on the Chapter 178, JMS Component component as all these options also apply for this component.

Camel on EAP deployment

This component is supported by the Camel on EAP (Wildfly Camel) framework, which offers a simplified deployment model on the Red Hat JBoss Enterprise Application Platform (JBoss EAP) container.

You can configure the ActiveMQ Camel component to work either with an embedded broker or an external broker. To embed a broker in the JBoss EAP container, configure the ActiveMQ Resource Adapter in the EAP container configuration file — for details, see ActiveMQ Resource Adapter Configuration.

Configuring the Connection Factory

The following test case shows how to add an ActiveMQComponent to the CamelContext using the activeMQComponent() method while specifying the brokerURL used to connect to ActiveMQ.

camelContext.addComponent("activemq", activeMQComponent("vm://localhost?broker.persistent=false"));
Copy to Clipboard Toggle word wrap

Configuring the Connection Factory using Spring XML

You can configure the ActiveMQ broker URL on the ActiveMQComponent as follows

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

  <camelContext xmlns="http://camel.apache.org/schema/spring">
  </camelContext>

  <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent">
    <property name="brokerURL" value="tcp://somehost:61616"/>
  </bean>

</beans>
Copy to Clipboard Toggle word wrap

Using connection pooling

When sending to an ActiveMQ broker using Camel it’s recommended to use a pooled connection factory to handle efficient pooling of JMS connections, sessions and producers. This is documented in the page ActiveMQ Spring Support.

You can grab Jencks AMQ pool with Maven:

    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-pool</artifactId>
      <version>5.3.2</version>
    </dependency>
Copy to Clipboard Toggle word wrap

And then setup the activemq component as follows:

    <bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://localhost:61616" />
    </bean>

    <bean id="pooledConnectionFactory"    class="org.apache.activemq.pool.PooledConnectionFactory" init-method="start" destroy-method="stop">
        <property name="maxConnections" value="8" />
        <property name="connectionFactory" ref="jmsConnectionFactory" />
    </bean>

    <bean id="jmsConfig" class="org.apache.camel.component.jms.JmsConfiguration">
        <property name="connectionFactory" ref="pooledConnectionFactory"/>
        <property name="concurrentConsumers" value="10"/>
    </bean>

    <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent">
        <property name="configuration" ref="jmsConfig"/>
    </bean>
Copy to Clipboard Toggle word wrap
Note

Notice the init and destroy methods on the pooled connection factory. This is important to ensure the connection pool is properly started and shutdown.

The PooledConnectionFactory will then create a connection pool with up to 8 connections in use at the same time. Each connection can be shared by many sessions. There is an option named maxActive you can use to configure the maximum number of sessions per connection; the default value is 500. From ActiveMQ 5.7 onwards the option has been renamed to better reflect its purpose, being named as maxActiveSessionPerConnection. Notice the concurrentConsumers is set to a higher value than maxConnections is. This is okay, as each consumer is using a session, and as a session can share the same connection, we are in the safe. In this example we can have 8 * 500 = 4000 active sessions at the same time.

Invoking MessageListener POJOs in a route

The ActiveMQ component also provides a helper Type Converter from a JMS MessageListener to a Processor. This means that the Chapter 43, Bean Component component is capable of invoking any JMS MessageListener bean directly inside any route.

So for example you can create a MessageListener in JMS as follows:

public class MyListener implements MessageListener {
   public void onMessage(Message jmsMessage) {
       // ...
   }
}
Copy to Clipboard Toggle word wrap

Then use it in your route as follows

from("file://foo/bar").
  bean(MyListener.class);
Copy to Clipboard Toggle word wrap

That is, you can reuse any of the Apache Camel components and easily integrate them into your JMS MessageListener POJO\!

Using ActiveMQ Destination Options

Available as of ActiveMQ 5.6

You can configure the Destination Options in the endpoint uri, using the "destination." prefix. For example to mark a consumer as exclusive, and set its prefetch size to 50, you can do as follows:

<camelContext xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="file://src/test/data?noop=true"/>
    <to uri="activemq:queue:foo"/>
  </route>
  <route>
    <!-- use consumer.exclusive ActiveMQ destination option, notice we have to prefix with destination. -->
    <from uri="activemq:foo?destination.consumer.exclusive=true&amp;destination.consumer.prefetchSize=50"/>
    <to uri="mock:results"/>
  </route>
</camelContext>
Copy to Clipboard Toggle word wrap

Consuming Advisory Messages

ActiveMQ can generate Advisory messages which are put in topics that you can consume. Such messages can help you send alerts in case you detect slow consumers or to build statistics (number of messages/produced per day, etc.) The following Spring DSL example shows you how to read messages from a topic.

<route>
	<from uri="activemq:topic:ActiveMQ.Advisory.Connection?mapJmsMessage=false" />
	<convertBodyTo type="java.lang.String"/>
	<transform>
	     <simple>${in.body}&#13;</simple>
	</transform>
	<to uri="file://data/activemq/?fileExist=Append&ileName=advisoryConnection-${date:now:yyyyMMdd}.txt" />
</route>
Copy to Clipboard Toggle word wrap

If you consume a message on a queue, you should see the following files under data/activemq folder :

advisoryConnection-20100312.txt advisoryProducer-20100312.txt

and containing string:

      ActiveMQMessage {commandId = 0, responseRequired = false, messageId = ID:dell-charles-3258-1268399815140
      -1:0:0:0:221, originalDestination = null, originalTransactionId = null, producerId = ID:dell-charles-
      3258-1268399815140-1:0:0:0, destination = topic://ActiveMQ.Advisory.Connection, transactionId = null,
      expiration = 0, timestamp = 0, arrival = 0, brokerInTime = 1268403383468, brokerOutTime = 1268403383468,
      correlationId = null, replyTo = null, persistent = false, type = Advisory, priority = 0, groupID = null,
      groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = null,
      marshalledProperties = org.apache.activemq.util.ByteSequence@17e2705, dataStructure = ConnectionInfo
      {commandId = 1, responseRequired = true, connectionId = ID:dell-charles-3258-1268399815140-2:50,
      clientId = ID:dell-charles-3258-1268399815140-14:0, userName = , password = *****,
      brokerPath = null, brokerMasterConnector = false, manageable = true, clientMaster = true},
      redeliveryCounter = 0, size = 0, properties = {originBrokerName=master, originBrokerId=ID:dell-charles-
      3258-1268399815140-0:0, originBrokerURL=vm://master}, readOnlyProperties = true, readOnlyBody = true,
      droppable = false}
Copy to Clipboard Toggle word wrap

Getting Component JAR

You need this dependency:

  • activemq-camel

ActiveMQ is an extension of the Chapter 178, JMS Component component released with the ActiveMQ project.

<dependency>
  <groupId>org.apache.activemq</groupId>
  <artifactId>activemq-camel</artifactId>
  <version>5.6.0</version>
</dependency>
Copy to Clipboard Toggle word wrap

Chapter 3. AHC Component

Available as of Camel version 2.8

The ahc: component provides HTTP based endpoints for consuming external HTTP resources (as a client to call external servers using HTTP).
The component uses the Async Http Client library.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-ahc</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

3.1. URI format

ahc:http://hostname[:port][/resourceUri][?options]
ahc:https://hostname[:port][/resourceUri][?options]
Copy to Clipboard Toggle word wrap

Will by default use port 80 for HTTP and 443 for HTTPS.

You can append query options to the URI in the following format, ?option=value&option=value&…​

3.2. AhcEndpoint Options

The AHC endpoint is configured using URI syntax:

ahc:httpUri
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

3.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

httpUri

Required The URI to use such as http://hostname:port/path

 

URI

3.2.2. Query Parameters (13 parameters):

Expand
NameDescriptionDefaultType

bridgeEndpoint (producer)

If the option is true, then the Exchange.HTTP_URI header is ignored, and use the endpoint’s URI for request. You may also set the throwExceptionOnFailure to be false to let the AhcProducer send all the fault response back.

false

boolean

bufferSize (producer)

The initial in-memory buffer size used when transferring data between Camel and AHC Client.

4096

int

connectionClose (producer)

Define if the Connection Close header has to be added to HTTP Request. This parameter is false by default

false

boolean

cookieHandler (producer)

Configure a cookie handler to maintain a HTTP session

 

CookieHandler

headerFilterStrategy (producer)

To use a custom HeaderFilterStrategy to filter header to and from Camel message.

 

HeaderFilterStrategy

throwExceptionOnFailure (producer)

Option to disable throwing the AhcOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code.

true

boolean

transferException (producer)

If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized in the response as a application/x-java-serialized-object content type (for example using Jetty or Servlet Camel components). On the producer side the exception will be deserialized and thrown as is, instead of the AhcOperationFailedException. The caused exception is required to be serialized. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk.

false

boolean

binding (advanced)

To use a custom AhcBinding which allows to control how to bind between AHC and Camel.

 

AhcBinding

clientConfig (advanced)

To configure the AsyncHttpClient to use a custom com.ning.http.client.AsyncHttpClientConfig instance.

 

AsyncHttpClientConfig

clientConfigOptions (advanced)

To configure the AsyncHttpClientConfig using the key/values from the Map.

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

clientConfigRealmOptions (security)

To configure the AsyncHttpClientConfig Realm using the key/values from the Map.

 

Map

sslContextParameters (security)

Reference to a org.apache.camel.util.jsse.SSLContextParameters in the Registry. This reference overrides any configured SSLContextParameters at the component level. See Using the JSSE Configuration Utility. Note that configuring this option will override any SSL/TLS configuration options provided through the clientConfig option at the endpoint or component level.

 

SSLContextParameters

3.3. AhcComponent Options

The AHC component supports 8 options which are listed below.

Expand
NameDescriptionDefaultType

client (advanced)

To use a custom AsyncHttpClient

 

AsyncHttpClient

binding (advanced)

To use a custom AhcBinding which allows to control how to bind between AHC and Camel.

 

AhcBinding

clientConfig (advanced)

To configure the AsyncHttpClient to use a custom com.ning.http.client.AsyncHttpClientConfig instance.

 

AsyncHttpClientConfig

sslContextParameters (security)

Reference to a org.apache.camel.util.jsse.SSLContextParameters in the Registry. Note that configuring this option will override any SSL/TLS configuration options provided through the clientConfig option at the endpoint or component level.

 

SSLContextParameters

allowJavaSerialized Object (advanced)

Whether to allow java serialization when a request uses context-type=application/x-java-serialized-object This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk.

false

boolean

useGlobalSslContext Parameters (security)

Enable usage of global SSL context parameters.

false

boolean

headerFilterStrategy (filter)

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

 

HeaderFilterStrategy

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

Notice that setting any of the options on the AhcComponent will propagate those options to AhcEndpoints being created. However the AhcEndpoint can also configure/override a custom option. Options set on endpoints will always take precedence over options from the AhcComponent.

3.4. Message Headers

Expand
NameTypeDescription

Exchange.HTTP_URI

String

URI to call. Will override existing URI set directly on the endpoint.

Exchange.HTTP_PATH

String

Request URI’s path, the header will be used to build the request URI with the HTTP_URI. If the path is start with "/", http producer will try to find the relative path based on the Exchange.HTTP_BASE_URI header or the exchange.getFromEndpoint().getEndpointUri();

Exchange.HTTP_QUERY

String

Camel 2.11 onwards: URI parameters. Will override existing URI parameters set directly on the endpoint.

Exchange.HTTP_RESPONSE_CODE

int

The HTTP response code from the external server. Is 200 for OK.

Exchange.HTTP_CHARACTER_ENCODING

String

Character encoding.

Exchange.CONTENT_TYPE

String

The HTTP content type. Is set on both the IN and OUT message to provide a content type, such as text/html.

Exchange.CONTENT_ENCODING

String

The HTTP content encoding. Is set on both the IN and OUT message to provide a content encoding, such as gzip.

3.5. Message Body

Camel will store the HTTP response from the external server on the OUT body. All headers from the IN message will be copied to the OUT message, so headers are preserved during routing. Additionally Camel will add the HTTP response headers as well to the OUT message headers.

3.6. Response code

Camel will handle according to the HTTP response code:

  • Response code is in the range 100..299, Camel regards it as a success response.
  • Response code is in the range 300..399, Camel regards it as a redirection response and will throw a AhcOperationFailedException with the information.
  • Response code is 400+, Camel regards it as an external server failure and will throw a AhcOperationFailedException with the information.

    throwExceptionOnFailure

    The option, throwExceptionOnFailure, can be set to false to prevent the AhcOperationFailedException from being thrown for failed response codes. This allows you to get any response from the remote server.

3.7. AhcOperationFailedException

This exception contains the following information:

  • The HTTP status code
  • The HTTP status line (text of the status code)
  • Redirect location, if server returned a redirect
  • Response body as a java.lang.String, if server provided a body as response

3.8. Calling using GET or POST

The following algorithm is used to determine if either GET or POST HTTP method should be used:
1. Use method provided in header.
2. GET if query string is provided in header.
3. GET if endpoint is configured with a query string.
4. POST if there is data to send (body is not null).
5. GET otherwise.

3.9. Configuring URI to call

You can set the HTTP producer’s URI directly form the endpoint URI. In the route below, Camel will call out to the external server, oldhost, using HTTP.

from("direct:start")
        .to("ahc:http://oldhost");
Copy to Clipboard Toggle word wrap

And the equivalent Spring sample:

<camelContext xmlns="http://activemq.apache.org/camel/schema/spring">
  <route>
    <from uri="direct:start"/>
    <to uri="ahc:http://oldhost"/>
  </route>
</camelContext>
Copy to Clipboard Toggle word wrap

You can override the HTTP endpoint URI by adding a header with the key, Exchange.HTTP_URI, on the message.

from("direct:start")
    .setHeader(Exchange.HTTP_URI, constant("http://newhost"))
    .to("ahc:http://oldhost");
Copy to Clipboard Toggle word wrap

3.10. Configuring URI Parameters

The ahc producer supports URI parameters to be sent to the HTTP server. The URI parameters can either be set directly on the endpoint URI or as a header with the key Exchange.HTTP_QUERY on the message.

from("direct:start")
        .to("ahc:http://oldhost?order=123&detail=short");
Copy to Clipboard Toggle word wrap

Or options provided in a header:

from("direct:start")
            .setHeader(Exchange.HTTP_QUERY, constant("order=123&detail=short"))
        .to("ahc:http://oldhost");
Copy to Clipboard Toggle word wrap

3.11. How to set the http method to the HTTP producer

The HTTP component provides a way to set the HTTP request method by setting the message header. Here is an example;

from("direct:start")
            .setHeader(Exchange.HTTP_METHOD, constant("POST"))
        .to("ahc:http://www.google.com")
            .to("mock:results");
Copy to Clipboard Toggle word wrap

And the equivalent Spring sample:

<camelContext xmlns="http://activemq.apache.org/camel/schema/spring">
  <route>
    <from uri="direct:start"/>
    <setHeader headerName="CamelHttpMethod">
        <constant>POST</constant>
    </setHeader>
    <to uri="ahc:http://www.google.com"/>
    <to uri="mock:results"/>
  </route>
</camelContext>
Copy to Clipboard Toggle word wrap

3.12. Configuring charset

If you are using POST to send data you can configure the charset using the Exchange property:

exchange.setProperty(Exchange.CHARSET_NAME, "iso-8859-1");
Copy to Clipboard Toggle word wrap

3.12.1. URI Parameters from the endpoint URI

In this sample we have the complete URI endpoint that is just what you would have typed in a web browser. Multiple URI parameters can of course be set using the & character as separator, just as you would in the web browser. Camel does no tricks here.

// we query for Camel at the Google page
template.sendBody("ahc:http://www.google.com/search?q=Camel", null);
Copy to Clipboard Toggle word wrap

3.12.2. URI Parameters from the Message

Map headers = new HashMap();
headers.put(Exchange.HTTP_QUERY, "q=Camel&lr=lang_en");
// we query for Camel and English language at Google
template.sendBody("ahc:http://www.google.com/search", null, headers);
Copy to Clipboard Toggle word wrap

In the header value above notice that it should not be prefixed with ? and you can separate parameters as usual with the & char.

3.12.3. Getting the Response Code

You can get the HTTP response code from the AHC component by getting the value from the Out message header with Exchange.HTTP_RESPONSE_CODE.

Exchange exchange = template.send("ahc:http://www.google.com/search", new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(Exchange.HTTP_QUERY, constant("hl=en&q=activemq"));
            }
   });
   Message out = exchange.getOut();
   int responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
Copy to Clipboard Toggle word wrap

3.13. Configuring AsyncHttpClient

The AsyncHttpClient client uses a AsyncHttpClientConfig to configure the client. See the documentation at
Async Http Client for more details.

In Camel 2.8, configuration is limited to using the builder pattern provided by AsyncHttpClientConfig.Builder. In Camel 2.8, the AsyncHttpClientConfig doesn’t support getters/setters so its not easy to create/configure using a Spring bean style (eg the <bean> tag in the XML file).

The example below shows how to use a builder to create the AsyncHttpClientConfig which we configure on the AhcComponent.

In Camel 2.9, the AHC component uses Async HTTP library 1.6.4. This newer version provides added support for plain bean style configuration. The AsyncHttpClientConfigBean class provides getters and setters for the configuration options available in AsyncHttpClientConfig. An instance of AsyncHttpClientConfigBean may be passed directly to the AHC component or referenced in an endpoint URI using the clientConfig URI parameter.

Also available in Camel 2.9 is the ability to set configuration options directly in the URI. URI parameters starting with "clientConfig." can be used to set the various configurable properties of AsyncHttpClientConfig. The properties specified in the endpoint URI are merged with those specified in the configuration referenced by the "clientConfig" URI parameter with those being set using the "clientConfig." parameter taking priority. The AsyncHttpClientConfig instance referenced is always copied for each endpoint such that settings on one endpoint will remain independent of settings on any previously created endpoints. The example below shows how to configure the AHC component using the "clientConfig." type URI parameters.

from("direct:start")
    .to("ahc:http://localhost:8080/foo?clientConfig.maxRequestRetry=3&clientConfig.followRedirects=true")
Copy to Clipboard Toggle word wrap

3.14. SSL Support (HTTPS)

Using the JSSE Configuration Utility

As of Camel 2.9, the AHC 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 AHC component.

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");

SSLContextParameters scp = new SSLContextParameters();
scp.setKeyManagers(kmp);

AhcComponent component = context.getComponent("ahc", AhcComponent.class);
component.setSslContextParameters(scp));
Copy to Clipboard Toggle word wrap

Spring DSL based configuration of endpoint

...
  <camel:sslContextParameters
      id="sslContextParameters">
    <camel:keyManagers
        keyPassword="keyPassword">
      <camel:keyStore
          resource="/users/home/server/keystore.jks"
          password="keystorePassword"/>
    </camel:keyManagers>
  </camel:sslContextParameters>...
...
  <to uri="ahc:https://localhost/foo?sslContextParameters=#sslContextParameters"/>
...
Copy to Clipboard Toggle word wrap

3.15. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • Jetty
  • HTTP
  • HTTP4

Chapter 4. AHC Websocket Component

Available as of Camel version 2.14

The ahc-ws component provides Websocket based endpoints for a client communicating with external servers over Websocket (as a client opening a websocket connection to an external server).
The component uses the AHC component that in turn uses the Async Http Client library.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-ahc-ws</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

4.1. URI Format

ahc-ws://hostname[:port][/resourceUri][?options]
ahc-wss://hostname[:port][/resourceUri][?options]
Copy to Clipboard Toggle word wrap

Will by default use port 80 for ahc-ws and 443 for ahc-wss.

4.2. AHC-WS Options

As the AHC-WS component is based on the AHC component, you can use the various configuration options of the AHC component.

The AHC Websocket component supports 8 options which are listed below.

Expand
NameDescriptionDefaultType

client (advanced)

To use a custom AsyncHttpClient

 

AsyncHttpClient

binding (advanced)

To use a custom AhcBinding which allows to control how to bind between AHC and Camel.

 

AhcBinding

clientConfig (advanced)

To configure the AsyncHttpClient to use a custom com.ning.http.client.AsyncHttpClientConfig instance.

 

AsyncHttpClientConfig

sslContextParameters (security)

Reference to a org.apache.camel.util.jsse.SSLContextParameters in the Registry. Note that configuring this option will override any SSL/TLS configuration options provided through the clientConfig option at the endpoint or component level.

 

SSLContextParameters

allowJavaSerialized Object (advanced)

Whether to allow java serialization when a request uses context-type=application/x-java-serialized-object This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk.

false

boolean

useGlobalSslContext Parameters (security)

Enable usage of global SSL context parameters.

false

boolean

headerFilterStrategy (filter)

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

 

HeaderFilterStrategy

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AHC Websocket endpoint is configured using URI syntax:

ahc-ws:httpUri
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

4.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

httpUri

Required The URI to use such as http://hostname:port/path

 

URI

4.2.2. Query Parameters (18 parameters):

Expand
NameDescriptionDefaultType

bridgeEndpoint (common)

If the option is true, then the Exchange.HTTP_URI header is ignored, and use the endpoint’s URI for request. You may also set the throwExceptionOnFailure to be false to let the AhcProducer send all the fault response back.

false

boolean

bufferSize (common)

The initial in-memory buffer size used when transferring data between Camel and AHC Client.

4096

int

headerFilterStrategy (common)

To use a custom HeaderFilterStrategy to filter header to and from Camel message.

 

HeaderFilterStrategy

throwExceptionOnFailure (common)

Option to disable throwing the AhcOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code.

true

boolean

transferException (common)

If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized in the response as a application/x-java-serialized-object content type (for example using Jetty or Servlet Camel components). On the producer side the exception will be deserialized and thrown as is, instead of the AhcOperationFailedException. The caused exception is required to be serialized. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk.

false

boolean

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

sendMessageOnError (consumer)

Whether to send an message if the web-socket listener received an error.

false

boolean

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

connectionClose (producer)

Define if the Connection Close header has to be added to HTTP Request. This parameter is false by default

false

boolean

cookieHandler (producer)

Configure a cookie handler to maintain a HTTP session

 

CookieHandler

useStreaming (producer)

To enable streaming to send data as multiple text fragments.

false

boolean

binding (advanced)

To use a custom AhcBinding which allows to control how to bind between AHC and Camel.

 

AhcBinding

clientConfig (advanced)

To configure the AsyncHttpClient to use a custom com.ning.http.client.AsyncHttpClientConfig instance.

 

AsyncHttpClientConfig

clientConfigOptions (advanced)

To configure the AsyncHttpClientConfig using the key/values from the Map.

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

clientConfigRealmOptions (security)

To configure the AsyncHttpClientConfig Realm using the key/values from the Map.

 

Map

sslContextParameters (security)

Reference to a org.apache.camel.util.jsse.SSLContextParameters in the Registry. This reference overrides any configured SSLContextParameters at the component level. See Using the JSSE Configuration Utility. Note that configuring this option will override any SSL/TLS configuration options provided through the clientConfig option at the endpoint or component level.

 

SSLContextParameters

4.3. Writing and Reading Data over Websocket

An ahc-ws 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.

4.4. Configuring URI to Write or Read Data

In the route below, Camel will write to the specified websocket connection.

from("direct:start")
        .to("ahc-ws://targethost");
Copy to Clipboard Toggle word wrap

And the equivalent Spring sample:

<camelContext xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="direct:start"/>
    <to uri="ahc-ws://targethost"/>
  </route>
</camelContext>
Copy to Clipboard Toggle word wrap

In the route below, Camel will read from the specified websocket connection.

from("ahc-ws://targethost")
        .to("direct:next");
Copy to Clipboard Toggle word wrap

And the equivalent Spring sample:

<camelContext xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="ahc-ws://targethost"/>
    <to uri="direct:next"/>
  </route>
</camelContext>
Copy to Clipboard Toggle word wrap

 

4.5. See Also

Chapter 5. AMQP Component

Available as of Camel version 1.2

The amqp: component supports the AMQP 1.0 protocol using the JMS Client API of the Qpid project. In case you want to use AMQP 0.9 (in particular RabbitMQ) you might also be interested in the Camel RabbitMQ component. Please keep in mind that prior to the Camel 2.17.0 AMQP component supported AMQP 0.9 and above, however since Camel 2.17.0 it supports only AMQP 1.0.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-amqp</artifactId>
    <version>${camel.version}</version> <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

5.1. URI format

amqp:[queue:|topic:]destinationName[?options]
Copy to Clipboard Toggle word wrap

5.2. AMQP Options

You can specify all of the various configuration options of the JMS component after the destination name.

The AMQP component supports 80 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

To use a shared JMS configuration

 

JmsConfiguration

acceptMessagesWhile Stopping (consumer)

Specifies whether the consumer accept messages while it is stopping. You may consider enabling this option, if you start and stop JMS routes at runtime, while there are still messages enqueued on the queue. If this option is false, and you stop the JMS route, then messages may be rejected, and the JMS broker would have to attempt redeliveries, which yet again may be rejected, and eventually the message may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option.

false

boolean

allowReplyManagerQuick Stop (consumer)

Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfigurationisAcceptMessagesWhileStopping is enabled, and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by default in the regular JMS consumers but to enable for reply managers you must enable this flag.

false

boolean

acknowledgementMode (consumer)

The JMS acknowledgement mode defined as an Integer. Allows you to set vendor-specific extensions to the acknowledgment mode.For the regular modes, it is preferable to use the acknowledgementModeName instead.

 

int

eagerLoadingOf Properties (consumer)

Enables eager loading of JMS properties as soon as a message is loaded which generally is inefficient as the JMS properties may not be required but sometimes can catch early any issues with the underlying JMS provider and the use of JMS properties

false

boolean

acknowledgementModeName (consumer)

The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE

AUTO_ ACKNOWLEDGE

String

autoStartup (consumer)

Specifies whether the consumer container should auto-startup.

true

boolean

cacheLevel (consumer)

Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details.

 

int

cacheLevelName (consumer)

Sets the cache level by name for the underlying JMS resources. Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, and CACHE_SESSION. The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information.

CACHE_AUTO

String

replyToCacheLevelName (producer)

Sets the cache level by name for the reply consumer when doing request/reply over JMS. This option only applies when using fixed reply queues (not temporary). Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere may require to set the replyToCacheLevelName=CACHE_NONE to work. Note: If using temporary queues then CACHE_NONE is not allowed, and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION.

 

String

clientId (common)

Sets the JMS client ID to use. Note that this value, if specified, must be unique and can only be used by a single JMS connection instance. It is typically only required for durable topic subscriptions. If using Apache ActiveMQ you may prefer to use Virtual Topics instead.

 

String

concurrentConsumers (consumer)

Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number of concurrent consumers on the reply message listener.

1

int

replyToConcurrent Consumers (producer)

Specifies the default number of concurrent consumers when doing request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads.

1

int

connectionFactory (common)

The connection factory to be use. A connection factory must be configured either on the component or endpoint.

 

ConnectionFactory

username (security)

Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.

 

String

password (security)

Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.

 

String

deliveryPersistent (producer)

Specifies whether persistent delivery is used by default.

true

boolean

deliveryMode (producer)

Specifies the delivery mode to be used. Possibles values are those defined by javax.jms.DeliveryMode. NON_PERSISTENT = 1 and PERSISTENT = 2.

 

Integer

durableSubscriptionName (common)

The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well.

 

String

exceptionListener (advanced)

Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions.

 

ExceptionListener

errorHandler (advanced)

Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. By default these exceptions will be logged at the WARN level, if no errorHandler has been configured. You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options. This makes it much easier to configure, than having to code a custom errorHandler.

 

ErrorHandler

errorHandlerLogging Level (logging)

Allows to configure the default errorHandler logging level for logging uncaught exceptions.

WARN

LoggingLevel

errorHandlerLogStack Trace (logging)

Allows to control whether stacktraces should be logged or not, by the default errorHandler.

true

boolean

explicitQosEnabled (producer)

Set if the deliveryMode, priority or timeToLive qualities of service should be used when sending messages. This option is based on Spring’s JmsTemplate. The deliveryMode, priority and timeToLive options are applied to the current endpoint. This contrasts with the preserveMessageQos option, which operates at message granularity, reading QoS properties exclusively from the Camel In message headers.

false

boolean

exposeListenerSession (consumer)

Specifies whether the listener session should be exposed when consuming messages.

false

boolean

idleTaskExecutionLimit (advanced)

Specifies the limit for idle executions of a receive task, not having received any message within its execution. If this limit is reached, the task will shut down and leave receiving to other executing tasks (in the case of dynamic scheduling; see the maxConcurrentConsumers setting). There is additional doc available from Spring.

1

int

idleConsumerLimit (advanced)

Specify the limit for the number of consumers that are allowed to be idle at any given time.

1

int

maxConcurrentConsumers (consumer)

Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number of concurrent consumers on the reply message listener.

 

int

replyToMaxConcurrent Consumers (producer)

Specifies the maximum number of concurrent consumers when using request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads.

 

int

replyOnTimeoutToMax ConcurrentConsumers (producer)

Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS.

1

int

maxMessagesPerTask (advanced)

The number of messages per task. -1 is unlimited. If you use a range for concurrent consumers (eg min max), then this option can be used to set a value to eg 100 to control how fast the consumers will shrink when less work is required.

-1

int

messageConverter (advanced)

To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control how to map to/from a javax.jms.Message.

 

MessageConverter

mapJmsMessage (advanced)

Specifies whether Camel should auto map the received JMS message to a suited payload type, such as javax.jms.TextMessage to a String etc.

true

boolean

messageIdEnabled (advanced)

When sending, specifies whether message IDs should be added. This is just an hint to the JMS broker.If the JMS provider accepts this hint, these messages must have the message ID set to null; if the provider ignores the hint, the message ID must be set to its normal unique value

true

boolean

messageTimestampEnabled (advanced)

Specifies whether timestamps should be enabled by default on sending messages. This is just an hint to the JMS broker.If the JMS provider accepts this hint, these messages must have the timestamp set to zero; if the provider ignores the hint the timestamp must be set to its normal value

true

boolean

alwaysCopyMessage (producer)

If true, Camel will always make a JMS message copy of the message when it is passed to the producer for sending. Copying the message is needed in some situations, such as when a replyToDestinationSelectorName is set (incidentally, Camel will set the alwaysCopyMessage option to true, if a replyToDestinationSelectorName is set)

false

boolean

useMessageIDAs CorrelationID (advanced)

Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages.

false

boolean

priority (producer)

Values greater than 1 specify the message priority when sending (where 0 is the lowest priority and 9 is the highest). The explicitQosEnabled option must also be enabled in order for this option to have any effect.

4

int

pubSubNoLocal (advanced)

Specifies whether to inhibit the delivery of messages published by its own connection.

false

boolean

receiveTimeout (advanced)

The timeout for receiving messages (in milliseconds).

1000

long

recoveryInterval (advanced)

Specifies the interval between recovery attempts, i.e. when a connection is being refreshed, in milliseconds. The default is 5000 ms, that is, 5 seconds.

5000

long

taskExecutor (consumer)

Allows you to specify a custom task executor for consuming messages.

 

TaskExecutor

timeToLive (producer)

When sending messages, specifies the time-to-live of the message (in milliseconds).

-1

long

transacted (transaction)

Specifies whether to use transacted mode

false

boolean

lazyCreateTransaction Manager (transaction)

If true, Camel will create a JmsTransactionManager, if there is no transactionManager injected when option transacted=true.

true

boolean

transactionManager (transaction)

The Spring transaction manager to use.

 

PlatformTransaction Manager

transactionName (transaction)

The name of the transaction to use.

 

String

transactionTimeout (transaction)

The timeout value of the transaction (in seconds), if using transacted mode.

-1

int

testConnectionOn Startup (common)

Specifies whether to test the connection on startup. This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. If a connection cannot be granted then Camel throws an exception on startup. This ensures that Camel is not started with failed connections. The JMS producers is tested as well.

false

boolean

asyncStartListener (advanced)

Whether to startup the JmsConsumer message listener asynchronously, when starting a route. For example if a JmsConsumer cannot get a connection to a remote JMS broker, then it may block while retrying and/or failover. This will cause Camel to block while starting routes. By setting this option to true, you will let routes startup, while the JmsConsumer connects to the JMS broker using a dedicated thread in asynchronous mode. If this option is used, then beware that if the connection could not be established, then an exception is logged at WARN level, and the consumer will not be able to receive messages; You can then restart the route to retry.

false

boolean

asyncStopListener (advanced)

Whether to stop the JmsConsumer message listener asynchronously, when stopping a route.

false

boolean

forceSendOriginal Message (producer)

When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination if you touch the headers (get or set) during the route. Set this option to true to force Camel to send the original JMS message that was received.

false

boolean

requestTimeout (producer)

The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). The default is 20 seconds. You can include the header CamelJmsRequestTimeout to override this endpoint configured timeout value, and thus have per message individual timeout values. See also the requestTimeoutCheckerInterval option.

20000

long

requestTimeoutChecker Interval (advanced)

Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS. By default Camel checks once per second. But if you must react faster when a timeout occurs, then you can lower this interval, to check more frequently. The timeout is determined by the option requestTimeout.

1000

long

transferExchange (advanced)

You can transfer the exchange over the wire instead of just the body and headers. The following fields are transferred: In body, Out body, Fault body, In headers, Out headers, Fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. You must enable this option on both the producer and consumer side, so Camel knows the payloads is an Exchange and not a regular payload.

false

boolean

transferException (advanced)

If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side, then the caused Exception will be send back in response as a javax.jms.ObjectMessage. If the client is Camel, the returned Exception is rethrown. This allows you to use Camel JMS as a bridge in your routing - for example, using persistent queues to enable robust routing. Notice that if you also have transferExchange enabled, this option takes precedence. The caught exception is required to be serializable. The original Exception on the consumer side can be wrapped in an outer exception such as org.apache.camel.RuntimeCamelException when returned to the producer.

false

boolean

transferFault (advanced)

If enabled and you are using Request Reply messaging (InOut) and an Exchange failed with a SOAP fault (not exception) on the consumer side, then the fault flag on MessageisFault() will be send back in the response as a JMS header with the key org.apache.camel.component.jms.JmsConstantsJMS_TRANSFER_FAULTJMS_TRANSFER_FAULT. If the client is Camel, the returned fault flag will be set on the link org.apache.camel.MessagesetFault(boolean). You may want to enable this when using Camel components that support faults such as SOAP based such as cxf or spring-ws.

false

boolean

jmsOperations (advanced)

Allows you to use your own implementation of the org.springframework.jms.core.JmsOperations interface. Camel uses JmsTemplate as default. Can be used for testing purpose, but not used much as stated in the spring API docs.

 

JmsOperations

destinationResolver (advanced)

A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver (for example, to lookup the real destination in a JNDI registry).

 

DestinationResolver

replyToType (producer)

Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. Possible values are: Temporary, Shared, or Exclusive. By default Camel will use temporary queues. However if replyTo has been configured, then Shared is used by default. This option allows you to use exclusive queues instead of shared ones. See Camel JMS documentation for more details, and especially the notes about the implications if running in a clustered environment, and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive.

 

ReplyToType

preserveMessageQos (producer)

Set to true, if you want to send message using the QoS settings specified on the message, instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority, JMSDeliveryMode, and JMSExpiration. You can provide all or only some of them. If not provided, Camel will fall back to use the values from the endpoint instead. So, when using this option, the headers override the values from the endpoint. The explicitQosEnabled option, by contrast, will only use options set on the endpoint, and not values from the message header.

false

boolean

asyncConsumer (consumer)

Whether the JmsConsumer processes the Exchange asynchronously. If enabled then the JmsConsumer may pickup the next message from the JMS queue, while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). This means that messages may be processed not 100% strictly in order. If disabled (as default) then the Exchange is fully processed before the JmsConsumer will pickup the next message from the JMS queue. Note if transacted has been enabled, then asyncConsumer=true does not run asynchronously, as transaction must be executed synchronously (Camel 3.0 may support async transactions).

false

boolean

allowNullBody (producer)

Whether to allow sending messages with no body. If this option is false and the message body is null, then an JMSException is thrown.

true

boolean

includeSentJMS MessageID (producer)

Only applicable when sending to JMS destination using InOnly (eg fire and forget). Enabling this option will enrich the Camel Exchange with the actual JMSMessageID that was used by the JMS client when the message was sent to the JMS destination.

false

boolean

includeAllJMSX Properties (advanced)

Whether to include all JMSXxxx properties when mapping from JMS to Camel Message. Setting this to true will include properties such as JMSXAppID, and JMSXUserID etc. Note: If you are using a custom headerFilterStrategy then this option does not apply.

false

boolean

defaultTaskExecutor Type (consumer)

Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer, for both consumer endpoints and the ReplyTo consumer of producer endpoints. Possible values: SimpleAsync (uses Spring’s SimpleAsyncTaskExecutor) or ThreadPool (uses Spring’s ThreadPoolTaskExecutor with optimal values - cached threadpool-like). If not set, it defaults to the previous behaviour, which uses a cached thread pool for consumer endpoints and SimpleAsync for reply consumers. The use of ThreadPool is recommended to reduce thread trash in elastic configurations with dynamically increasing and decreasing concurrent consumers.

 

DefaultTaskExecutor Type

jmsKeyFormatStrategy (advanced)

Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. Camel provides two implementations out of the box: default and passthrough. The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy and refer to it using the notation.

 

JmsKeyFormatStrategy

allowAdditionalHeaders (producer)

This option is used to allow additional headers which may have values that are invalid according to JMS specification. For example some message systems such as WMQ do this with header names using prefix JMS_IBM_MQMD_ containing values with byte array or other invalid types. You can specify multiple header names separated by comma, and use as suffix for wildcard matching.

 

String

queueBrowseStrategy (advanced)

To use a custom QueueBrowseStrategy when browsing queues

 

QueueBrowseStrategy

messageCreatedStrategy (advanced)

To use the given MessageCreatedStrategy which are invoked when Camel creates new instances of javax.jms.Message objects when Camel is sending a JMS message.

 

MessageCreatedStrategy

waitForProvision CorrelationToBeUpdated Counter (advanced)

Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS and when the option useMessageIDAsCorrelationID is enabled.

50

int

waitForProvision CorrelationToBeUpdated ThreadSleepingTime (advanced)

Interval in millis to sleep each time while waiting for provisional correlation id to be updated.

100

long

correlationProperty (producer)

Use this JMS property to correlate messages in InOut exchange pattern (request-reply) instead of JMSCorrelationID property. This allows you to exchange messages with systems that do not correlate messages using JMSCorrelationID JMS property. If used JMSCorrelationID will not be used or set by Camel. The value of here named property will be generated if not supplied in the header of the message under the same name.

 

String

subscriptionDurable (consumer)

Set whether to make the subscription durable. The durable subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a durable subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well.

false

boolean

subscriptionShared (consumer)

Set whether to make the subscription shared. The shared subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a shared subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Note that shared subscriptions may also be durable, so this flag can (and often will) be combined with subscriptionDurable as well. Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well. Requires a JMS 2.0 compatible message broker.

false

boolean

subscriptionName (consumer)

Set the name of a subscription to create. To be applied in case of a topic (pub-sub domain) with a shared or durable subscription. The subscription name needs to be unique within this client’s JMS client id. Default is the class name of the specified message listener. Note: Only 1 concurrent consumer (which is the default of this message listener container) is allowed for each subscription, except for a shared subscription (which requires JMS 2.0).

 

String

streamMessageType Enabled (producer)

Sets whether StreamMessage type is enabled or not. Message payloads of streaming kind such as files, InputStream, etc will either by sent as BytesMessage or StreamMessage. This option controls which kind will be used. By default BytesMessage is used which enforces the entire message payload to be read into memory. By enabling this option the message payload is read into memory in chunks and each chunk is then written to the StreamMessage until no more data.

false

boolean

formatDateHeadersTo Iso8601 (producer)

Sets whether date headers should be formatted according to the ISO 8601 standard.

false

boolean

headerFilterStrategy (filter)

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

 

HeaderFilterStrategy

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AMQP endpoint is configured using URI syntax:

amqp:destinationType:destinationName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

5.2.1. Path Parameters (2 parameters):

Expand
NameDescriptionDefaultType

destinationType

The kind of destination to use

queue

String

destinationName

Required Name of the queue or topic to use as destination

 

String

5.2.2. Query Parameters (91 parameters):

Expand
NameDescriptionDefaultType

clientId (common)

Sets the JMS client ID to use. Note that this value, if specified, must be unique and can only be used by a single JMS connection instance. It is typically only required for durable topic subscriptions. If using Apache ActiveMQ you may prefer to use Virtual Topics instead.

 

String

connectionFactory (common)

The connection factory to be use. A connection factory must be configured either on the component or endpoint.

 

ConnectionFactory

disableReplyTo (common)

Specifies whether Camel ignores the JMSReplyTo header in messages. If true, Camel does not send a reply back to the destination specified in the JMSReplyTo header. You can use this option if you want Camel to consume from a route and you do not want Camel to automatically send back a reply message because another component in your code handles the reply message. You can also use this option if you want to use Camel as a proxy between different message brokers and you want to route message from one system to another.

false

boolean

durableSubscriptionName (common)

The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well.

 

String

jmsMessageType (common)

Allows you to force the use of a specific javax.jms.Message implementation for sending JMS messages. Possible values are: Bytes, Map, Object, Stream, Text. By default, Camel would determine which JMS message type to use from the In body type. This option allows you to specify it.

 

JmsMessageType

testConnectionOnStartup (common)

Specifies whether to test the connection on startup. This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. If a connection cannot be granted then Camel throws an exception on startup. This ensures that Camel is not started with failed connections. The JMS producers is tested as well.

false

boolean

acknowledgementModeName (consumer)

The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE

AUTO_ ACKNOWLEDGE

String

asyncConsumer (consumer)

Whether the JmsConsumer processes the Exchange asynchronously. If enabled then the JmsConsumer may pickup the next message from the JMS queue, while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). This means that messages may be processed not 100% strictly in order. If disabled (as default) then the Exchange is fully processed before the JmsConsumer will pickup the next message from the JMS queue. Note if transacted has been enabled, then asyncConsumer=true does not run asynchronously, as transaction must be executed synchronously (Camel 3.0 may support async transactions).

false

boolean

autoStartup (consumer)

Specifies whether the consumer container should auto-startup.

true

boolean

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

cacheLevel (consumer)

Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details.

 

int

cacheLevelName (consumer)

Sets the cache level by name for the underlying JMS resources. Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, and CACHE_SESSION. The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information.

CACHE_AUTO

String

concurrentConsumers (consumer)

Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number of concurrent consumers on the reply message listener.

1

int

maxConcurrentConsumers (consumer)

Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number of concurrent consumers on the reply message listener.

 

int

replyTo (consumer)

Provides an explicit ReplyTo destination, which overrides any incoming value of Message.getJMSReplyTo().

 

String

replyToDeliveryPersistent (consumer)

Specifies whether to use persistent delivery by default for replies.

true

boolean

selector (consumer)

Sets the JMS selector to use

 

String

subscriptionDurable (consumer)

Set whether to make the subscription durable. The durable subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a durable subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well.

false

boolean

subscriptionName (consumer)

Set the name of a subscription to create. To be applied in case of a topic (pub-sub domain) with a shared or durable subscription. The subscription name needs to be unique within this client’s JMS client id. Default is the class name of the specified message listener. Note: Only 1 concurrent consumer (which is the default of this message listener container) is allowed for each subscription, except for a shared subscription (which requires JMS 2.0).

 

String

subscriptionShared (consumer)

Set whether to make the subscription shared. The shared subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a shared subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Note that shared subscriptions may also be durable, so this flag can (and often will) be combined with subscriptionDurable as well. Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well. Requires a JMS 2.0 compatible message broker.

false

boolean

acceptMessagesWhileStopping (consumer)

Specifies whether the consumer accept messages while it is stopping. You may consider enabling this option, if you start and stop JMS routes at runtime, while there are still messages enqueued on the queue. If this option is false, and you stop the JMS route, then messages may be rejected, and the JMS broker would have to attempt redeliveries, which yet again may be rejected, and eventually the message may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option.

false

boolean

allowReplyManagerQuickStop (consumer)

Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfigurationisAcceptMessagesWhileStopping is enabled, and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by default in the regular JMS consumers but to enable for reply managers you must enable this flag.

false

boolean

consumerType (consumer)

The consumer type to use, which can be one of: Simple, Default, or Custom. The consumer type determines which Spring JMS listener to use. Default will use org.springframework.jms.listener.DefaultMessageListenerContainer, Simple will use org.springframework.jms.listener.SimpleMessageListenerContainer. When Custom is specified, the MessageListenerContainerFactory defined by the messageListenerContainerFactory option will determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use.

Default

ConsumerType

defaultTaskExecutorType (consumer)

Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer, for both consumer endpoints and the ReplyTo consumer of producer endpoints. Possible values: SimpleAsync (uses Spring’s SimpleAsyncTaskExecutor) or ThreadPool (uses Spring’s ThreadPoolTaskExecutor with optimal values - cached threadpool-like). If not set, it defaults to the previous behaviour, which uses a cached thread pool for consumer endpoints and SimpleAsync for reply consumers. The use of ThreadPool is recommended to reduce thread trash in elastic configurations with dynamically increasing and decreasing concurrent consumers.

 

DefaultTaskExecutor Type

eagerLoadingOfProperties (consumer)

Enables eager loading of JMS properties and payload as soon as a message is loaded which generally is inefficient as the JMS properties may not be required but sometimes can catch early any issues with the underlying JMS provider and the use of JMS properties

false

boolean

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

exposeListenerSession (consumer)

Specifies whether the listener session should be exposed when consuming messages.

false

boolean

replyToSameDestination Allowed (consumer)

Whether a JMS consumer is allowed to send a reply message to the same destination that the consumer is using to consume from. This prevents an endless loop by consuming and sending back the same message to itself.

false

boolean

taskExecutor (consumer)

Allows you to specify a custom task executor for consuming messages.

 

TaskExecutor

deliveryMode (producer)

Specifies the delivery mode to be used. Possibles values are those defined by javax.jms.DeliveryMode. NON_PERSISTENT = 1 and PERSISTENT = 2.

 

Integer

deliveryPersistent (producer)

Specifies whether persistent delivery is used by default.

true

boolean

explicitQosEnabled (producer)

Set if the deliveryMode, priority or timeToLive qualities of service should be used when sending messages. This option is based on Spring’s JmsTemplate. The deliveryMode, priority and timeToLive options are applied to the current endpoint. This contrasts with the preserveMessageQos option, which operates at message granularity, reading QoS properties exclusively from the Camel In message headers.

false

Boolean

formatDateHeadersToIso8601 (producer)

Sets whether JMS date properties should be formatted according to the ISO 8601 standard.

false

boolean

preserveMessageQos (producer)

Set to true, if you want to send message using the QoS settings specified on the message, instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority, JMSDeliveryMode, and JMSExpiration. You can provide all or only some of them. If not provided, Camel will fall back to use the values from the endpoint instead. So, when using this option, the headers override the values from the endpoint. The explicitQosEnabled option, by contrast, will only use options set on the endpoint, and not values from the message header.

false

boolean

priority (producer)

Values greater than 1 specify the message priority when sending (where 0 is the lowest priority and 9 is the highest). The explicitQosEnabled option must also be enabled in order for this option to have any effect.

4

int

replyToConcurrentConsumers (producer)

Specifies the default number of concurrent consumers when doing request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads.

1

int

replyToMaxConcurrent Consumers (producer)

Specifies the maximum number of concurrent consumers when using request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads.

 

int

replyToOnTimeoutMax ConcurrentConsumers (producer)

Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS.

1

int

replyToOverride (producer)

Provides an explicit ReplyTo destination in the JMS message, which overrides the setting of replyTo. It is useful if you want to forward the message to a remote Queue and receive the reply message from the ReplyTo destination.

 

String

replyToType (producer)

Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. Possible values are: Temporary, Shared, or Exclusive. By default Camel will use temporary queues. However if replyTo has been configured, then Shared is used by default. This option allows you to use exclusive queues instead of shared ones. See Camel JMS documentation for more details, and especially the notes about the implications if running in a clustered environment, and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive.

 

ReplyToType

requestTimeout (producer)

The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). The default is 20 seconds. You can include the header CamelJmsRequestTimeout to override this endpoint configured timeout value, and thus have per message individual timeout values. See also the requestTimeoutCheckerInterval option.

20000

long

timeToLive (producer)

When sending messages, specifies the time-to-live of the message (in milliseconds).

-1

long

allowAdditionalHeaders (producer)

This option is used to allow additional headers which may have values that are invalid according to JMS specification. For example some message systems such as WMQ do this with header names using prefix JMS_IBM_MQMD_ containing values with byte array or other invalid types. You can specify multiple header names separated by comma, and use as suffix for wildcard matching.

 

String

allowNullBody (producer)

Whether to allow sending messages with no body. If this option is false and the message body is null, then an JMSException is thrown.

true

boolean

alwaysCopyMessage (producer)

If true, Camel will always make a JMS message copy of the message when it is passed to the producer for sending. Copying the message is needed in some situations, such as when a replyToDestinationSelectorName is set (incidentally, Camel will set the alwaysCopyMessage option to true, if a replyToDestinationSelectorName is set)

false

boolean

correlationProperty (producer)

When using InOut exchange pattern use this JMS property instead of JMSCorrelationID JMS property to correlate messages. If set messages will be correlated solely on the value of this property JMSCorrelationID property will be ignored and not set by Camel.

 

String

disableTimeToLive (producer)

Use this option to force disabling time to live. For example when you do request/reply over JMS, then Camel will by default use the requestTimeout value as time to live on the message being sent. The problem is that the sender and receiver systems have to have their clocks synchronized, so they are in sync. This is not always so easy to archive. So you can use disableTimeToLive=true to not set a time to live value on the sent message. Then the message will not expire on the receiver system. See below in section About time to live for more details.

false

boolean

forceSendOriginalMessage (producer)

When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination if you touch the headers (get or set) during the route. Set this option to true to force Camel to send the original JMS message that was received.

false

boolean

includeSentJMSMessageID (producer)

Only applicable when sending to JMS destination using InOnly (eg fire and forget). Enabling this option will enrich the Camel Exchange with the actual JMSMessageID that was used by the JMS client when the message was sent to the JMS destination.

false

boolean

replyToCacheLevelName (producer)

Sets the cache level by name for the reply consumer when doing request/reply over JMS. This option only applies when using fixed reply queues (not temporary). Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere may require to set the replyToCacheLevelName=CACHE_NONE to work. Note: If using temporary queues then CACHE_NONE is not allowed, and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION.

 

String

replyToDestinationSelector Name (producer)

Sets the JMS Selector using the fixed name to be used so you can filter out your own replies from the others when using a shared queue (that is, if you are not using a temporary reply queue).

 

String

streamMessageTypeEnabled (producer)

Sets whether StreamMessage type is enabled or not. Message payloads of streaming kind such as files, InputStream, etc will either by sent as BytesMessage or StreamMessage. This option controls which kind will be used. By default BytesMessage is used which enforces the entire message payload to be read into memory. By enabling this option the message payload is read into memory in chunks and each chunk is then written to the StreamMessage until no more data.

false

boolean

allowSerializedHeaders (advanced)

Controls whether or not to include serialized headers. Applies only when transferExchange is true. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level.

false

boolean

asyncStartListener (advanced)

Whether to startup the JmsConsumer message listener asynchronously, when starting a route. For example if a JmsConsumer cannot get a connection to a remote JMS broker, then it may block while retrying and/or failover. This will cause Camel to block while starting routes. By setting this option to true, you will let routes startup, while the JmsConsumer connects to the JMS broker using a dedicated thread in asynchronous mode. If this option is used, then beware that if the connection could not be established, then an exception is logged at WARN level, and the consumer will not be able to receive messages; You can then restart the route to retry.

false

boolean

asyncStopListener (advanced)

Whether to stop the JmsConsumer message listener asynchronously, when stopping a route.

false

boolean

destinationResolver (advanced)

A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver (for example, to lookup the real destination in a JNDI registry).

 

DestinationResolver

errorHandler (advanced)

Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. By default these exceptions will be logged at the WARN level, if no errorHandler has been configured. You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options. This makes it much easier to configure, than having to code a custom errorHandler.

 

ErrorHandler

exceptionListener (advanced)

Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions.

 

ExceptionListener

headerFilterStrategy (advanced)

To use a custom HeaderFilterStrategy to filter header to and from Camel message.

 

HeaderFilterStrategy

idleConsumerLimit (advanced)

Specify the limit for the number of consumers that are allowed to be idle at any given time.

1

int

idleTaskExecutionLimit (advanced)

Specifies the limit for idle executions of a receive task, not having received any message within its execution. If this limit is reached, the task will shut down and leave receiving to other executing tasks (in the case of dynamic scheduling; see the maxConcurrentConsumers setting). There is additional doc available from Spring.

1

int

includeAllJMSXProperties (advanced)

Whether to include all JMSXxxx properties when mapping from JMS to Camel Message. Setting this to true will include properties such as JMSXAppID, and JMSXUserID etc. Note: If you are using a custom headerFilterStrategy then this option does not apply.

false

boolean

jmsKeyFormatStrategy (advanced)

Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. Camel provides two implementations out of the box: default and passthrough. The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy and refer to it using the notation.

 

String

mapJmsMessage (advanced)

Specifies whether Camel should auto map the received JMS message to a suited payload type, such as javax.jms.TextMessage to a String etc.

true

boolean

maxMessagesPerTask (advanced)

The number of messages per task. -1 is unlimited. If you use a range for concurrent consumers (eg min max), then this option can be used to set a value to eg 100 to control how fast the consumers will shrink when less work is required.

-1

int

messageConverter (advanced)

To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control how to map to/from a javax.jms.Message.

 

MessageConverter

messageCreatedStrategy (advanced)

To use the given MessageCreatedStrategy which are invoked when Camel creates new instances of javax.jms.Message objects when Camel is sending a JMS message.

 

MessageCreatedStrategy

messageIdEnabled (advanced)

When sending, specifies whether message IDs should be added. This is just an hint to the JMS broker.If the JMS provider accepts this hint, these messages must have the message ID set to null; if the provider ignores the hint, the message ID must be set to its normal unique value

true

boolean

messageListenerContainer Factory (advanced)

Registry ID of the MessageListenerContainerFactory used to determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use to consume messages. Setting this will automatically set consumerType to Custom.

 

MessageListener ContainerFactory

messageTimestampEnabled (advanced)

Specifies whether timestamps should be enabled by default on sending messages. This is just an hint to the JMS broker.If the JMS provider accepts this hint, these messages must have the timestamp set to zero; if the provider ignores the hint the timestamp must be set to its normal value

true

boolean

pubSubNoLocal (advanced)

Specifies whether to inhibit the delivery of messages published by its own connection.

false

boolean

receiveTimeout (advanced)

The timeout for receiving messages (in milliseconds).

1000

long

recoveryInterval (advanced)

Specifies the interval between recovery attempts, i.e. when a connection is being refreshed, in milliseconds. The default is 5000 ms, that is, 5 seconds.

5000

long

requestTimeoutChecker Interval (advanced)

Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS. By default Camel checks once per second. But if you must react faster when a timeout occurs, then you can lower this interval, to check more frequently. The timeout is determined by the option requestTimeout.

1000

long

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

transferException (advanced)

If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side, then the caused Exception will be send back in response as a javax.jms.ObjectMessage. If the client is Camel, the returned Exception is rethrown. This allows you to use Camel JMS as a bridge in your routing - for example, using persistent queues to enable robust routing. Notice that if you also have transferExchange enabled, this option takes precedence. The caught exception is required to be serializable. The original Exception on the consumer side can be wrapped in an outer exception such as org.apache.camel.RuntimeCamelException when returned to the producer.

false

boolean

transferExchange (advanced)

You can transfer the exchange over the wire instead of just the body and headers. The following fields are transferred: In body, Out body, Fault body, In headers, Out headers, Fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. You must enable this option on both the producer and consumer side, so Camel knows the payloads is an Exchange and not a regular payload.

false

boolean

transferFault (advanced)

If enabled and you are using Request Reply messaging (InOut) and an Exchange failed with a SOAP fault (not exception) on the consumer side, then the fault flag on MessageisFault() will be send back in the response as a JMS header with the key org.apache.camel.component.jms.JmsConstantsJMS_TRANSFER_FAULTJMS_TRANSFER_FAULT. If the client is Camel, the returned fault flag will be set on the link org.apache.camel.MessagesetFault(boolean). You may want to enable this when using Camel components that support faults such as SOAP based such as cxf or spring-ws.

false

boolean

useMessageIDAsCorrelation ID (advanced)

Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages.

false

boolean

waitForProvisionCorrelation ToBeUpdatedCounter (advanced)

Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS and when the option useMessageIDAsCorrelationID is enabled.

50

int

waitForProvisionCorrelation ToBeUpdatedThreadSleeping Time (advanced)

Interval in millis to sleep each time while waiting for provisional correlation id to be updated.

100

long

errorHandlerLoggingLevel (logging)

Allows to configure the default errorHandler logging level for logging uncaught exceptions.

WARN

LoggingLevel

errorHandlerLogStackTrace (logging)

Allows to control whether stacktraces should be logged or not, by the default errorHandler.

true

boolean

password (security)

Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.

 

String

username (security)

Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.

 

String

transacted (transaction)

Specifies whether to use transacted mode

false

boolean

lazyCreateTransaction Manager (transaction)

If true, Camel will create a JmsTransactionManager, if there is no transactionManager injected when option transacted=true.

true

boolean

transactionManager (transaction)

The Spring transaction manager to use.

 

PlatformTransaction Manager

transactionName (transaction)

The name of the transaction to use.

 

String

transactionTimeout (transaction)

The timeout value of the transaction (in seconds), if using transacted mode.

-1

int

5.3. Usage

As AMQP component is inherited from JMS component, the usage of the former is almost identical to the latter:

Using AMQP component

// Consuming from AMQP queue
from("amqp:queue:incoming").
  to(...);
 
// Sending message to the AMQP topic
from(...).
  to("amqp:topic:notify");
Copy to Clipboard Toggle word wrap

5.4. Configuring AMQP component

Starting from the Camel 2.16.1 you can also use the AMQPComponent#amqp10Component(String connectionURI) factory method to return the AMQP 1.0 component with the pre-configured topic prefix: 

Creating AMQP 1.0 component

 AMQPComponent amqp = AMQPComponent.amqp10Component("amqp://guest:guest@localhost:5672");
Copy to Clipboard Toggle word wrap

Keep in mind that starting from the Camel 2.17 the AMQPComponent#amqp10Component(String connectionURI) factory method has been deprecated on the behalf of the AMQPComponent#amqpComponent(String connectionURI)

Creating AMQP 1.0 component

AMQPComponent amqp = AMQPComponent.amqpComponent("amqp://localhost:5672");
 
AMQPComponent authorizedAmqp = AMQPComponent.amqpComponent("amqp://localhost:5672", "user", "password");
Copy to Clipboard Toggle word wrap

Starting from Camel 2.17, in order to automatically configure the AMQP component, you can also add an instance of org.apache.camel.component.amqp.AMQPConnectionDetails to the registry. For example for Spring Boot you just have to define bean:

AMQP connection details auto-configuration

@Bean
AMQPConnectionDetails amqpConnection() {
  return new AMQPConnectionDetails("amqp://localhost:5672");
}
 
@Bean
AMQPConnectionDetails securedAmqpConnection() {
  return new AMQPConnectionDetails("amqp://lcoalhost:5672", "username", "password");
}
Copy to Clipboard Toggle word wrap

Likewise, you can also use CDI producer methods when using Camel-CDI

AMQP connection details auto-configuration for CDI

@Produces
AMQPConnectionDetails amqpConnection() {
  return new AMQPConnectionDetails("amqp://localhost:5672");
}
Copy to Clipboard Toggle word wrap

You can also rely on the Camel properties to read the AMQP connection details. Factory method AMQPConnectionDetails.discoverAMQP() attempts to read Camel properties in a Kubernetes-like convention, just as demonstrated on the snippet below:

AMQP connection details auto-configuration

export AMQP_SERVICE_HOST = "mybroker.com"
export AMQP_SERVICE_PORT = "6666"
export AMQP_SERVICE_USERNAME = "username"
export AMQP_SERVICE_PASSWORD = "password"
 
...
 
@Bean
AMQPConnectionDetails amqpConnection() {
  return AMQPConnectionDetails.discoverAMQP();
}
Copy to Clipboard Toggle word wrap

Enabling AMQP specific options

If you, for example, need to enable amqp.traceFrames you can do that by appending the option to your URI, like the following example:

AMQPComponent amqp = AMQPComponent.amqpComponent("amqp://localhost:5672?amqp.traceFrames=true");
Copy to Clipboard Toggle word wrap

For reference take a look at the QPID JMS client configuration

5.5. Using topics

To have using topics working with camel-amqp you need to configure the component to use topic:// as topic prefix, as shown below:

 <bean id="amqp" class="org.apache.camel.component.amqp.AmqpComponent">
   <property name="connectionFactory">
     <bean class="org.apache.qpid.jms.JmsConnectionFactory" factory-method="createFromURL">
       <property name="remoteURI" value="amqp://localhost:5672" />
       <property name="topicPrefix" value="topic://" />  <!-- only necessary when connecting to ActiveMQ over AMQP 1.0 -->
     </bean>
   </property>
 </bean>
Copy to Clipboard Toggle word wrap

Keep in mind that both  AMQPComponent#amqpComponent() methods and AMQPConnectionDetails pre-configure the component with the topic prefix, so you don’t have to configure it explicitly.

5.6. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started

Chapter 6. APNS Component

Available as of Camel version 2.8

The apns component is used for sending notifications to iOS devices. The apns components use javapns library.
The component supports sending notifications to Apple Push Notification Servers (APNS) and consuming feedback from the servers.

The consumer is configured with 3600 seconds for polling by default because it is a best practice to consume feedback stream from Apple Push Notification Servers only from time to time. For example: every 1 hour to avoid flooding the servers.

The feedback stream gives informations about inactive devices. You only need to get this informations every some hours if your mobile application is not a heavily used one.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-apns</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

6.1. URI format

To send notifications:

apns:notify[?options]
Copy to Clipboard Toggle word wrap

To consume feedback:

apns:consumer[?options]
Copy to Clipboard Toggle word wrap

6.2. Options

The APNS component supports 2 options which are listed below.

Expand
NameDescriptionDefaultType

apnsService (common)

Required The ApnsService to use. The org.apache.camel.component.apns.factory.ApnsServiceFactory can be used to build a ApnsService

 

ApnsService

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The APNS endpoint is configured using URI syntax:

apns:name
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

6.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

name

Name of the endpoint

 

String

6.2.2. Query Parameters (20 parameters):

Expand
NameDescriptionDefaultType

tokens (common)

Configure this property in case you want to statically declare tokens related to devices you want to notify. Tokens are separated by comma.

 

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

pollStrategy (consumer)

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

 

PollingConsumerPoll Strategy

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

 

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

 

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

 

int

delay (scheduler)

Milliseconds before the next poll. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

initialDelay (scheduler)

Milliseconds before the first poll starts. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

1000

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

 

ScheduledExecutor Service

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz2 component

none

ScheduledPollConsumer Scheduler

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz2, Spring based scheduler.

 

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

You can append query options to the URI in the following format, ?option=value&option=value&…​

6.2.3. Component

The ApnsComponent must be configured with a com.notnoop.apns.ApnsService. The service can be created and configured using the org.apache.camel.component.apns.factory.ApnsServiceFactory. See further below for an example. And as well in the test source code.

6.2.3.1. SSL Setting

In order to use secure connection, an instance of org.apache.camel.util.jsse.SSLContextParameters should be injected to org.apache.camel.component.apns.factory.ApnsServiceFactory which is used to configure the component. See the test resources for an example. ssl example

6.3. Exchange data format

When Camel will fetch feedback data corresponding to inactive devices, it will retrieve a List of InactiveDevice objects. Each InactiveDevice object of the retrieved list will be setted as the In body, and then processed by the consumer endpoint.

6.4. Message Headers

Camel Apns uses these headers.

Expand
PropertyDefaultDescription

CamelApnsTokens

 

Empty by default.

CamelApnsMessageType

STRING, PAYLOAD, APNS_NOTIFICATION 

In case you choose PAYLOAD for the message type, then the message will be considered as a APNS payload and sent as is. In case you choose STRING, message will be converted as a APNS payload. From Camel 2.16 onwards APNS_NOTIFICATION is used for sending message body as com.notnoop.apns.ApnsNotification types.

6.5. ApnsServiceFactory builder callback

ApnsServiceFactory comes with the empty callback method that could be used to configure (or even replace) the default ApnsServiceBuilder instance. The signature of the method could look as follows:

protected ApnsServiceBuilder configureServiceBuilder(ApnsServiceBuilder serviceBuilder);
Copy to Clipboard Toggle word wrap

And could be used like as follows:

ApnsServiceFactory proxiedApnsServiceFactory = new ApnsServiceFactory(){
  
  @Override
  protected ApnsServiceBuilder configureServiceBuilder(ApnsServiceBuilder serviceBuilder) {
    return serviceBuilder.withSocksProxy("my.proxy.com", 6666);
  }

};
Copy to Clipboard Toggle word wrap

6.6. Samples

6.6.1. Camel Xml route

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <!-- Replace by desired values -->
    <bean id="apnsServiceFactory" class="org.apache.camel.component.apns.factory.ApnsServiceFactory">

        <!-- Optional configuration of feedback host and port -->
        <!-- <property name="feedbackHost" value="localhost" /> -->
        <!-- <property name="feedbackPort" value="7843" /> -->

        <!-- Optional configuration of gateway host and port -->
        <!-- <property name="gatewayHost" value="localhost" /> -->
        <!-- <property name="gatewayPort" value="7654" /> -->

        <!-- Declaration of certificate used -->
                <!-- from Camel 2.11 onwards you can use prefix: classpath:, file: to refer to load the certificate from classpath or file. Default it classpath -->
        <property name="certificatePath" value="certificate.p12" />
        <property name="certificatePassword" value="MyCertPassword" />

        <!-- Optional connection strategy - By Default: No need to configure -->
        <!-- Possible options: NON_BLOCKING, QUEUE, POOL or Nothing -->
        <!-- <property name="connectionStrategy" value="POOL" /> -->
        <!-- Optional pool size -->
        <!-- <property name="poolSize" value="15" /> -->

        <!-- Optional connection strategy - By Default: No need to configure -->
        <!-- Possible options: EVERY_HALF_HOUR, EVERY_NOTIFICATION or Nothing (Corresponds to NEVER javapns option) -->
        <!-- <property name="reconnectionPolicy" value="EVERY_HALF_HOUR" /> -->
    </bean>

    <bean id="apnsService" factory-bean="apnsServiceFactory" factory-method="getApnsService" />

    <!-- Replace this declaration by wanted configuration -->
    <bean id="apns" class="org.apache.camel.component.apns.ApnsComponent">
        <property name="apnsService" ref="apnsService" />
    </bean>

    <camelContext id="camel-apns-test" xmlns="http://camel.apache.org/schema/spring">
            <route id="apns-test">
                    <from uri="apns:consumer?initialDelay=10&amp;delay=3600&amp;timeUnit=SECONDS" />
                    <to uri="log:org.apache.camel.component.apns?showAll=true&amp;multiline=true" />
                    <to uri="mock:result" />
            </route>
    </camelContext>

</beans>
Copy to Clipboard Toggle word wrap

6.6.2. Camel Java route

Create camel context and declare apns component programmatically

    protected CamelContext createCamelContext() throws Exception {
        CamelContext camelContext = super.createCamelContext();

        ApnsServiceFactory apnsServiceFactory = new ApnsServiceFactory();
        apnsServiceFactory.setCertificatePath("classpath:/certificate.p12");
        apnsServiceFactory.setCertificatePassword("MyCertPassword");

        ApnsService apnsService = apnsServiceFactory.getApnsService(camelContext);

        ApnsComponent apnsComponent = new ApnsComponent(apnsService);
        camelContext.addComponent("apns", apnsComponent);

        return camelContext;
    }
Copy to Clipboard Toggle word wrap

[[APNS-ApnsProducer-iOStargetdevicedynamicallyconfiguredviaheader:"CamelApnsTokens"]] ApnsProducer - iOS target device dynamically configured via header: "CamelApnsTokens"

    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from("direct:test")
                    .setHeader(ApnsConstants.HEADER_TOKENS, constant(IOS_DEVICE_TOKEN))
                    .to("apns:notify");
                }
        }
    }
Copy to Clipboard Toggle word wrap

ApnsProducer - iOS target device statically configured via uri

    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from("direct:test").
                to("apns:notify?tokens=" + IOS_DEVICE_TOKEN);
            }
        };
    }
Copy to Clipboard Toggle word wrap

ApnsConsumer

from("apns:consumer?initialDelay=10&delay=3600&timeUnit=SECONDS")
    .to("log:com.apache.camel.component.apns?showAll=true&multiline=true")
    .to("mock:result");
Copy to Clipboard Toggle word wrap

6.7. See Also

Chapter 7. ASN.1 File DataFormat

Available as of Camel version 2.20

The ASN.1 Data Format Data Format [Intoduction to ASN.1](https://www.itu.int/en/ITU-T/asn1/Pages/introduction.aspx) is a Camel Frameworks’s data format implementation based on Bouncy Castle’s bcprov-jdk15on library and jASN.1’s java compiler for the formal notation used for describing data transmitted by telecommunications protocols, regardless of language implementation and physical representation of these data, whatever the application, whether complex or very simple. Messages can be unmarshalled (conversion to simple Java POJO(s)) to plain Java objects. By the help of Camel’s routing engine and data transformations you can then play with POJO(s) and apply customised formatting and call other Camel Component’s to convert and send messages to upstream systems.

7.1. ASN.1 Data Format Options

The ASN.1 File dataformat supports 3 options which are listed below.

Expand
NameDefaultJava TypeDescription

usingIterator

false

Boolean

If the asn1 file has more then one entry, the setting this option to true, allows to work with the splitter EIP, to split the data using an iterator in a streaming mode.

clazzName

 

String

Name of class to use when unmarshalling

contentTypeHeader

false

Boolean

Whether the data format should set the Content-Type header with the type from the data format if the data format is capable of doing so. For example application/xml for data formats marshalling to XML, or application/json for data formats marshalling to JSon etc.

7.2. Unmarshal

There are 3 different ways to unmarshal ASN.1 structured messages. (Usually binary files)

In this first example we unmarshal BER file payload to OutputStream and send it to mock endpoint.

from("direct:unmarshal").unmarshal(asn1).to("mock:unmarshal");
Copy to Clipboard Toggle word wrap

In the second example we unmarshal BER file payload to byte array using Split EIP. The reason for applying Split EIP is that usually each BER file or (ASN.1 structured file) contains multiple records to process and Split EIP helps us to get each record in a file as byte arrays which is actually ASN1Primitive’s instance (by the use of Bouncy Castle’s ASN.1 support in bcprov-jdk15on library) Byte arrays then may be converted to ASN1Primitive by the help of public static method in (ASN1Primitive.fromByteArray) In such example, note that you need to set usingIterator=true

from("direct:unmarshal").unmarshal(asn1).split(body(Iterator.class)).streaming().to("mock:unmarshal");
Copy to Clipboard Toggle word wrap

In the last example we unmarshal BER file payload to plain old Java Objects using Split EIP. The reason for applying Split EIP is already mentioned in the previous example. Please note and keep in mind that reason. In such example we also need to set the fully qualified name of the class or <YourObject>.class reference through data format. The important thing to note here is that your object should have been generated by jasn1 compiler which is a nice tool to generate java object representations of your ASN.1 structure. For the reference usage of jasn1 compiler see [JASN.1 Project Page](https://www.openmuc.org/asn1/) and please also see how the compiler is invoked with the help of maven’s exec plugin. For example, in this data format’s unit tests an example ASN.1 structure(TestSMSBerCdr.asn1) is added in src/test/resources/asn1_structure. jasn1 compiler is invoked and java object’s representations are generated in ${basedir}/target/generated/src/test/java The nice thing about this example, you will get POJO instance at the mock endpoint or at whatever your endpoint is.

from("direct:unmarshaldsl")
         .unmarshal()
         .asn1("org.apache.camel.dataformat.asn1.model.testsmscbercdr.SmsCdr")
         .split(body(Iterator.class)).streaming()
.to("mock:unmarshaldsl");
Copy to Clipboard Toggle word wrap

7.3. Dependencies

To use ASN.1 data format in your camel routes you need to add a dependency on camel-asn1 which implements this data format.

If you use Maven you can just add the following to your pom.xml, substituting the version number for the latest & greatest release (see the download page for the latest versions).

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-asn1</artifactId>
  <version>x.x.x</version>
  <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

Chapter 8. AS2 Component

Available as of Camel version 2.22

The AS2 component provides transport of EDI messages using the HTTP transfer protocol as specified in RFC4130.

Note

This component is currently a work in progress. Expect URI options and path and query parameters to change in future versions of this component.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-as2</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

8.1. URI format

as2://apiName/methodName
Copy to Clipboard Toggle word wrap

apiName can be one of:

  • client
  • server

8.2. AS2 Options

The AS2 component supports 2 options, which are listed below.

Expand
NameDescriptionDefaultType

configuration (common)

To use the shared configuration

 

AS2Configuration

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AS2 endpoint is configured using URI syntax:

as2:apiName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

8.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

apiName

Required What kind of operation to perform

 

AS2ApiName

8.2.2. Query Parameters (30 parameters):

Expand
NameDescriptionDefaultType

as2From (common)

The value of the AS2From header of AS2 message.

 

String

as2MessageStructure (common)

The structure of AS2 Message. One of: PLAIN - No encryption, no signature, SIGNED - No encryption, signature, ENCRYPTED - Encryption, no signature, ENCRYPTED_SIGNED - Encryption, signature

 

AS2MessageStructure

as2To (common)

The value of the AS2To header of AS2 message.

 

String

as2Version (common)

The version of the AS2 protocol.

1.1

String

clientFqdn (common)

The Client Fully Qualified Domain Name (FQDN). Used in message ids sent by endpoint.

camel.apache.org

String

dispositionNotificationTo (common)

The value of the Disposition-Notification-To header. Assigning a value to this parameter requests a message disposition notification (MDN) for the AS2 message.

 

String

ediMessageTransferEncoding (common)

The transfer encoding of EDI message.

 

String

ediMessageType (common)

The content type of EDI message. One of application/edifact, application/edi-x12, application/edi-consent

 

ContentType

encryptingAlgorithm (common)

The algorithm used to encrypt EDI message.

 

AS2EncryptionAlgorithm

encryptingCertificateChain (common)

The chain of certificates used to encrypt EDI message.

 

Certificate[]

encryptingPrivateKey (common)

The key used to encrypt the EDI message.

 

PrivateKey

from (common)

The value of the From header of AS2 message.

 

String

inBody (common)

Sets the name of a parameter to be passed in the exchange In Body

 

String

methodName (common)

Required What sub operation to use for the selected operation

 

String

requestUri (common)

The request URI of EDI message.

/

String

server (common)

The value included in the Server message header identifying the AS2 Server.

Camel AS2 Server Endpoint

String

serverFqdn (common)

The Server Fully Qualified Domain Name (FQDN). Used in message ids sent by endpoint.

camel.apache.org

String

serverPortNumber (common)

The port number of server.

 

Integer

signedReceiptMicAlgorithms (common)

The list of algorithms, in order of preference, requested to generate a message integrity check (MIC) returned in message dispostion notification (MDN)

 

String[]

signingAlgorithm (common)

The algorithm used to sign EDI message.

 

AS2SignatureAlgorithm

signingCertificateChain (common)

The chain of certificates used to sign EDI message.

 

Certificate[]

signingPrivateKey (common)

The key used to sign the EDI message.

 

PrivateKey

subject (common)

The value of Subject header of AS2 message.

 

String

targetHostname (common)

The host name (IP or DNS name) of target host.

 

String

targetPortNumber (common)

The port number of target host. -1 indicates the scheme default port.

 

Integer

userAgent (common)

The value included in the User-Agent message header identifying the AS2 user agent.

Camel AS2 Client Endpoint

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

8.3. Spring Boot Auto-Configuration

The component supports 28 options, which are listed below.

Expand
NameDescriptionDefaultType

camel.component.as2.configuration.api-name

What kind of operation to perform

 

AS2ApiName

camel.component.as2.configuration.as2-from

The value of the AS2From header of AS2 message.

 

String

camel.component.as2.configuration.as2-message-structure

The structure of AS2 Message. One of: PLAIN - No encryption, no signature, SIGNED - No encryption, signature, ENCRYPTED - Encryption, no signature, ENCRYPTED_SIGNED - Encryption, signature

 

AS2MessageStructure

camel.component.as2.configuration.as2-to

The value of the AS2To header of AS2 message.

 

String

camel.component.as2.configuration.as2-version

The version of the AS2 protocol.

1.1

String

camel.component.as2.configuration.client-fqdn

The Client Fully Qualified Domain Name (FQDN). Used in message ids sent by endpoint.

camel.apache.org

String

camel.component.as2.configuration.disposition-notification-to

The value of the Disposition-Notification-To header. Assigning a value to this parameter requests a message disposition notification (MDN) for the AS2 message.

 

String

camel.component.as2.configuration.edi-message-transfer-encoding

The transfer encoding of EDI message.

 

String

camel.component.as2.configuration.edi-message-type

The content type of EDI message. One of application/edifact, application/edi-x12, application/edi-consent

 

ContentType

camel.component.as2.configuration.encrypting-algorithm

The algorithm used to encrypt EDI message.

 

AS2EncryptionAlgorithm

camel.component.as2.configuration.encrypting-certificate-chain

The chain of certificates used to encrypt EDI message.

 

Certificate[]

camel.component.as2.configuration.encrypting-private-key

The key used to encrypt the EDI message.

 

PrivateKey

camel.component.as2.configuration.from

The value of the From header of AS2 message.

 

String

camel.component.as2.configuration.method-name

What sub operation to use for the selected operation

 

String

camel.component.as2.configuration.request-uri

The request URI of EDI message.

/

String

camel.component.as2.configuration.server

The value included in the Server message header identifying the AS2 Server.

Camel AS2 Server Endpoint

String

camel.component.as2.configuration.server-fqdn

The Server Fully Qualified Domain Name (FQDN). Used in message ids sent by endpoint.

camel.apache.org

String

camel.component.as2.configuration.server-port-number

The port number of server.

 

Integer

camel.component.as2.configuration.signed-receipt-mic-algorithms

The list of algorithms, in order of preference, requested to generate a message integrity check (MIC) returned in message dispostion notification (MDN)

 

String[]

camel.component.as2.configuration.signing-algorithm

The algorithm used to sign EDI message.

 

AS2SignatureAlgorithm

camel.component.as2.configuration.signing-certificate-chain

The chain of certificates used to sign EDI message.

 

Certificate[]

camel.component.as2.configuration.signing-private-key

The key used to sign the EDI message.

 

PrivateKey

camel.component.as2.configuration.subject

The value of Subject header of AS2 message.

 

String

camel.component.as2.configuration.target-hostname

The host name (IP or DNS name) of target host.

 

String

camel.component.as2.configuration.target-port-number

The port number of target host. -1 indicates the scheme default port.

 

Integer

camel.component.as2.configuration.user-agent

The value included in the User-Agent message header identifying the AS2 user agent.

Camel AS2 Client Endpoint

String

camel.component.as2.enabled

Whether to enable auto configuration of the as2 component. This is enabled by default.

 

Boolean

camel.component.as2.resolve-property-placeholders

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

Boolean

8.4. Client Endpoints:

Client endpoints use the endpoint prefix client followed by the name of a method and associated options described next. The endpoint URI MUST contain the prefix client.

as2://client/method?[options]
Copy to Clipboard Toggle word wrap

Endpoint options that are not mandatory are denoted by []. When there are no mandatory options for an endpoint, one of the set of [] options MUST be provided. Producer endpoints can also use a special option inBody that in turn should contain the name of the endpoint option whose value will be contained in the Camel Exchange In message.

Any of the endpoint options can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format CamelAS2.<option>. Note that the inBody option overrides message header, i.e. the endpoint option inBody=option would override a CamelAS2.option header.

If a value is not provided for the option defaultRequest either in the endpoint URI or in a message header, it will be assumed to be null. Note that the null value will only be used if other options do not satisfy matching endpoints.

In case of AS2 API errors the endpoint will throw a RuntimeCamelException with a org.apache.http.HttpException derived exception cause.

Expand
MethodOptionsResult Body Type

send

ediMessage, requestUri, subject, from, as2From, as2To, as2MessageStructure, ediMessageContentType, ediMessageTransferEncoding, dispositionNotificationTo, signedReceiptMicAlgorithms

org.apache.http.protocol.HttpCoreContext

URI Options for client

Expand
NameType

ediMessage

String

requestUri

String

subject

String

from

String

as2From

String

as2To

String

as2MessageStructure

org.apache.camel.component.as2.api.AS2MessageStructure

ediMessageContentType

String

ediMessageTransferEncoding

String

dispositionNotificationTo

String

signedReceiptMicAlgorithms

String[]

8.5. Server Endpoints:

Server endpoints use the endpoint prefix server followed by the name of a method and associated options described next. The endpoint URI MUST contain the prefix server.

as2://server/method?[options]
Copy to Clipboard Toggle word wrap

Endpoint options that are not mandatory are denoted by []. When there are no mandatory options for an endpoint, one of the set of [] options MUST be provided. Producer endpoints can also use a special option inBody that in turn should contain the name of the endpoint option whose value will be contained in the Camel Exchange In message.

Any of the endpoint options can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format CamelAS2.<option>. Note that the inBody option overrides message header, i.e. the endpoint option inBody=option would override a CamelAS2.option header.

If a value is not provided for the option defaultRequest either in the endpoint URI or in a message header, it will be assumed to be null. Note that the null value will only be used if other options do not satisfy matching endpoints.

In case of AS2 API errors the endpoint will throw a RuntimeCamelException with a org.apache.http.HttpException derived exception cause.

Expand
MethodOptionsResult Body Type

listen

requestUriPattern

org.apache.http.protocol.HttpCoreContext

URI Options for server

Expand
NameType

requestUriPattern

String

Chapter 9. Asterisk Component

Available as of Camel version 2.18

The asterisk: component allows you to work easily with an Asterisk PBX Server http://www.asterisk.org/ using asterisk-java

This component help to interface with Asterisk Manager Interface

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-asterisk</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

9.1. URI format

asterisk:name[?options]
Copy to Clipboard Toggle word wrap

9.2. Options

The Asterisk component has no options.

The Asterisk endpoint is configured using URI syntax:

asterisk:name
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

9.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

name

Required Logical name

 

String

9.2.2. Query Parameters (8 parameters):

Expand
NameDescriptionDefaultType

hostname (common)

Required The hostname of the asterisk server

 

String

password (common)

Required Login password

 

String

username (common)

Required Login username

 

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

action (producer)

What action to perform such as getting queue status, sip peers or extension state.

 

AsteriskAction

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

9.3. Action

Supported actions are:

  • QUEUE_STATUS, Queue Status
  • SIP_PEERS, List SIP Peers
  • EXTENSION_STATE, Check Extension Status

Chapter 10. Atmos Component

Available as of Camel version 2.15

Camel-Atmos is an Apache Camel component that allows you to work with ViPR object data services using the Atmos Client.

from("atmos:foo/get?remotePath=/path").to("mock:test");
Copy to Clipboard Toggle word wrap

10.1. Options

The Atmos component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

fullTokenId (security)

The token id to pass to the Atmos client

 

String

secretKey (security)

The secret key to pass to the Atmos client

 

String

uri (advanced)

The URI of the server for the Atmos client to connect to

 

String

sslValidation (security)

Whether the Atmos client should perform SSL validation

false

boolean

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Atmos endpoint is configured using URI syntax:

atmos:name/operation
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

10.1.1. Path Parameters (2 parameters):

Expand
NameDescriptionDefaultType

name

Atmos name

 

String

operation

Required Operation to perform

 

AtmosOperation

10.1.2. Query Parameters (12 parameters):

Expand
NameDescriptionDefaultType

enableSslValidation (common)

Atmos SSL validation

false

boolean

fullTokenId (common)

Atmos client fullTokenId

 

String

localPath (common)

Local path to put files

 

String

newRemotePath (common)

New path on Atmos when moving files

 

String

query (common)

Search query on Atmos

 

String

remotePath (common)

Where to put files on Atmos

 

String

secretKey (common)

Atmos shared secret

 

String

uri (common)

Atomos server uri

 

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

10.2. Dependencies

To use Atmos in your camel routes you need to add the dependency on camel-atmos which implements this data format.

If you use maven you could just add the following to your pom.xml, substituting the version number for the latest & greatest release (see the download page for the latest versions).

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-atmos</artifactId>
  <version>x.x.x</version>
  <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

10.3. Integrations

When you look at atmos integrations, there is one type of consumer, GetConsumer, which is a type of ScheduledPollConsumer.

  • Get

Whereas there are 4 types of producers which are

  • Get
  • Del
  • Move
  • Put

10.4. Examples

These example are taken from tests:

from("atmos:foo/get?remotePath=/path").to("mock:test");
Copy to Clipboard Toggle word wrap

Here, this is a consumer example. remotePath represents the path from where the data will be read and passes the camel exchange to regarding producer Underneath, this component uses atmos client API for this and every other operations.

from("direct:start")
.to("atmos://get?remotePath=/dummy/dummy.txt")
.to("mock:result");
Copy to Clipboard Toggle word wrap

Here, this a producer sample. remotePath represents the path where the operations occur on ViPR object data service. In producers, operations(Get,Del, Move,Put) run on ViPR object data services and results are set on headers of camel exchange.

Regarding the operations, the following headers are set on camel exhange

DOWNLOADED_FILE, DOWNLOADED_FILES, UPLOADED_FILE, UPLOADED_FILES, FOUND_FILES, DELETED_PATH, MOVED_PATH;
Copy to Clipboard Toggle word wrap

10.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started

Chapter 11. Atmosphere Websocket Component

Available as of Camel version 2.14

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).
The component uses the SERVLET component and uses the Atmosphere library to support the Websocket transport in various Servlet containers (e..g., Jetty, Tomcat, …​).

Unlike the Websocket component that starts the embedded Jetty server, this component uses the servlet provider of the container.

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>
Copy to Clipboard Toggle word wrap

11.1. Atmosphere-Websocket Options

The Atmosphere Websocket component supports 8 options which are listed below.

Expand
NameDescriptionDefaultType

servletName (common)

Default name of servlet to use. The default name is CamelServlet.

 

String

httpRegistry (common)

To use a custom org.apache.camel.component.servlet.HttpRegistry.

 

HttpRegistry

attachmentMultipart Binding (common)

Whether to automatic bind multipart/form-data as attachments on the Camel Exchange. The options attachmentMultipartBinding=true and disableStreamCache=false cannot work together. Remove disableStreamCache to use AttachmentMultipartBinding. This is turn off by default as this may require servlet specific configuration to enable this when using Servlet’s.

false

boolean

httpBinding (advanced)

To use a custom HttpBinding to control the mapping between Camel message and HttpClient.

 

HttpBinding

httpConfiguration (advanced)

To use the shared HttpConfiguration as base configuration.

 

HttpConfiguration

allowJavaSerialized Object (advanced)

Whether to allow java serialization when a request uses context-type=application/x-java-serialized-object. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk.

false

boolean

headerFilterStrategy (filter)

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

 

HeaderFilterStrategy

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Atmosphere Websocket endpoint is configured using URI syntax:

atmosphere-websocket:servicePath
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

11.1.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

servicePath

Required Name of websocket endpoint

 

String

11.1.2. Query Parameters (37 parameters):

Expand
NameDescriptionDefaultType

chunked (common)

If this option is false the Servlet will disable the HTTP streaming and set the content-length header on the response

true

boolean

disableStreamCache (common)

Determines whether or not the raw input stream from Servlet is cached or not (Camel will read the stream into a in memory/overflow to file, Stream caching) cache. By default Camel will cache the Servlet input stream to support reading it multiple times to ensure it Camel can retrieve all data from the stream. However you can set this option to true when you for example need to access the raw stream, such as streaming it directly to a file or other persistent store. DefaultHttpBinding will copy the request input stream into a stream cache and put it into message body if this option is false to support reading the stream multiple times. If you use Servlet to bridge/proxy an endpoint then consider enabling this option to improve performance, in case you do not need to read the message payload multiple times. The http/http4 producer will by default cache the response body stream. If setting this option to true, then the producers will not cache the response body stream but use the response stream as-is as the message body.

false

boolean

headerFilterStrategy (common)

To use a custom HeaderFilterStrategy to filter header to and from Camel message.

 

HeaderFilterStrategy

sendToAll (common)

Whether to send to all (broadcast) or send to a single receiver.

false

boolean

transferException (common)

If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized in the response as a application/x-java-serialized-object content type. On the producer side the exception will be deserialized and thrown as is, instead of the HttpOperationFailedException. The caused exception is required to be serialized. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk.

false

boolean

useStreaming (common)

To enable streaming to send data as multiple text fragments.

false

boolean

httpBinding (common)

To use a custom HttpBinding to control the mapping between Camel message and HttpClient.

 

HttpBinding

async (consumer)

Configure the consumer to work in async mode

false

boolean

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

httpMethodRestrict (consumer)

Used to only allow consuming if the HttpMethod matches, such as GET/POST/PUT etc. Multiple methods can be specified separated by comma.

 

String

matchOnUriPrefix (consumer)

Whether or not the consumer should try to find a target consumer by matching the URI prefix if no exact match is found.

false

boolean

responseBufferSize (consumer)

To use a custom buffer size on the javax.servlet.ServletResponse.

 

Integer

servletName (consumer)

Name of the servlet to use

CamelServlet

String

attachmentMultipartBinding (consumer)

Whether to automatic bind multipart/form-data as attachments on the Camel Exchange. The options attachmentMultipartBinding=true and disableStreamCache=false cannot work together. Remove disableStreamCache to use AttachmentMultipartBinding. This is turn off by default as this may require servlet specific configuration to enable this when using Servlet’s.

false

boolean

eagerCheckContentAvailable (consumer)

Whether to eager check whether the HTTP requests has content if the content-length header is 0 or not present. This can be turned on in case HTTP clients do not send streamed data.

false

boolean

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

optionsEnabled (consumer)

Specifies whether to enable HTTP OPTIONS for this Servlet consumer. By default OPTIONS is turned off.

false

boolean

traceEnabled (consumer)

Specifies whether to enable HTTP TRACE for this Servlet consumer. By default TRACE is turned off.

false

boolean

bridgeEndpoint (producer)

If the option is true, HttpProducer will ignore the Exchange.HTTP_URI header, and use the endpoint’s URI for request. You may also set the option throwExceptionOnFailure to be false to let the HttpProducer send all the fault response back.

false

boolean

connectionClose (producer)

Specifies whether a Connection Close header must be added to HTTP Request. By default connectionClose is false.

false

boolean

copyHeaders (producer)

If this option is true then IN exchange headers will be copied to OUT exchange headers according to copy strategy. Setting this to false, allows to only include the headers from the HTTP response (not propagating IN headers).

true

boolean

httpMethod (producer)

Configure the HTTP method to use. The HttpMethod header cannot override this option if set.

 

HttpMethods

ignoreResponseBody (producer)

If this option is true, The http producer won’t read response body and cache the input stream

false

boolean

preserveHostHeader (producer)

If the option is true, HttpProducer will set the Host header to the value contained in the current exchange Host header, useful in reverse proxy applications where you want the Host header received by the downstream server to reflect the URL called by the upstream client, this allows applications which use the Host header to generate accurate URL’s for a proxied service

false

boolean

throwExceptionOnFailure (producer)

Option to disable throwing the HttpOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code.

true

boolean

cookieHandler (producer)

Configure a cookie handler to maintain a HTTP session

 

CookieHandler

okStatusCodeRange (producer)

The status codes which are considered a success response. The values are inclusive. Multiple ranges can be defined, separated by comma, e.g. 200-204,209,301-304. Each range must be a single number or from-to with the dash included.

200-299

String

urlRewrite (producer)

Deprecated Refers to a custom org.apache.camel.component.http.UrlRewrite which allows you to rewrite urls when you bridge/proxy endpoints. See more details at http://camel.apache.org/urlrewrite.html

 

UrlRewrite

mapHttpMessageBody (advanced)

If this option is true then IN exchange Body of the exchange will be mapped to HTTP body. Setting this to false will avoid the HTTP mapping.

true

boolean

mapHttpMessageFormUrl EncodedBody (advanced)

If this option is true then IN exchange Form Encoded body of the exchange will be mapped to HTTP. Setting this to false will avoid the HTTP Form Encoded body mapping.

true

boolean

mapHttpMessageHeaders (advanced)

If this option is true then IN exchange Headers of the exchange will be mapped to HTTP headers. Setting this to false will avoid the HTTP Headers mapping.

true

boolean

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

proxyAuthScheme (proxy)

Proxy authentication scheme to use

 

String

proxyHost (proxy)

Proxy hostname to use

 

String

proxyPort (proxy)

Proxy port to use

 

int

authHost (security)

Authentication host to use with NTML

 

String

11.2. URI Format

atmosphere-websocket:///relative path[?options]
Copy to Clipboard Toggle word wrap

11.3. 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.

11.4. Configuring URI to Read or Write Data

In the route below, Camel will read from the specified websocket connection.

from("atmosphere-websocket:///servicepath")
        .to("direct:next");
Copy to Clipboard Toggle word wrap

And the equivalent Spring sample:

<camelContext xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="atmosphere-websocket:///servicepath"/>
    <to uri="direct:next"/>
  </route>
</camelContext>
Copy to Clipboard Toggle word wrap

In the route below, Camel will read from the specified websocket connection.

from("direct:next")
        .to("atmosphere-websocket:///servicepath");
Copy to Clipboard Toggle word wrap

And the equivalent Spring sample:

<camelContext xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="direct:next"/>
    <to uri="atmosphere-websocket:///servicepath"/>
  </route>
</camelContext>
Copy to Clipboard Toggle word wrap

 

11.5. See Also

Chapter 12. Atom Component

Available as of Camel version 1.2

The atom: component is used for polling Atom feeds.

Camel will poll the feed every 60 seconds by default.
Note: The component currently only supports polling (consuming) feeds.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-atom</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

12.1. URI format

atom://atomUri[?options]
Copy to Clipboard Toggle word wrap

Where atomUri is the URI to the Atom feed to poll.

12.2. Options

The Atom component has no options.

The Atom endpoint is configured using URI syntax:

atom:feedUri
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

12.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

feedUri

Required The URI to the feed to poll.

 

String

12.2.2. Query Parameters (27 parameters):

Expand
NameDescriptionDefaultType

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

feedHeader (consumer)

Sets whether to add the feed object as a header

true

boolean

filter (consumer)

Sets whether to use filtering or not of the entries.

true

boolean

lastUpdate (consumer)

Sets the timestamp to be used for filtering entries from the atom feeds. This options is only in conjunction with the splitEntries.

 

Date

password (consumer)

Sets the password to be used for basic authentication when polling from a HTTP feed

 

String

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

sortEntries (consumer)

Sets whether to sort entries by published date. Only works when splitEntries = true.

false

boolean

splitEntries (consumer)

Sets whether or not entries should be sent individually or whether the entire feed should be sent as a single message

true

boolean

throttleEntries (consumer)

Sets whether all entries identified in a single feed poll should be delivered immediately. If true, only one entry is processed per consumer.delay. Only applicable when splitEntries = true.

true

boolean

username (consumer)

Sets the username to be used for basic authentication when polling from a HTTP feed

 

String

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

pollStrategy (consumer)

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

 

PollingConsumerPoll Strategy

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

 

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

 

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

 

int

delay (scheduler)

Milliseconds before the next poll. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

initialDelay (scheduler)

Milliseconds before the first poll starts. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

1000

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

 

ScheduledExecutor Service

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz2 component

none

ScheduledPollConsumer Scheduler

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz2, Spring based scheduler.

 

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

You can append query options to the URI in the following format, ?option=value&option=value&…​

12.3. Exchange data format

Camel will set the In body on the returned Exchange with the entries. Depending on the splitEntries flag Camel will either return one Entry or a List<Entry>.

Expand
OptionValueBehavior

splitEntries

true

Only a single entry from the currently being processed feed is set: exchange.in.body(Entry)

splitEntries

false

The entire list of entries from the feed is set: exchange.in.body(List<Entry>)

Camel can set the Feed object on the In header (see feedHeader option to disable this):

12.4. Message Headers

Camel atom uses these headers.

Expand
HeaderDescription

CamelAtomFeed

When consuming the org.apache.abdera.model.Feed object is set to this header.

12.5. Samples

In this sample we poll James Strachan’s blog.

from("atom://http://macstrac.blogspot.com/feeds/posts/default").to("seda:feeds");
Copy to Clipboard Toggle word wrap

In this sample we want to filter only good blogs we like to a SEDA queue. The sample also shows how to setup Camel standalone, not running in any Container or using Spring.

12.6. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • RSS

Chapter 13. Atomix Map Component

Available as of Camel version 2.20

The camel atomix-map component allows you to work with Atomix’s Distributed Map collection.

Maven users will need to add the following dependency to their pom.xml for this component:

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-atomix</artifactId>
        <version>${camel-version}</version>
    </dependency>
Copy to Clipboard Toggle word wrap

13.1. URI format

    atomix-map:mapName
Copy to Clipboard Toggle word wrap

13.2. Options

The Atomix Map component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (common)

The shared component configuration

 

AtomixMapConfiguration

atomix (common)

The shared AtomixClient instance

 

AtomixClient

nodes (common)

The nodes the AtomixClient should connect to

 

List

configurationUri (common)

The path to the AtomixClient configuration

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Atomix Map endpoint is configured using URI syntax:

atomix-map:resourceName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

13.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

resourceName

Required The distributed resource name

 

String

13.2.2. Query Parameters (18 parameters):

Expand
NameDescriptionDefaultType

atomix (common)

The Atomix instance to use

 

Atomix

configurationUri (common)

The Atomix configuration uri.

 

String

defaultAction (common)

The default action.

PUT

Action

key (common)

The key to use if none is set in the header or to listen for events for a specific key.

 

Object

nodes (common)

The address of the nodes composing the cluster.

 

String

resultHeader (common)

The header that wil carry the result.

 

String

transport (common)

Sets the Atomix transport.

io.atomix.catalyst.transport.netty.NettyTransport

Transport

ttl (common)

The resource ttl.

 

long

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

defaultResourceConfig (advanced)

The cluster wide default resource configuration.

 

Properties

defaultResourceOptions (advanced)

The local default resource options.

 

Properties

ephemeral (advanced)

Sets if the local member should join groups as PersistentMember or not. If set to ephemeral the local member will receive an auto generated ID thus the local one is ignored.

false

boolean

readConsistency (advanced)

The read consistency level.

 

ReadConsistency

resourceConfigs (advanced)

Cluster wide resources configuration.

 

Map

resourceOptions (advanced)

Local resources configurations

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

13.3. Headers

Expand
NameTypeValuesDescription

CamelAtomixResourceAction

AtomixMap.Action

  • PUT
  • PUT_IF_ABSENT
  • GET
  • CLEAR
  • SIZE
  • CONTAINS_KEY
  • CONTAINS_VALUE
  • IS_EMPTY
  • ENTRY_SET
  • REMOVE
  • REPLACE
  • VALUES

The action to perform

CamelAtomixResourceKey

Object

-

The key to operate on

CamelAtomixResourceValue

Object

-

The value, if missing In Body is used

CamelAtomixResourceOldValue

Object

-

The old value

CamelAtomixResourceTTL

String / long

-

The entry TTL

CamelAtomixResourceReadConsistency

ReadConsistency

  • ATOMIC
  • ATOMIC_LEASE
  • SEQUENTIAL
  • LOCAL

The read consistency level

The nodes of the Atomix cluster you want to join can be se at Endpoint or component level (recommended), below some examples:

  • Endpoint:

    <beans xmlns="...">
        <camelContext xmlns="http://camel.apache.org/schema/spring">
            <from uri="direct:start"/>
                <to uri="atomix-map:myMap?nodes=node-1.atomix.cluster:8700,node-2.atomix.cluster:8700"/>
            </route>
        </camelContext>
    </beans>
    Copy to Clipboard Toggle word wrap
  • Component:

    <beans xmlns="...">
        <bean id="atomix-map" class="org.apache.camel.component.atomix.client.map.AtomixMapComponent">
            <property name="nodes" value="nodes=node-1.atomix.cluster:8700,node-2.atomix.cluster:8700"/>
        </bean>
    
        <camelContext xmlns="http://camel.apache.org/schema/spring">
            <from uri="direct:start"/>
                <to uri="atomix-map:myMap"/>
            </route>
        </camelContext>
    </beans>
    Copy to Clipboard Toggle word wrap

13.5. Usage examples:

  • PUT an element with TTL of 1 second:

    FluentProducerTemplate.on(context)
        .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixMap.Action.PUT)
        .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
        .withHeader(AtomixClientConstants.RESOURCE_TTL, "1s")
        .withBody(val)
        .to("direct:start")
        .send();
    Copy to Clipboard Toggle word wrap

Chapter 14. Atomix Messaging Component

Available as of Camel version 2.20

The camel atomix-messaging component allows you to work with Atomix’s Group Messaging.

Maven users will need to add the following dependency to their pom.xml for this component:

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-atomix</artifactId>
        <version>${camel-version}</version>
    </dependency>
Copy to Clipboard Toggle word wrap

14.1. URI format

    atomix-messaging:group
Copy to Clipboard Toggle word wrap

The Atomix Messaging component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (common)

The shared component configuration

 

AtomixMessaging Configuration

atomix (common)

The shared AtomixClient instance

 

AtomixClient

nodes (common)

The nodes the AtomixClient should connect to

 

List

configurationUri (common)

The path to the AtomixClient configuration

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Atomix Messaging endpoint is configured using URI syntax:

atomix-messaging:resourceName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

14.1.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

resourceName

Required The distributed resource name

 

String

14.1.2. Query Parameters (19 parameters):

Expand
NameDescriptionDefaultType

atomix (common)

The Atomix instance to use

 

Atomix

broadcastType (common)

The broadcast type.

ALL

BroadcastType

channelName (common)

The messaging channel name

 

String

configurationUri (common)

The Atomix configuration uri.

 

String

defaultAction (common)

The default action.

DIRECT

Action

memberName (common)

The Atomix Group member name

 

String

nodes (common)

The address of the nodes composing the cluster.

 

String

resultHeader (common)

The header that wil carry the result.

 

String

transport (common)

Sets the Atomix transport.

io.atomix.catalyst.transport.netty.NettyTransport

Transport

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

defaultResourceConfig (advanced)

The cluster wide default resource configuration.

 

Properties

defaultResourceOptions (advanced)

The local default resource options.

 

Properties

ephemeral (advanced)

Sets if the local member should join groups as PersistentMember or not. If set to ephemeral the local member will receive an auto generated ID thus the local one is ignored.

false

boolean

readConsistency (advanced)

The read consistency level.

 

ReadConsistency

resourceConfigs (advanced)

Cluster wide resources configuration.

 

Map

resourceOptions (advanced)

Local resources configurations

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Chapter 15. Atomix MultiMap Component

Available as of Camel version 2.20

The camel atomix-multimap component allows you to work with Atomix’s Distributed MultiMap collection.

Maven users will need to add the following dependency to their pom.xml for this component:

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-atomix</artifactId>
        <version>${camel-version}</version>
    </dependency>
Copy to Clipboard Toggle word wrap

15.1. URI format

    atomix-multimap:multiMapName
Copy to Clipboard Toggle word wrap

The Atomix MultiMap component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (consumer)

The shared component configuration

 

AtomixMultiMap Configuration

atomix (consumer)

The shared AtomixClient instance

 

AtomixClient

nodes (consumer)

The nodes the AtomixClient should connect to

 

List

configurationUri (consumer)

The path to the AtomixClient configuration

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Atomix MultiMap endpoint is configured using URI syntax:

atomix-multimap:resourceName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

15.1.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

resourceName

Required The distributed resource name

 

String

15.1.2. Query Parameters (18 parameters):

Expand
NameDescriptionDefaultType

atomix (consumer)

The Atomix instance to use

 

Atomix

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

configurationUri (consumer)

The Atomix configuration uri.

 

String

defaultAction (consumer)

The default action.

PUT

Action

key (consumer)

The key to use if none is set in the header or to listen for events for a specific key.

 

Object

nodes (consumer)

The address of the nodes composing the cluster.

 

String

resultHeader (consumer)

The header that wil carry the result.

 

String

transport (consumer)

Sets the Atomix transport.

io.atomix.catalyst.transport.netty.NettyTransport

Transport

ttl (consumer)

The resource ttl.

 

long

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

defaultResourceConfig (advanced)

The cluster wide default resource configuration.

 

Properties

defaultResourceOptions (advanced)

The local default resource options.

 

Properties

ephemeral (advanced)

Sets if the local member should join groups as PersistentMember or not. If set to ephemeral the local member will receive an auto generated ID thus the local one is ignored.

false

boolean

readConsistency (advanced)

The read consistency level.

 

ReadConsistency

resourceConfigs (advanced)

Cluster wide resources configuration.

 

Map

resourceOptions (advanced)

Local resources configurations

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Chapter 16. Atomix Queue Component

Available as of Camel version 2.20

The camel atomix-queue component allows you to work with Atomix’s Distributed Queue collection.

Maven users will need to add the following dependency to their pom.xml for this component:

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-atomix</artifactId>
        <version>${camel-version}</version>
    </dependency>
Copy to Clipboard Toggle word wrap

16.1. URI format

    atomix-queue:queueName
Copy to Clipboard Toggle word wrap

The Atomix Queue component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (common)

The shared component configuration

 

AtomixQueue Configuration

atomix (common)

The shared AtomixClient instance

 

AtomixClient

nodes (common)

The nodes the AtomixClient should connect to

 

List

configurationUri (common)

The path to the AtomixClient configuration

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Atomix Queue endpoint is configured using URI syntax:

atomix-queue:resourceName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

16.1.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

resourceName

Required The distributed resource name

 

String

16.1.2. Query Parameters (16 parameters):

Expand
NameDescriptionDefaultType

atomix (common)

The Atomix instance to use

 

Atomix

configurationUri (common)

The Atomix configuration uri.

 

String

defaultAction (common)

The default action.

ADD

Action

nodes (common)

The address of the nodes composing the cluster.

 

String

resultHeader (common)

The header that wil carry the result.

 

String

transport (common)

Sets the Atomix transport.

io.atomix.catalyst.transport.netty.NettyTransport

Transport

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

defaultResourceConfig (advanced)

The cluster wide default resource configuration.

 

Properties

defaultResourceOptions (advanced)

The local default resource options.

 

Properties

ephemeral (advanced)

Sets if the local member should join groups as PersistentMember or not. If set to ephemeral the local member will receive an auto generated ID thus the local one is ignored.

false

boolean

readConsistency (advanced)

The read consistency level.

 

ReadConsistency

resourceConfigs (advanced)

Cluster wide resources configuration.

 

Map

resourceOptions (advanced)

Local resources configurations

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Chapter 17. Atomix Set Component

Available as of Camel version 2.20

The camel atomix-set component allows you to work with Atomix’s Distributed Set collection.

Maven users will need to add the following dependency to their pom.xml for this component:

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-atomix</artifactId>
        <version>${camel-version}</version>
    </dependency>
Copy to Clipboard Toggle word wrap

17.1. URI format

    atomix-set:setName
Copy to Clipboard Toggle word wrap

The Atomix Set component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (common)

The shared component configuration

 

AtomixSetConfiguration

atomix (common)

The shared AtomixClient instance

 

AtomixClient

nodes (common)

The nodes the AtomixClient should connect to

 

List

configurationUri (common)

The path to the AtomixClient configuration

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Atomix Set endpoint is configured using URI syntax:

atomix-set:resourceName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

17.1.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

resourceName

Required The distributed resource name

 

String

17.1.2. Query Parameters (17 parameters):

Expand
NameDescriptionDefaultType

atomix (common)

The Atomix instance to use

 

Atomix

configurationUri (common)

The Atomix configuration uri.

 

String

defaultAction (common)

The default action.

ADD

Action

nodes (common)

The address of the nodes composing the cluster.

 

String

resultHeader (common)

The header that wil carry the result.

 

String

transport (common)

Sets the Atomix transport.

io.atomix.catalyst.transport.netty.NettyTransport

Transport

ttl (common)

The resource ttl.

 

long

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

defaultResourceConfig (advanced)

The cluster wide default resource configuration.

 

Properties

defaultResourceOptions (advanced)

The local default resource options.

 

Properties

ephemeral (advanced)

Sets if the local member should join groups as PersistentMember or not. If set to ephemeral the local member will receive an auto generated ID thus the local one is ignored.

false

boolean

readConsistency (advanced)

The read consistency level.

 

ReadConsistency

resourceConfigs (advanced)

Cluster wide resources configuration.

 

Map

resourceOptions (advanced)

Local resources configurations

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Chapter 18. Atomix Value Component

Available as of Camel version 2.20

The camel atomix-value component allows you to work with Atomix’s Distributed Value.

Maven users will need to add the following dependency to their pom.xml for this component:

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-atomix</artifactId>
        <version>${camel-version}</version>
    </dependency>
Copy to Clipboard Toggle word wrap

18.1. URI format

    atomix-value:valueName
Copy to Clipboard Toggle word wrap

The Atomix Value component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (common)

The shared component configuration

 

AtomixValue Configuration

atomix (common)

The shared AtomixClient instance

 

AtomixClient

nodes (common)

The nodes the AtomixClient should connect to

 

List

configurationUri (common)

The path to the AtomixClient configuration

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Atomix Value endpoint is configured using URI syntax:

atomix-value:resourceName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

18.1.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

resourceName

Required The distributed resource name

 

String

18.1.2. Query Parameters (17 parameters):

Expand
NameDescriptionDefaultType

atomix (common)

The Atomix instance to use

 

Atomix

configurationUri (common)

The Atomix configuration uri.

 

String

defaultAction (common)

The default action.

SET

Action

nodes (common)

The address of the nodes composing the cluster.

 

String

resultHeader (common)

The header that wil carry the result.

 

String

transport (common)

Sets the Atomix transport.

io.atomix.catalyst.transport.netty.NettyTransport

Transport

ttl (common)

The resource ttl.

 

long

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

defaultResourceConfig (advanced)

The cluster wide default resource configuration.

 

Properties

defaultResourceOptions (advanced)

The local default resource options.

 

Properties

ephemeral (advanced)

Sets if the local member should join groups as PersistentMember or not. If set to ephemeral the local member will receive an auto generated ID thus the local one is ignored.

false

boolean

readConsistency (advanced)

The read consistency level.

 

ReadConsistency

resourceConfigs (advanced)

Cluster wide resources configuration.

 

Map

resourceOptions (advanced)

Local resources configurations

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Chapter 19. Avro Component

Available as of Camel version 2.10

This component provides a dataformat for avro, which allows serialization and deserialization of messages using Apache Avro’s binary dataformat. Moreover, it provides support for Apache Avro’s rpc, by providing producers and consumers endpoint for using avro over netty or http.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-avro</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

19.1. Apache Avro Overview

Avro allows you to define message types and a protocol using a json like format and then generate java code for the specified types and messages. An example of how a schema looks like is below.

{"namespace": "org.apache.camel.avro.generated",
 "protocol": "KeyValueProtocol",

 "types": [
     {"name": "Key", "type": "record",
      "fields": [
          {"name": "key",   "type": "string"}
      ]
     },
     {"name": "Value", "type": "record",
      "fields": [
          {"name": "value",   "type": "string"}
      ]
     }
 ],

 "messages": {
     "put": {
         "request": [{"name": "key", "type": "Key"}, {"name": "value", "type": "Value"} ],
         "response": "null"
     },
     "get": {
         "request": [{"name": "key", "type": "Key"}],
         "response": "Value"
     }
 }
}
Copy to Clipboard Toggle word wrap

You can easily generate classes from a schema, using maven, ant etc. More details can be found at the Apache Avro documentation.

However, it doesn’t enforce a schema first approach and you can create schema for your existing classes. Since 2.12 you can use existing protocol interfaces to make RCP calls. You should use interface for the protocol itself and POJO beans or primitive/String classes for parameter and result types. Here is an example of the class that corresponds to schema above:

package org.apache.camel.avro.reflection;

public interface KeyValueProtocol {
    void put(String key, Value value);
    Value get(String key);
}

class Value {
    private String value;
    public String getValue() { return value; }
    public void setValue(String value) { this.value = value; }
}
Copy to Clipboard Toggle word wrap

Note: Existing classes can be used only for RPC (see below), not in data format.

19.2. Using the Avro data format

Using the avro data format is as easy as specifying that the class that you want to marshal or unmarshal in your route.

    <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
        <route>
            <from uri="direct:in"/>
            <marshal>
                <avro instanceClass="org.apache.camel.dataformat.avro.Message"/>
            </marshal>
            <to uri="log:out"/>
        </route>
    </camelContext>
Copy to Clipboard Toggle word wrap

An alternative can be to specify the dataformat inside the context and reference it from your route.

    <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
         <dataFormats>
            <avro id="avro" instanceClass="org.apache.camel.dataformat.avro.Message"/>
        </dataFormats>
        <route>
            <from uri="direct:in"/>
            <marshal ref="avro"/>
            <to uri="log:out"/>
        </route>
    </camelContext>
Copy to Clipboard Toggle word wrap

In the same manner you can umarshal using the avro data format.

19.3. Using Avro RPC in Camel

As mentioned above Avro also provides RPC support over multiple transports such as http and netty. Camel provides consumers and producers for these two transports.

avro:[transport]:[host]:[port][?options]
Copy to Clipboard Toggle word wrap

The supported transport values are currently http or netty.

Since 2.12 you can specify message name right in the URI:

avro:[transport]:[host]:[port][/messageName][?options]
Copy to Clipboard Toggle word wrap

For consumers this allows you to have multiple routes attached to the same socket. Dispatching to correct route will be done by the avro component automatically. Route with no messageName specified (if any) will be used as default.

When using camel producers for avro ipc, the "in" message body needs to contain the parameters of the operation specified in the avro protocol. The response will be added in the body of the "out" message.

In a similar manner when using camel avro consumers for avro ipc, the requests parameters will be placed inside the "in" message body of the created exchange and once the exchange is processed the body of the "out" message will be send as a response.

Note: By default consumer parameters are wrapped into array. If you’ve got only one parameter, since 2.12 you can use singleParameter URI option to receive it direcly in the "in" message body without array wrapping.

19.4. Avro RPC URI Options

The Avro component supports 2 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

To use a shared AvroConfiguration to configure options once

 

AvroConfiguration

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Avro endpoint is configured using URI syntax:

avro:transport:host:port/messageName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

19.4.1. Path Parameters (4 parameters):

Expand
NameDescriptionDefaultType

transport

Required Transport to use

 

AvroTransport

port

Required Port number to use

 

int

host

Required Hostname to use

 

String

messageName

The name of the message to send.

 

String

19.4.2. Query Parameters (10 parameters):

Expand
NameDescriptionDefaultType

protocol (common)

Avro protocol to use

 

Protocol

protocolClassName (common)

Avro protocol to use defined by the FQN class name

 

String

protocolLocation (common)

Avro protocol location

 

String

reflectionProtocol (common)

If protocol object provided is reflection protocol. Should be used only with protocol parameter because for protocolClassName protocol type will be auto detected

false

boolean

singleParameter (common)

If true, consumer parameter won’t be wrapped into array. Will fail if protocol specifies more then 1 parameter for the message

false

boolean

uriAuthority (common)

Authority to use (username and password)

 

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

19.5. Avro RPC Headers

Expand
NameDescription

CamelAvroMessageName

The name of the message to send. In consumer overrides message name from URI (if any)

19.6. Examples

An example of using camel avro producers via http:

        <route>
            <from uri="direct:start"/>
            <to uri="avro:http:localhost:{{avroport}}?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol"/>
            <to uri="log:avro"/>
        </route>
Copy to Clipboard Toggle word wrap

In the example above you need to fill CamelAvroMessageName header. Since 2.12 you can use following syntax to call constant messages:

        <route>
            <from uri="direct:start"/>
            <to uri="avro:http:localhost:{{avroport}}/put?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol"/>
            <to uri="log:avro"/>
        </route>
Copy to Clipboard Toggle word wrap

An example of consuming messages using camel avro consumers via netty:

        <route>
            <from uri="avro:netty:localhost:{{avroport}}?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol"/>
            <choice>
                <when>
                    <el>${in.headers.CamelAvroMessageName == 'put'}</el>
                    <process ref="putProcessor"/>
                </when>
                <when>
                    <el>${in.headers.CamelAvroMessageName == 'get'}</el>
                    <process ref="getProcessor"/>
                </when>
            </choice>
        </route>
Copy to Clipboard Toggle word wrap

Since 2.12 you can set up two distinct routes to perform the same task:

        <route>
            <from uri="avro:netty:localhost:{{avroport}}/put?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol">
            <process ref="putProcessor"/>
        </route>
        <route>
            <from uri="avro:netty:localhost:{{avroport}}/get?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol&singleParameter=true"/>
            <process ref="getProcessor"/>
        </route>
Copy to Clipboard Toggle word wrap

In the example above, get takes only one parameter, so singleParameter is used and getProcessor will receive Value class directly in body, while putProcessor will receive an array of size 2 with String key and Value value filled as array contents.

Chapter 20. Avro DataFormat

Available as of Camel version 2.14

This component provides a dataformat for avro, which allows serialization and deserialization of messages using Apache Avro’s binary dataformat. Moreover, it provides support for Apache Avro’s rpc, by providing producers and consumers endpoint for using avro over netty or http.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-avro</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

20.1. Apache Avro Overview

Avro allows you to define message types and a protocol using a json like format and then generate java code for the specified types and messages. An example of how a schema looks like is below.

{"namespace": "org.apache.camel.avro.generated",
 "protocol": "KeyValueProtocol",

 "types": [
     {"name": "Key", "type": "record",
      "fields": [
          {"name": "key",   "type": "string"}
      ]
     },
     {"name": "Value", "type": "record",
      "fields": [
          {"name": "value",   "type": "string"}
      ]
     }
 ],

 "messages": {
     "put": {
         "request": [{"name": "key", "type": "Key"}, {"name": "value", "type": "Value"} ],
         "response": "null"
     },
     "get": {
         "request": [{"name": "key", "type": "Key"}],
         "response": "Value"
     }
 }
}
Copy to Clipboard Toggle word wrap

You can easily generate classes from a schema, using maven, ant etc. More details can be found at the Apache Avro documentation.

However, it doesn’t enforce a schema first approach and you can create schema for your existing classes. Since 2.12 you can use existing protocol interfaces to make RCP calls. You should use interface for the protocol itself and POJO beans or primitive/String classes for parameter and result types. Here is an example of the class that corresponds to schema above:

package org.apache.camel.avro.reflection;

public interface KeyValueProtocol {
    void put(String key, Value value);
    Value get(String key);
}

class Value {
    private String value;
    public String getValue() { return value; }
    public void setValue(String value) { this.value = value; }
}
Copy to Clipboard Toggle word wrap

Note: Existing classes can be used only for RPC (see below), not in data format.

20.2. Using the Avro data format

Using the avro data format is as easy as specifying that the class that you want to marshal or unmarshal in your route.

    <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
        <route>
            <from uri="direct:in"/>
            <marshal>
                <avro instanceClass="org.apache.camel.dataformat.avro.Message"/>
            </marshal>
            <to uri="log:out"/>
        </route>
    </camelContext>
Copy to Clipboard Toggle word wrap

An alternative can be to specify the dataformat inside the context and reference it from your route.

    <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
         <dataFormats>
            <avro id="avro" instanceClass="org.apache.camel.dataformat.avro.Message"/>
        </dataFormats>
        <route>
            <from uri="direct:in"/>
            <marshal ref="avro"/>
            <to uri="log:out"/>
        </route>
    </camelContext>
Copy to Clipboard Toggle word wrap

In the same manner you can umarshal using the avro data format.

20.3. Avro Dataformat Options

The Avro dataformat supports 2 options which are listed below.

Expand
NameDefaultJava TypeDescription

instanceClassName

 

String

Class name to use for marshal and unmarshalling

contentTypeHeader

false

Boolean

Whether the data format should set the Content-Type header with the type from the data format if the data format is capable of doing so. For example application/xml for data formats marshalling to XML, or application/json for data formats marshalling to JSon etc.

Chapter 21. AWS CloudWatch Component

Available as of Camel version 2.11

The CW component allows messages to be sent to an Amazon CloudWatch metrics. The implementation of the Amazon API is provided by the AWS SDK.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon CloudWatch. More information are available at Amazon CloudWatch.

21.1. URI Format

aws-cw://namespace[?options]
Copy to Clipboard Toggle word wrap

The metrics will be created if they don’t already exists.
You can append query options to the URI in the following format, ?options=value&option2=value&…​

21.2. URI Options

The AWS CloudWatch component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS CW default configuration

 

CwConfiguration

accessKey (producer)

Amazon AWS Access Key

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

region (producer)

The region in which CW client needs to work

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS CloudWatch endpoint is configured using URI syntax:

aws-cw:namespace
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

21.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

namespace

Required The metric namespace

 

String

21.2.2. Query Parameters (11 parameters):

Expand
NameDescriptionDefaultType

amazonCwClient (producer)

To use the AmazonCloudWatch as the client

 

AmazonCloudWatch

name (producer)

The metric name

 

String

proxyHost (producer)

To define a proxy host when instantiating the CW client

 

String

proxyPort (producer)

To define a proxy port when instantiating the CW client

 

Integer

region (producer)

The region in which CW client needs to work

 

String

timestamp (producer)

The metric timestamp

 

Date

unit (producer)

The metric unit

 

String

value (producer)

The metric value

 

Double

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

accessKey (security)

Amazon AWS Access Key

 

String

secretKey (security)

Amazon AWS Secret Key

 

String

Required CW component options

You have to provide the amazonCwClient in the Registry or your accessKey and secretKey to access the Amazon’s CloudWatch.

21.3. Usage

21.3.1. Message headers evaluated by the CW producer

Expand
HeaderTypeDescription

CamelAwsCwMetricName

String

The Amazon CW metric name.

CamelAwsCwMetricValue

Double

The Amazon CW metric value.

CamelAwsCwMetricUnit

String

The Amazon CW metric unit.

CamelAwsCwMetricNamespace

String

The Amazon CW metric namespace.

CamelAwsCwMetricTimestamp

Date

The Amazon CW metric timestamp.

CamelAwsCwMetricDimensionName

String

Camel 2.12: The Amazon CW metric dimension name.

CamelAwsCwMetricDimensionValue

String

Camel 2.12: The Amazon CW metric dimension value.

CamelAwsCwMetricDimensions

Map<String, String>

Camel 2.12: A map of dimension names and dimension values.

21.3.2. Advanced AmazonCloudWatch configuration

If you need more control over the AmazonCloudWatch instance configuration you can create your own instance and refer to it from the URI:

from("direct:start")
.to("aws-cw://namepsace?amazonCwClient=#client");
Copy to Clipboard Toggle word wrap

The #client refers to a AmazonCloudWatch in the Registry.

For example if your Camel Application is running behind a firewall:

AWSCredentials awsCredentials = new BasicAWSCredentials("myAccessKey", "mySecretKey");
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);

AmazonCloudWatch client = new AmazonCloudWatchClient(awsCredentials, clientConfiguration);

registry.bind("client", client);
Copy to Clipboard Toggle word wrap

21.4. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.10 or higher).

21.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 22. AWS DynamoDB Component

Available as of Camel version 2.10

The DynamoDB component supports storing and retrieving data from/to Amazon’s DynamoDB service.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon DynamoDB. More information are available at Amazon DynamoDB.

22.1. URI Format

aws-ddb://domainName[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?options=value&option2=value&…​

22.2. URI Options

The AWS DynamoDB component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS DDB default configuration

 

DdbConfiguration

accessKey (producer)

Amazon AWS Access Key

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

region (producer)

The region in which DDB client needs to work

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS DynamoDB endpoint is configured using URI syntax:

aws-ddb:tableName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

22.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

tableName

Required The name of the table currently worked with.

 

String

22.2.2. Query Parameters (13 parameters):

Expand
NameDescriptionDefaultType

amazonDDBClient (producer)

To use the AmazonDynamoDB as the client

 

AmazonDynamoDB

consistentRead (producer)

Determines whether or not strong consistency should be enforced when data is read.

false

boolean

keyAttributeName (producer)

Attribute name when creating table

 

String

keyAttributeType (producer)

Attribute type when creating table

 

String

operation (producer)

What operation to perform

PutItem

DdbOperations

proxyHost (producer)

To define a proxy host when instantiating the DDB client

 

String

proxyPort (producer)

To define a proxy port when instantiating the DDB client

 

Integer

readCapacity (producer)

The provisioned throughput to reserve for reading resources from your table

 

Long

region (producer)

The region in which DDB client needs to work

 

String

writeCapacity (producer)

The provisioned throughput to reserved for writing resources to your table

 

Long

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

accessKey (security)

Amazon AWS Access Key

 

String

secretKey (security)

Amazon AWS Secret Key

 

String

Required DDB component options

You have to provide the amazonDDBClient in the Registry or your accessKey and secretKey to access the Amazon’s DynamoDB.

22.3. Usage

22.3.1. Message headers evaluated by the DDB producer

Expand
HeaderTypeDescription

CamelAwsDdbBatchItems

Map<String, KeysAndAttributes>

A map of the table name and corresponding items to get by primary key.

CamelAwsDdbTableName

String

Table Name for this operation.

CamelAwsDdbKey

Key

The primary key that uniquely identifies each item in a table. From Camel 2.16.0 the type of this header is Map<String, AttributeValue> and not Key

CamelAwsDdbReturnValues

String

Use this parameter if you want to get the attribute name-value pairs before or after they are modified(NONE, ALL_OLD, UPDATED_OLD, ALL_NEW, UPDATED_NEW).

CamelAwsDdbUpdateCondition

Map<String, ExpectedAttributeValue>

Designates an attribute for a conditional modification.

CamelAwsDdbAttributeNames

Collection<String>

If attribute names are not specified then all attributes will be returned.

CamelAwsDdbConsistentRead

Boolean

If set to true, then a consistent read is issued, otherwise eventually consistent is used.

CamelAwsDdbIndexName

String

If set will be used as Secondary Index for Query operation.

CamelAwsDdbItem

Map<String, AttributeValue>

A map of the attributes for the item, and must include the primary key values that define the item.

CamelAwsDdbExactCount

Boolean

If set to true, Amazon DynamoDB returns a total number of items that match the query parameters, instead of a list of the matching items and their attributes. From Camel 2.16.0 this header doesn’t exist anymore.

CamelAwsDdbKeyConditions

Map<String, Condition>

From Camel 2.16.0. This header specify the selection criteria for the query, and merge together the two old headers CamelAwsDdbHashKeyValue and CamelAwsDdbScanRangeKeyCondition

CamelAwsDdbStartKey

Key

Primary key of the item from which to continue an earlier query.

CamelAwsDdbHashKeyValue

AttributeValue

Value of the hash component of the composite primary key. From Camel 2.16.0 this header doesn’t exist anymore.

CamelAwsDdbLimit

Integer

The maximum number of items to return.

CamelAwsDdbScanRangeKeyCondition

Condition

A container for the attribute values and comparison operators to use for the query.From Camel 2.16.0 this header doesn’t exist anymore.

CamelAwsDdbScanIndexForward

Boolean

Specifies forward or backward traversal of the index.

CamelAwsDdbScanFilter

Map<String, Condition>

Evaluates the scan results and returns only the desired values.

CamelAwsDdbUpdateValues

Map<String, AttributeValueUpdate>

Map of attribute name to the new value and action for the update.

22.3.2. Message headers set during BatchGetItems operation

Expand
HeaderTypeDescription

CamelAwsDdbBatchResponse

Map<String,BatchResponse>

Table names and the respective item attributes from the tables.

CamelAwsDdbUnprocessedKeys

Map<String,KeysAndAttributes>

Contains a map of tables and their respective keys that were not processed with the current response.

22.3.3. Message headers set during DeleteItem operation

Expand
HeaderTypeDescription

CamelAwsDdbAttributes

Map<String, AttributeValue>

The list of attributes returned by the operation.

22.3.4. Message headers set during DeleteTable operation

Expand
HeaderTypeDescription

CamelAwsDdbProvisionedThroughput

  

ProvisionedThroughputDescription

 

The value of the ProvisionedThroughput property for this table

CamelAwsDdbCreationDate

Date

Creation DateTime of this table.

CamelAwsDdbTableItemCount

Long

Item count for this table.

CamelAwsDdbKeySchema

KeySchema

The KeySchema that identifies the primary key for this table. From Camel 2.16.0 the type of this header is List<KeySchemaElement> and not KeySchema

CamelAwsDdbTableName

String

The table name.

CamelAwsDdbTableSize

Long

The table size in bytes.

CamelAwsDdbTableStatus

String

The status of the table: CREATING, UPDATING, DELETING, ACTIVE

22.3.5. Message headers set during DescribeTable operation

Expand
HeaderTypeDescription

CamelAwsDdbProvisionedThroughput

{{ProvisionedThroughputDescription}}

The value of the ProvisionedThroughput property for this table

CamelAwsDdbCreationDate

Date

Creation DateTime of this table.

CamelAwsDdbTableItemCount

Long

Item count for this table.

CamelAwsDdbKeySchema

{{KeySchema}}

The KeySchema that identifies the primary key for this table. From Camel 2.16.0 the type of this header is List<KeySchemaElement> and not KeySchema

CamelAwsDdbTableName

String

The table name.

CamelAwsDdbTableSize

Long

The table size in bytes.

CamelAwsDdbTableStatus

String

The status of the table: CREATING, UPDATING, DELETING, ACTIVE

CamelAwsDdbReadCapacity

Long

ReadCapacityUnits property of this table.

CamelAwsDdbWriteCapacity

Long

WriteCapacityUnits property of this table.

22.3.6. Message headers set during GetItem operation

Expand
HeaderTypeDescription

CamelAwsDdbAttributes

Map<String, AttributeValue>

The list of attributes returned by the operation.

22.3.7. Message headers set during PutItem operation

Expand
HeaderTypeDescription

CamelAwsDdbAttributes

Map<String, AttributeValue>

The list of attributes returned by the operation.

22.3.8. Message headers set during Query operation

Expand
HeaderTypeDescription

CamelAwsDdbItems

List<java.util.Map<String,AttributeValue>>

The list of attributes returned by the operation.

CamelAwsDdbLastEvaluatedKey

Key

Primary key of the item where the query operation stopped, inclusive of the previous result set.

CamelAwsDdbConsumedCapacity

Double

The number of Capacity Units of the provisioned throughput of the table consumed during the operation.

CamelAwsDdbCount

Integer

Number of items in the response.

22.3.9. Message headers set during Scan operation

Expand
HeaderTypeDescription

CamelAwsDdbItems

List<java.util.Map<String,AttributeValue>>

The list of attributes returned by the operation.

CamelAwsDdbLastEvaluatedKey

Key

Primary key of the item where the query operation stopped, inclusive of the previous result set.

CamelAwsDdbConsumedCapacity

Double

The number of Capacity Units of the provisioned throughput of the table consumed during the operation.

CamelAwsDdbCount

Integer

Number of items in the response.

CamelAwsDdbScannedCount

Integer

Number of items in the complete scan before any filters are applied.

22.3.10. Message headers set during UpdateItem operation

Expand
HeaderTypeDescription

CamelAwsDdbAttributes

Map<String, AttributeValue>

The list of attributes returned by the operation.

22.3.11. Advanced AmazonDynamoDB configuration

If you need more control over the AmazonDynamoDB instance configuration you can create your own instance and refer to it from the URI:

from("direct:start")
.to("aws-ddb://domainName?amazonDDBClient=#client");
Copy to Clipboard Toggle word wrap

The #client refers to a AmazonDynamoDB in the Registry.

For example if your Camel Application is running behind a firewall:

AWSCredentials awsCredentials = new BasicAWSCredentials("myAccessKey", "mySecretKey");
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);

AmazonDynamoDB client = new AmazonDynamoDBClient(awsCredentials, clientConfiguration);

registry.bind("client", client);
Copy to Clipboard Toggle word wrap

22.4. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.10 or higher).

22.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 23. AWS DynamoDB Streams Component

Available as of Camel version 2.17

The DynamoDB Stream component supports receiving messages from Amazon DynamoDB Stream service.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon DynamoDB Streams. More information are available at AWS DynamoDB

23.1. URI Format

aws-ddbstream://table-name[?options]
Copy to Clipboard Toggle word wrap

The stream needs to be created prior to it being used.
You can append query options to the URI in the following format, ?options=value&option2=value&…​

23.2. URI Options

The AWS DynamoDB Streams component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS DDB stream default configuration

 

DdbStreamConfiguration

accessKey (consumer)

Amazon AWS Access Key

 

String

secretKey (consumer)

Amazon AWS Secret Key

 

String

region (consumer)

Amazon AWS Region

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS DynamoDB Streams endpoint is configured using URI syntax:

aws-ddbstream:tableName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

23.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

tableName

Required Name of the dynamodb table

 

String

23.2.2. Query Parameters (28 parameters):

Expand
NameDescriptionDefaultType

amazonDynamoDbStreams Client (consumer)

Amazon DynamoDB client to use for all requests for this endpoint

 

AmazonDynamoDBStreams

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

iteratorType (consumer)

Defines where in the DynaboDB stream to start getting records. Note that using TRIM_HORIZON can cause a significant delay before the stream has caught up to real-time. if AT,AFTER_SEQUENCE_NUMBER are used, then a sequenceNumberProvider MUST be supplied.

LATEST

ShardIteratorType

maxResultsPerRequest (consumer)

Maximum number of records that will be fetched in each poll

 

int

proxyHost (consumer)

To define a proxy host when instantiating the DDBStreams client

 

String

proxyPort (consumer)

To define a proxy port when instantiating the DDBStreams client

 

Integer

region (consumer)

The region in which DDBStreams client needs to work

 

String

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

sequenceNumberProvider (consumer)

Provider for the sequence number when using one of the two ShardIteratorType.AT,AFTER_SEQUENCE_NUMBER iterator types. Can be a registry reference or a literal sequence number.

 

SequenceNumberProvider

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

pollStrategy (consumer)

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

 

PollingConsumerPoll Strategy

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

 

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

 

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

 

int

delay (scheduler)

Milliseconds before the next poll. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

initialDelay (scheduler)

Milliseconds before the first poll starts. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

1000

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

 

ScheduledExecutor Service

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz2 component

none

ScheduledPollConsumer Scheduler

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz2, Spring based scheduler.

 

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

accessKey (security)

Amazon AWS Access Key

 

String

secretKey (security)

Amazon AWS Secret Key

 

String

Required DynampDBStream component options

You have to provide the amazonDynamoDbStreamsClient in the Registry with proxies and relevant credentials configured.

23.3. Sequence Numbers

You can provide a literal string as the sequence number or provide a bean in the registry. An example of using the bean would be to save your current position in the change feed and restore it on Camel startup.

It is an error to provide a sequence number that is greater than the largest sequence number in the describe-streams result, as this will lead to the AWS call returning an HTTP 400.

23.4. Batch Consumer

This component implements the Batch Consumer.

This allows you for instance to know how many messages exists in this batch and for instance let the Aggregator aggregate this number of messages.

23.5. Usage

23.5.1. AmazonDynamoDBStreamsClient configuration

You will need to create an instance of AmazonDynamoDBStreamsClient and bind it to the registry

ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);

Region region = Region.getRegion(Regions.fromName(region));
region.createClient(AmazonDynamoDBStreamsClient.class, null, clientConfiguration);
// the 'null' here is the AWSCredentialsProvider which defaults to an instance of DefaultAWSCredentialsProviderChain

registry.bind("kinesisClient", client);
Copy to Clipboard Toggle word wrap

23.5.2. Providing AWS Credentials

It is recommended that the credentials are obtained by using the DefaultAWSCredentialsProviderChain that is the default when creating a new ClientConfiguration instance, however, a different AWSCredentialsProvider can be specified when calling createClient(…​).

23.6. Coping with Downtime

23.6.1. AWS DynamoDB Streams outage of less than 24 hours

The consumer will resume from the last seen sequence number (as implemented for CAMEL-9515), so you should receive a flood of events in quick succession, as long as the outage did not also include DynamoDB itself.

23.6.2. AWS DynamoDB Streams outage of more than 24 hours

Given that AWS only retain 24 hours worth of changes, you will have missed change events no matter what mitigations are in place.

23.7. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.7 or higher).

23.8. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component
    +

Chapter 24. AWS EC2 Component

Available as of Camel version 2.16

The EC2 component supports create, run, start, stop and terminate AWS EC2 instances.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon EC2. More information are available at Amazon EC2.

24.1. URI Format

aws-ec2://label[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?options=value&option2=value&…​

24.2. URI Options

The AWS EC2 component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS EC2 default configuration

 

EC2Configuration

region (producer)

The region in which EC2 client needs to work

 

String

accessKey (producer)

Amazon AWS Access Key

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS EC2 endpoint is configured using URI syntax:

aws-ec2:label
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

24.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

label

Required Logical name

 

String

24.2.2. Query Parameters (8 parameters):

Expand
NameDescriptionDefaultType

accessKey (producer)

Amazon AWS Access Key

 

String

amazonEc2Client (producer)

To use a existing configured AmazonEC2Client as client

 

AmazonEC2Client

operation (producer)

Required The operation to perform. It can be createAndRunInstances, startInstances, stopInstances, terminateInstances, describeInstances, describeInstancesStatus, rebootInstances, monitorInstances, unmonitorInstances, createTags or deleteTags

 

EC2Operations

proxyHost (producer)

To define a proxy host when instantiating the EC2 client

 

String

proxyPort (producer)

To define a proxy port when instantiating the EC2 client

 

Integer

region (producer)

The region in which EC2 client needs to work

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Required EC2 component options

You have to provide the amazonEc2Client in the Registry or your accessKey and secretKey to access the Amazon EC2 service.

24.3. Usage

24.3.1. Message headers evaluated by the EC2 producer

Expand
HeaderTypeDescription

CamelAwsEC2ImageId

String

An image ID of the AWS marketplace

CamelAwsEC2InstanceType

com.amazonaws.services.ec2.model.InstanceType

The instance type we want to create and run

CamelAwsEC2Operation

String

The operation we want to perform

CamelAwsEC2InstanceMinCount

Int

The mininum number of instances we want to run.

CamelAwsEC2InstanceMaxCount

Int

The maximum number of instances we want to run.

CamelAwsEC2InstanceMonitoring

Boolean

Define if we want the running instances to be monitored

CamelAwsEC2InstanceEbsOptimized

Boolean

Define if the creating instance is optimized for EBS I/O.

CamelAwsEC2InstanceSecurityGroups

Collection

The security groups to associate to the instances

CamelAwsEC2InstancesIds

Collection

A collection of instances IDS to execute start, stop, describe and terminate operations on.

CamelAwsEC2InstancesTags

Collection

A collection of tags to add or remove from EC2 resources

Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.16 or higher).

24.4. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 25. AWS IAM Component

Available as of Camel version 2.23

The KMS component supports create, run, start, stop and terminate AWS IAM instances.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon IAM. More information are available at Amazon IAM.

25.1. URI Format

aws-kms://label[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?options=value&option2=value&…​

25.2. URI Options

The AWS IAM component supports 5 options, which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS IAM default configuration

 

IAMConfiguration

accessKey (producer)

Amazon AWS Access Key

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

region (producer)

The region in which IAM client needs to work

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS IAM endpoint is configured using URI syntax:

aws-iam:label
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

25.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

label

Required Logical name

 

String

25.2.2. Query Parameters (8 parameters):

Expand
NameDescriptionDefaultType

accessKey (producer)

Amazon AWS Access Key

 

String

iamClient (producer)

To use a existing configured AWS IAM as client

 

AmazonIdentity ManagementClient

operation (producer)

Required The operation to perform

 

IAMOperations

proxyHost (producer)

To define a proxy host when instantiating the KMS client

 

String

proxyPort (producer)

To define a proxy port when instantiating the KMS client

 

Integer

region (producer)

The region in which KMS client needs to work

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

25.3. Spring Boot Auto-Configuration

The component supports 12 options, which are listed below.

Expand
NameDescriptionDefaultType

camel.component.aws-iam.access-key

Amazon AWS Access Key

 

String

camel.component.aws-iam.configuration.access-key

Amazon AWS Access Key

 

String

camel.component.aws-iam.configuration.iam-client

To use a existing configured AWS IAM as client

 

AmazonIdentity ManagementClient

camel.component.aws-iam.configuration.operation

The operation to perform

 

IAMOperations

camel.component.aws-iam.configuration.proxy-host

To define a proxy host when instantiating the KMS client

 

String

camel.component.aws-iam.configuration.proxy-port

To define a proxy port when instantiating the KMS client

 

Integer

camel.component.aws-iam.configuration.region

The region in which KMS client needs to work

 

String

camel.component.aws-iam.configuration.secret-key

Amazon AWS Secret Key

 

String

camel.component.aws-iam.enabled

Whether to enable auto configuration of the aws-iam component. This is enabled by default.

 

Boolean

camel.component.aws-iam.region

The region in which IAM client needs to work

 

String

camel.component.aws-iam.resolve-property-placeholders

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

Boolean

camel.component.aws-iam.secret-key

Amazon AWS Secret Key

 

String

Required IAM component options

You have to provide the amazonKmsClient in the Registry or your accessKey and secretKey to access the Amazon IAM service.

25.4. Usage

25.4.1. Message headers evaluated by the IAM producer

Expand
HeaderTypeDescription

CamelAwsIAMOperation

String

The operation we want to perform

CamelAwsIAMUsername

String

The username for the user you want to manage

CamelAwsIAMAccessKeyID

String

The accessKey you want to manage

CamelAwsIAMAccessKeyStatus

String

The Status of the AccessKey you want to set, possible value are active and inactive

25.4.2. IAM Producer operations

Camel-AWS IAM component provides the following operation on the producer side:

  • listAccessKeys
  • createUser
  • deleteUser
  • listUsers
  • getUser
  • createAccessKey
  • deleteAccessKey
  • updateAccessKey

Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.16 or higher).

25.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 26. AWS Kinesis Component

Available as of Camel version 2.17

The Kinesis component supports receiving messages from and sending messages to Amazon Kinesis service.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon Kinesis. More information are available at AWS Kinesis

26.1. URI Format

aws-kinesis://stream-name[?options]
Copy to Clipboard Toggle word wrap

The stream needs to be created prior to it being used.
You can append query options to the URI in the following format, ?options=value&option2=value&…​

26.2. URI Options

The AWS Kinesis component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS S3 default configuration

 

KinesisConfiguration

accessKey (common)

Amazon AWS Access Key

 

String

secretKey (common)

Amazon AWS Secret Key

 

String

region (common)

Amazon AWS Region

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS Kinesis endpoint is configured using URI syntax:

aws-kinesis:streamName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

26.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

streamName

Required Name of the stream

 

String

26.2.2. Query Parameters (30 parameters):

Expand
NameDescriptionDefaultType

amazonKinesisClient (common)

Amazon Kinesis client to use for all requests for this endpoint

 

AmazonKinesis

proxyHost (common)

To define a proxy host when instantiating the DDBStreams client

 

String

proxyPort (common)

To define a proxy port when instantiating the DDBStreams client

 

Integer

region (common)

The region in which Kinesis client needs to work

 

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

iteratorType (consumer)

Defines where in the Kinesis stream to start getting records

TRIM_HORIZON

ShardIteratorType

maxResultsPerRequest (consumer)

Maximum number of records that will be fetched in each poll

1

int

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

sequenceNumber (consumer)

The sequence number to start polling from. Required if iteratorType is set to AFTER_SEQUENCE_NUMBER or AT_SEQUENCE_NUMBER

 

String

shardClosed (consumer)

Define what will be the behavior in case of shard closed. Possible value are ignore, silent and fail.In case of ignore a message will be logged and the consumer will restart from the beginning,in case of silent there will be no logging and the consumer will start from the beginning,in case of fail a ReachedClosedStateException will be raised

ignore

KinesisShardClosed StrategyEnum

shardId (consumer)

Defines which shardId in the Kinesis stream to get records from

 

String

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

pollStrategy (consumer)

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

 

PollingConsumerPoll Strategy

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

 

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

 

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

 

int

delay (scheduler)

Milliseconds before the next poll. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

initialDelay (scheduler)

Milliseconds before the first poll starts. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

1000

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

 

ScheduledExecutor Service

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz2 component

none

ScheduledPollConsumer Scheduler

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz2, Spring based scheduler.

 

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

accessKey (security)

Amazon AWS Access Key

 

String

secretKey (security)

Amazon AWS Secret Key

 

String

Required Kinesis component options

You have to provide the amazonKinesisClient in the Registry with proxies and relevant credentials configured.

26.3. Batch Consumer

This component implements the Batch Consumer.

This allows you for instance to know how many messages exists in this batch and for instance let the Aggregator aggregate this number of messages.

26.4. Usage

26.4.1. Message headers set by the Kinesis consumer

Expand
HeaderTypeDescription

CamelAwsKinesisSequenceNumber

String

The sequence number of the record. This is represented as a String as it size is not defined by the API. If it is to be used as a numerical type then use

CamelAwsKinesisApproximateArrivalTimestamp

String

The time AWS assigned as the arrival time of the record.

CamelAwsKinesisPartitionKey

String

Identifies which shard in the stream the data record is assigned to.

26.4.2. AmazonKinesis configuration

You will need to create an instance of AmazonKinesisClient and bind it to the registry

ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);

Region region = Region.getRegion(Regions.fromName(region));
region.createClient(AmazonKinesisClient.class, null, clientConfiguration);
// the 'null' here is the AWSCredentialsProvider which defaults to an instance of DefaultAWSCredentialsProviderChain

registry.bind("kinesisClient", client);
Copy to Clipboard Toggle word wrap

You then have to reference the AmazonKinesisClient in the amazonKinesisClient URI option.

from("aws-kinesis://mykinesisstream?amazonKinesisClient=#kinesisClient")
  .to("log:out?showAll=true");
Copy to Clipboard Toggle word wrap

26.4.3. Providing AWS Credentials

It is recommended that the credentials are obtained by using the DefaultAWSCredentialsProviderChain that is the default when creating a new ClientConfiguration instance, however, a different AWSCredentialsProvider can be specified when calling createClient(…​).

Expand
HeaderTypeDescription

CamelAwsKinesisPartitionKey

String

The PartitionKey to pass to Kinesis to store this record.

CamelAwsKinesisSequenceNumber

String

Optional paramter to indicate the sequence number of this record.

Expand
HeaderTypeDescription

CamelAwsKinesisSequenceNumber

String

The sequence number of the record, as defined in Response Syntax

CamelAwsKinesisShardId

String

The shard ID of where the Record was stored

26.5. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.17 or higher).

26.6. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 27. AWS Kinesis Firehose Component

Available as of Camel version 2.19

The Kinesis Firehose component supports sending messages to Amazon Kinesis Firehose service.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon Kinesis Firehose. More information are available at AWS Kinesis Firehose

27.1. URI Format

aws-kinesis-firehose://delivery-stream-name[?options]
Copy to Clipboard Toggle word wrap

The stream needs to be created prior to it being used.
You can append query options to the URI in the following format, ?options=value&option2=value&…​

27.2. URI Options

The AWS Kinesis Firehose component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS Kinesis Firehose default configuration

 

KinesisFirehose Configuration

accessKey (producer)

Amazon AWS Access Key

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

region (producer)

Amazon AWS Region

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS Kinesis Firehose endpoint is configured using URI syntax:

aws-kinesis-firehose:streamName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

27.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

streamName

Required Name of the stream

 

String

27.2.2. Query Parameters (7 parameters):

Expand
NameDescriptionDefaultType

amazonKinesisFirehoseClient (producer)

Amazon Kinesis Firehose client to use for all requests for this endpoint

 

AmazonKinesisFirehose

proxyHost (producer)

To define a proxy host when instantiating the DDBStreams client

 

String

proxyPort (producer)

To define a proxy port when instantiating the DDBStreams client

 

Integer

region (producer)

The region in which Kinesis client needs to work

 

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

accessKey (security)

Amazon AWS Access Key

 

String

secretKey (security)

Amazon AWS Secret Key

 

String

Required Kinesis Firehose component options

You have to provide the amazonKinesisClient in the Registry with proxies and relevant credentials configured.

27.3. Usage

27.3.1. Amazon Kinesis Firehose configuration

You will need to create an instance of AmazonKinesisClient and bind it to the registry

ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);

Region region = Region.getRegion(Regions.fromName(region));
region.createClient(AmazonKinesisClient.class, null, clientConfiguration);
// the 'null' here is the AWSCredentialsProvider which defaults to an instance of DefaultAWSCredentialsProviderChain

registry.bind("kinesisFirehoseClient", client);
Copy to Clipboard Toggle word wrap

You then have to reference the AmazonKinesisFirehoseClient in the amazonKinesisFirehoseClient URI option.

from("aws-kinesis-firehose://mykinesisdeliverystream?amazonKinesisFirehoseClient=#kinesisClient")
  .to("log:out?showAll=true");
Copy to Clipboard Toggle word wrap

27.3.2. Providing AWS Credentials

It is recommended that the credentials are obtained by using the DefaultAWSCredentialsProviderChain that is the default when creating a new ClientConfiguration instance, however, a different AWSCredentialsProvider can be specified when calling createClient(…​).

Expand
HeaderTypeDescription

CamelAwsKinesisFirehoseRecordId

String

The record ID, as defined in Response Syntax

27.4. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.19 or higher).

27.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 28. AWS KMS Component

Available as of Camel version 2.21

The KMS component supports create, run, start, stop and terminate AWS KMS instances.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon KMS. More information are available at Amazon KMS.

28.1. URI Format

aws-kms://label[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?options=value&option2=value&…​

28.2. URI Options

The AWS KMS component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS MQ default configuration

 

KMSConfiguration

accessKey (producer)

Amazon AWS Access Key

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

region (producer)

The region in which MQ client needs to work

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS KMS endpoint is configured using URI syntax:

aws-kms:label
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

28.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

label

Required Logical name

 

String

28.2.2. Query Parameters (8 parameters):

Expand
NameDescriptionDefaultType

accessKey (producer)

Amazon AWS Access Key

 

String

kmsClient (producer)

To use a existing configured AWS KMS as client

 

AWSKMS

operation (producer)

Required The operation to perform

 

KMSOperations

proxyHost (producer)

To define a proxy host when instantiating the KMS client

 

String

proxyPort (producer)

To define a proxy port when instantiating the KMS client

 

Integer

region (producer)

The region in which KMS client needs to work

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Required KMS component options

You have to provide the amazonKmsClient in the Registry or your accessKey and secretKey to access the Amazon KMS service.

28.3. Usage

28.3.1. Message headers evaluated by the MQ producer

Expand
HeaderTypeDescription

CamelAwsKMSLimit

Integer

The limit number of keys to return while performing a listKeys operation

CamelAwsKMSOperation

String

The operation we want to perform

CamelAwsKMSDescription

String

A key description to use while performing a createKey operation

CamelAwsKMSKeyId

String

The key Id

Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.16 or higher).

28.4. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 29. AWS Lambda Component

Available as of Camel version 2.20

The Lambda component supports create, get, list, delete and invoke AWS Lambda functions.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon Lambda. More information are available at Amazon Lambda.

When creating a Lambda function, you need to specify a IAM role which has at least the AWSLambdaBasicExecuteRole policy attached.

Warning

Lambda is regional service. Unlike S3 bucket, Lambda function created in a given region is not available on other regions.

29.1. URI Format

aws-lambda://functionName[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?options=value&option2=value&…​

29.2. URI Options

The AWS Lambda component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS Lambda default configuration

 

LambdaConfiguration

accessKey (producer)

Amazon AWS Access Key

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

region (producer)

Amazon AWS Region

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS Lambda endpoint is configured using URI syntax:

aws-lambda:function
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

29.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

function

Required Name of the Lambda function.

 

String

29.2.2. Query Parameters (8 parameters):

Expand
NameDescriptionDefaultType

operation (producer)

Required The operation to perform. It can be listFunctions, getFunction, createFunction, deleteFunction or invokeFunction

 

LambdaOperations

region (producer)

Amazon AWS Region

 

String

awsLambdaClient (advanced)

To use a existing configured AwsLambdaClient as client

 

AWSLambda

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

proxyHost (proxy)

To define a proxy host when instantiating the Lambda client

 

String

proxyPort (proxy)

To define a proxy port when instantiating the Lambda client

 

Integer

accessKey (security)

Amazon AWS Access Key

 

String

secretKey (security)

Amazon AWS Secret Key

 

String

Required Lambda component options

You have to provide the awsLambdaClient in the Registry or your accessKey and secretKey to access the Amazon Lambda service.

29.3. Usage

29.3.1. Message headers evaluated by the Lambda producer

Expand
OperationHeaderTypeDescriptionRequired

All

CamelAwsLambdaOperation

String

The operation we want to perform. Override operation passed as query parameter

Yes

createFunction

CamelAwsLambdaS3Bucket

String

Amazon S3 bucket name where the .zip file containing your deployment package is stored. This bucket must reside in the same AWS region where you are creating the Lambda function.

No

createFunction

CamelAwsLambdaS3Key

String

The Amazon S3 object (the deployment package) key name you want to upload.

No

createFunction

CamelAwsLambdaS3ObjectVersion

String

The Amazon S3 object (the deployment package) version you want to upload.

No

createFunction

CamelAwsLambdaZipFile

String

The local path of the zip file (the deployment package). Content of zip file can also be put in Message body.

No

createFunction

CamelAwsLambdaRole

String

The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes your function to access any other Amazon Web Services (AWS) resources.

Yes

createFunction

CamelAwsLambdaRuntime

String

The runtime environment for the Lambda function you are uploading. (nodejs, nodejs4.3, nodejs6.10, java8, python2.7, python3.6, dotnetcore1.0, odejs4.3-edge)

Yes

createFunction

CamelAwsLambdaHandler

String

The function within your code that Lambda calls to begin execution. For Node.js, it is the module-name.export value in your function. For Java, it can be package.class-name::handler or package.class-name.

Yes

createFunction

CamelAwsLambdaDescription

String

The user-provided description.

No

createFunction

CamelAwsLambdaTargetArn

String

The parent object that contains the target ARN (Amazon Resource Name) of an Amazon SQS queue or Amazon SNS topic.

No

createFunction

CamelAwsLambdaMemorySize

Integer

The memory size, in MB, you configured for the function. Must be a multiple of 64 MB.

No

createFunction

CamelAwsLambdaKMSKeyArn

String

The Amazon Resource Name (ARN) of the KMS key used to encrypt your function’s environment variables. If not provided, AWS Lambda will use a default service key.

No

createFunction

CamelAwsLambdaPublish

Boolean

This boolean parameter can be used to request AWS Lambda to create the Lambda function and publish a version as an atomic operation.

No

createFunction

CamelAwsLambdaTimeout

Integer

The function execution time at which Lambda should terminate the function. The default is 3 seconds.

No

createFunction

CamelAwsLambdaTracingConfig

String

Your function’s tracing settings (Active or PassThrough).

No

createFunction

CamelAwsLambdaEnvironmentVariables

Map<String, String>

The key-value pairs that represent your environment’s configuration settings.

No

createFunction

CamelAwsLambdaEnvironmentTags

Map<String, String>

The list of tags (key-value pairs) assigned to the new function.

No

createFunction

CamelAwsLambdaSecurityGroupIds

List<String>

If your Lambda function accesses resources in a VPC, a list of one or more security groups IDs in your VPC.

No

createFunction

CamelAwsLambdaSubnetIds

List<String>

If your Lambda function accesses resources in a VPC, a list of one or more subnet IDs in your VPC.

No

Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.16 or higher).

29.4. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 30. AWS MQ Component

Available as of Camel version 2.21

The MQ component supports create, run, start, stop and terminate AWS MQ instances.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon MQ. More information are available at Amazon MQ.

30.1. URI Format

aws-mq://label[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?options=value&option2=value&…​

30.2. URI Options

The AWS MQ component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS MQ default configuration

 

MQConfiguration

accessKey (producer)

Amazon AWS Access Key

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

region (producer)

The region in which MQ client needs to work

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS MQ endpoint is configured using URI syntax:

aws-mq:label
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

30.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

label

Required Logical name

 

String

30.2.2. Query Parameters (8 parameters):

Expand
NameDescriptionDefaultType

accessKey (producer)

Amazon AWS Access Key

 

String

amazonMqClient (producer)

To use a existing configured AmazonMQClient as client

 

AmazonMQ

operation (producer)

Required The operation to perform. It can be listBrokers,createBroker,deleteBroker

 

MQOperations

proxyHost (producer)

To define a proxy host when instantiating the MQ client

 

String

proxyPort (producer)

To define a proxy port when instantiating the MQ client

 

Integer

region (producer)

The region in which MQ client needs to work

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Required EC2 component options

You have to provide the amazonEc2Client in the Registry or your accessKey and secretKey to access the Amazon EC2 service.

30.3. Usage

30.3.1. Message headers evaluated by the MQ producer

Expand
HeaderTypeDescription

CamelAwsMQMaxResults

String

The number of results that must be retrieved from listBrokers operation

CamelAwsMQBrokerName

String

The broker name

CamelAwsMQOperation

String

The operation we want to perform

CamelAwsMQBrokerId

String

The broker id

CamelAwsMQBrokerDeploymentMode

String

The deployment mode for the broker in the createBroker operation

Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.16 or higher).

30.4. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 31. AWS S3 Storage Service Component

Available as of Camel version 2.8

The S3 component supports storing and retrieving objetcs from/to Amazon’s S3 service.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon S3. More information are available at Amazon S3.

31.1. URI Format

aws-s3://bucketNameOrArn[?options]
Copy to Clipboard Toggle word wrap

The bucket will be created if it don’t already exists.
You can append query options to the URI in the following format, ?options=value&option2=value&…​

For example in order to read file hello.txt from bucket helloBucket, use the following snippet:

from("aws-s3:helloBucket?accessKey=yourAccessKey&secretKey=yourSecretKey&prefix=hello.txt")
  .to("file:/var/downloaded");
Copy to Clipboard Toggle word wrap

31.2. URI Options

The AWS S3 Storage Service component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS S3 default configuration

 

S3Configuration

accessKey (common)

Amazon AWS Access Key

 

String

secretKey (common)

Amazon AWS Secret Key

 

String

region (common)

The region where the bucket is located. This option is used in the com.amazonaws.services.s3.model.CreateBucketRequest.

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS S3 Storage Service endpoint is configured using URI syntax:

aws-s3:bucketNameOrArn
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

31.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

bucketNameOrArn

Required Bucket name or ARN

 

String

31.2.2. Query Parameters (50 parameters):

Expand
NameDescriptionDefaultType

amazonS3Client (common)

Reference to a com.amazonaws.services.sqs.AmazonS3 in the link:https://camel.apache.org/registry.htmlRegistry.

 

AmazonS3

pathStyleAccess (common)

Whether or not the S3 client should use path style access

false

boolean

policy (common)

The policy for this queue to set in the com.amazonaws.services.s3.AmazonS3setBucketPolicy() method.

 

String

proxyHost (common)

To define a proxy host when instantiating the SQS client

 

String

proxyPort (common)

Specify a proxy port to be used inside the client definition.

 

Integer

region (common)

The region in which S3 client needs to work

 

String

useIAMCredentials (common)

Set whether the S3 client should expect to load credentials on an EC2 instance or to expect static credentials to be passed in.

false

boolean

encryptionMaterials (common)

The encryption materials to use in case of Symmetric/Asymmetric client usage

 

EncryptionMaterials

useEncryption (common)

Define if encryption must be used or not

false

boolean

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

deleteAfterRead (consumer)

Delete objects from S3 after they have been retrieved. The delete is only performed if the Exchange is committed. If a rollback occurs, the object is not deleted. If this option is false, then the same objects will be retrieve over and over again on the polls. Therefore you need to use the Idempotent Consumer EIP in the route to filter out duplicates. You can filter using the link S3ConstantsBUCKET_NAME and link S3ConstantsKEY headers, or only the link S3ConstantsKEY header.

true

boolean

fileName (consumer)

To get the object from the bucket with the given file name

 

String

includeBody (consumer)

If it is true, the exchange body will be set to a stream to the contents of the file. If false, the headers will be set with the S3 object metadata, but the body will be null. This option is strongly related to autocloseBody option. In case of setting includeBody to true and autocloseBody to false, it will be up to the caller to close the S3Object stream. Setting autocloseBody to true, will close the S3Object stream automatically.

true

boolean

maxConnections (consumer)

Set the maxConnections parameter in the S3 client configuration

60

int

maxMessagesPerPoll (consumer)

Gets the maximum number of messages as a limit to poll at each polling. Is default unlimited, but use 0 or negative number to disable it as unlimited.

10

int

prefix (consumer)

The prefix which is used in the com.amazonaws.services.s3.model.ListObjectsRequest to only consume objects we are interested in.

 

String

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

autocloseBody (consumer)

If this option is true and includeBody is true, then the S3Object.close() method will be called on exchange completion. This option is strongly related to includeBody option. In case of setting includeBody to true and autocloseBody to false, it will be up to the caller to close the S3Object stream. Setting autocloseBody to true, will close the S3Object stream automatically.

true

boolean

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

pollStrategy (consumer)

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

 

PollingConsumerPoll Strategy

deleteAfterWrite (producer)

Delete file object after the S3 file has been uploaded

false

boolean

multiPartUpload (producer)

If it is true, camel will upload the file with multi part format, the part size is decided by the option of partSize

false

boolean

operation (producer)

The operation to do in case the user don’t want to do only an upload

 

S3Operations

partSize (producer)

Setup the partSize which is used in multi part upload, the default size is 25M.

26214400

long

serverSideEncryption (producer)

Sets the server-side encryption algorithm when encrypting the object using AWS-managed keys. For example use AES256.

 

String

storageClass (producer)

The storage class to set in the com.amazonaws.services.s3.model.PutObjectRequest request.

 

String

awsKMSKeyId (producer)

Define the id of KMS key to use in case KMS is enabled

 

String

useAwsKMS (producer)

Define if KMS must be used or not

false

boolean

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

accelerateModeEnabled ( advanced)

Define if Accelerate Mode enabled is true or false

false

boolean

chunkedEncodingDisabled ( advanced)

Define if disabled Chunked Encoding is true or false

false

boolean

dualstackEnabled ( advanced)

Define if Dualstack enabled is true or false

false

boolean

forceGlobalBucketAccess Enabled ( advanced)

Define if Force Global Bucket Access enabled is true or false

false

boolean

payloadSigningEnabled ( advanced)

Define if Payload Signing enabled is true or false

false

boolean

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

 

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

 

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

 

int

delay (scheduler)

Milliseconds before the next poll. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

initialDelay (scheduler)

Milliseconds before the first poll starts. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

1000

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

 

ScheduledExecutor Service

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz2 component

none

ScheduledPollConsumer Scheduler

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz2, Spring based scheduler.

 

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

accessKey (security)

Amazon AWS Access Key

 

String

secretKey (security)

Amazon AWS Secret Key

 

String

Required S3 component options

You have to provide the amazonS3Client in the Registry or your accessKey and secretKey to access the Amazon’s S3.

31.3. Batch Consumer

This component implements the Batch Consumer.

This allows you for instance to know how many messages exists in this batch and for instance let the Aggregator aggregate this number of messages.

31.4. Usage

31.4.1. Message headers evaluated by the S3 producer

Expand
HeaderTypeDescription

CamelAwsS3BucketName

String

The bucket Name which this object will be stored or which will be used for the current operation

CamelAwsS3BucketDestinationName

String

Camel 2.18: The bucket Destination Name which will be used for the current operation

CamelAwsS3ContentLength

Long

The content length of this object.

CamelAwsS3ContentType

String

The content type of this object.

CamelAwsS3ContentControl

String

Camel 2.8.2: The content control of this object.

CamelAwsS3ContentDisposition

String

Camel 2.8.2: The content disposition of this object.

CamelAwsS3ContentEncoding

String

Camel 2.8.2: The content encoding of this object.

CamelAwsS3ContentMD5

String

Camel 2.8.2: The md5 checksum of this object.

CamelAwsS3DestinationKey

String

Camel 2.18:The Destination key which will be used for the current operation

CamelAwsS3Key

String

The key under which this object will be stored or which will be used for the current operation

CamelAwsS3LastModified

java.util.Date

Camel 2.8.2: The last modified timestamp of this object.

CamelAwsS3Operation

String

Camel 2.18: The operation to perform. Permitted values are copyObject, listBuckets, deleteBucket, downloadLink

CamelAwsS3StorageClass

String

Camel 2.8.4: The storage class of this object.

CamelAwsS3CannedAcl

String

Camel 2.11.0: The canned acl that will be applied to the object. see com.amazonaws.services.s3.model.CannedAccessControlList for allowed values.

CamelAwsS3Acl

com.amazonaws.services.s3.model.AccessControlList

Camel 2.11.0: a well constructed Amazon S3 Access Control List object. see com.amazonaws.services.s3.model.AccessControlList for more details

CamelAwsS3Headers

Map<String,String>

Camel 2.15.0: support to get or set custom objectMetadata headers.

CamelAwsS3ServerSideEncryption

String

Camel 2.16: Sets the server-side encryption algorithm when encrypting the object using AWS-managed keys. For example use AES256.

CamelAwsS3VersionId

String

The version Id of the object to be stored or returned from the current operation

31.4.2. Message headers set by the S3 producer

Expand
HeaderTypeDescription

CamelAwsS3ETag

String

The ETag value for the newly uploaded object.

CamelAwsS3VersionId

String

The optional version ID of the newly uploaded object.

CamelAwsS3DownloadLinkExpiration

String

The expiration (millis) of URL download link. The link will be stored into CamelAwsS3DownloadLink response header.

31.4.3. Message headers set by the S3 consumer

Expand
HeaderTypeDescription

CamelAwsS3Key

String

The key under which this object is stored.

CamelAwsS3BucketName

String

The name of the bucket in which this object is contained.

CamelAwsS3ETag

String

The hex encoded 128-bit MD5 digest of the associated object according to RFC 1864. This data is used as an integrity check to verify that the data received by the caller is the same data that was sent by Amazon S3.

CamelAwsS3LastModified

Date

The value of the Last-Modified header, indicating the date and time at which Amazon S3 last recorded a modification to the associated object.

CamelAwsS3VersionId

String

The version ID of the associated Amazon S3 object if available. Version IDs are only assigned to objects when an object is uploaded to an Amazon S3 bucket that has object versioning enabled.

CamelAwsS3ContentType

String

The Content-Type HTTP header, which indicates the type of content stored in the associated object. The value of this header is a standard MIME type.

CamelAwsS3ContentMD5

String

The base64 encoded 128-bit MD5 digest of the associated object (content - not including headers) according to RFC 1864. This data is used as a message integrity check to verify that the data received by Amazon S3 is the same data that the caller sent.

CamelAwsS3ContentLength

Long

The Content-Length HTTP header indicating the size of the associated object in bytes.

CamelAwsS3ContentEncoding

String

The optional Content-Encoding HTTP header specifying what content encodings have been applied to the object and what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type field.

CamelAwsS3ContentDisposition

String

The optional Content-Disposition HTTP header, which specifies presentational information such as the recommended filename for the object to be saved as.

CamelAwsS3ContentControl

String

The optional Cache-Control HTTP header which allows the user to specify caching behavior along the HTTP request/reply chain.

CamelAwsS3ServerSideEncryption

String

Camel 2.16: The server-side encryption algorithm when encrypting the object using AWS-managed keys.

31.4.4. Advanced AmazonS3 configuration

If your Camel Application is running behind a firewall or if you need to have more control over the AmazonS3 instance configuration, you can create your own instance:

AWSCredentials awsCredentials = new BasicAWSCredentials("myAccessKey", "mySecretKey");

ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);

AmazonS3 client = new AmazonS3Client(awsCredentials, clientConfiguration);

registry.bind("client", client);
Copy to Clipboard Toggle word wrap

and refer to it in your Camel aws-s3 component configuration:

from("aws-s3://MyBucket?amazonS3Client=#client&delay=5000&maxMessagesPerPoll=5")
.to("mock:result");
Copy to Clipboard Toggle word wrap

31.4.5. Use KMS with the S3 component

To use AWS KMS to encrypt/decrypt data by using AWS infrastructure you can use the options introduced in 2.21.x like in the following example

from("file:tmp/test?fileName=test.txt")
     .setHeader(S3Constants.KEY, constant("testFile"))
     .to("aws-s3://mybucket?amazonS3Client=#client&useAwsKMS=true&awsKMSKeyId=3f0637ad-296a-3dfe-a796-e60654fb128c");
Copy to Clipboard Toggle word wrap

In this way you’ll ask to S3, to use the KMS key 3f0637ad-296a-3dfe-a796-e60654fb128c, to encrypt the file test.txt. When you’ll ask to download this file, the decryption will be done directly before the download.

31.4.6. Use "useIAMCredentials" with the s3 component

To use AWS IAM credentials, you must first verify that the EC2 in which you are launching the Camel application on has an IAM role associated with it containing the appropriate policies attached to run effectively. Keep in mind that this feature should only be set to "true" on remote instances. To clarify even further, you must still use static credentials locally since IAM is an AWS specific component, but AWS environments should now be easier to manage. After this is implemented and understood, you can set the query parameter "useIAMCredentials" to "true" for AWS environments! To effectively toggle this on and off based on local and remote environments, you can consider enabling this query parameter with system environment variables. For example, your code could set the "useIAMCredentials" query parameter to "true", when the system environment variable called "isRemote" is set to true (there are many other ways to do this and this should act as a simple example). Although it doesn’t take away the need for static credentials completely, using IAM credentials on AWS environments takes away the need to refresh on remote environments and adds a major security boost (IAM credentials are refreshed automatically every 6 hours and update when their policies are updated). This is the AWS recommended way to manage credentials and therefore should be used as often as possible.

31.5. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.8 or higher).

31.6. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 32. AWS SimpleDB Component

Available as of Camel version 2.9

The sdb component supports storing and retrieving data from/to Amazon’s SDB service.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon SDB. More information are available at Amazon SDB.

32.1. URI Format

aws-sdb://domainName[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?options=value&option2=value&…​

32.2. URI Options

The AWS SimpleDB component has no options.

The AWS SimpleDB endpoint is configured using URI syntax:

aws-sdb:domainName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

32.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

domainName

Required The name of the domain currently worked with.

 

String

32.2.2. Query Parameters (10 parameters):

Expand
NameDescriptionDefaultType

accessKey (producer)

Amazon AWS Access Key

 

String

amazonSDBClient (producer)

To use the AmazonSimpleDB as the client

 

AmazonSimpleDB

consistentRead (producer)

Determines whether or not strong consistency should be enforced when data is read.

false

boolean

maxNumberOfDomains (producer)

The maximum number of domain names you want returned. The range is 1 to 100.

 

Integer

operation (producer)

Operation to perform

PutAttributes

SdbOperations

proxyHost (producer)

To define a proxy host when instantiating the SDB client

 

String

proxyPort (producer)

To define a proxy port when instantiating the SDB client

 

Integer

region (producer)

The region in which SDB client needs to work

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Required SDB component options

You have to provide the amazonSDBClient in the Registry or your accessKey and secretKey to access the Amazon’s SDB.

32.3. Usage

32.3.1. Message headers evaluated by the SDB producer

Expand
HeaderTypeDescription

CamelAwsSdbAttributes

Collection<Attribute>

List of attributes to be acted upon.

CamelAwsSdbAttributeNames

Collection<String>

The names of the attributes to be retrieved.

CamelAwsSdbConsistentRead

Boolean

Determines whether or not strong consistency should be enforced when data is read.

CamelAwsSdbDeletableItems

Collection<DeletableItem>

A list of items on which to perform the delete operation in a batch.

CamelAwsSdbDomainName

String

The name of the domain currently worked with.

CamelAwsSdbItemName

String

The unique key for this item

CamelAwsSdbMaxNumberOfDomains

Integer

The maximum number of domain names you want returned. The range is 1 * to 100.

CamelAwsSdbNextToken

String

A string specifying where to start the next list of domain/item names.

CamelAwsSdbOperation

String

To override the operation from the URI options.

CamelAwsSdbReplaceableAttributes

Collection<ReplaceableAttribute>

List of attributes to put in an Item.

CamelAwsSdbReplaceableItems

Collection<ReplaceableItem>

A list of items to put in a Domain.

CamelAwsSdbSelectExpression

String

The expression used to query the domain.

CamelAwsSdbUpdateCondition

UpdateCondition

The update condition which, if specified, determines whether the specified attributes will be updated/deleted or not.

32.3.2. Message headers set during DomainMetadata operation

Expand
HeaderTypeDescription

CamelAwsSdbTimestamp

Integer

The data and time when metadata was calculated, in Epoch (UNIX) seconds.

CamelAwsSdbItemCount

Integer

The number of all items in the domain.

CamelAwsSdbAttributeNameCount

Integer

The number of unique attribute names in the domain.

CamelAwsSdbAttributeValueCount

Integer

The number of all attribute name/value pairs in the domain.

CamelAwsSdbAttributeNameSize

Long

The total size of all unique attribute names in the domain, in bytes.

CamelAwsSdbAttributeValueSize

Long

The total size of all attribute values in the domain, in bytes.

CamelAwsSdbItemNameSize

Long

The total size of all item names in the domain, in bytes.

32.3.3. Message headers set during GetAttributes operation

Expand
HeaderTypeDescription

CamelAwsSdbAttributes

List<Attribute>

The list of attributes returned by the operation.

32.3.4. Message headers set during ListDomains operation

Expand
HeaderTypeDescription

CamelAwsSdbDomainNames

List<String>

A list of domain names that match the expression.

CamelAwsSdbNextToken

String

An opaque token indicating that there are more domains than the specified MaxNumberOfDomains still available.

32.3.5. Message headers set during Select operation

Expand
HeaderTypeDescription

CamelAwsSdbItems

List<Item>

A list of items that match the select expression.

CamelAwsSdbNextToken

String

An opaque token indicating that more items than MaxNumberOfItems were matched, the response size exceeded 1 megabyte, or the execution time exceeded 5 seconds.

32.3.6. Advanced AmazonSimpleDB configuration

If you need more control over the AmazonSimpleDB instance configuration you can create your own instance and refer to it from the URI:

from("direct:start")
.to("aws-sdb://domainName?amazonSDBClient=#client");
Copy to Clipboard Toggle word wrap

The #client refers to a AmazonSimpleDB in the Registry.

For example if your Camel Application is running behind a firewall:

AWSCredentials awsCredentials = new BasicAWSCredentials("myAccessKey", "mySecretKey");
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);

AmazonSimpleDB client = new AmazonSimpleDBClient(awsCredentials, clientConfiguration);

registry.bind("client", client);
Copy to Clipboard Toggle word wrap

32.4. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.8.4 or higher).

32.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 33. AWS Simple Email Service Component

Available as of Camel version 2.9

The ses component supports sending emails with Amazon’s SES service.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon SES. More information are available at Amazon SES.

33.1. URI Format

aws-ses://from[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?options=value&option2=value&…​

33.2. URI Options

The AWS Simple Email Service component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS SES default configuration

 

SesConfiguration

accessKey (producer)

Amazon AWS Access Key

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

region (producer)

The region in which SES client needs to work

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS Simple Email Service endpoint is configured using URI syntax:

aws-ses:from
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

33.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

from

Required The sender’s email address.

 

String

33.2.2. Query Parameters (11 parameters):

Expand
NameDescriptionDefaultType

amazonSESClient (producer)

To use the AmazonSimpleEmailService as the client

 

AmazonSimpleEmail Service

proxyHost (producer)

To define a proxy host when instantiating the SES client

 

String

proxyPort (producer)

To define a proxy port when instantiating the SES client

 

Integer

region (producer)

The region in which SES client needs to work

 

String

replyToAddresses (producer)

List of reply-to email address(es) for the message, override it using 'CamelAwsSesReplyToAddresses' header.

 

List

returnPath (producer)

The email address to which bounce notifications are to be forwarded, override it using 'CamelAwsSesReturnPath' header.

 

String

subject (producer)

The subject which is used if the message header 'CamelAwsSesSubject' is not present.

 

String

to (producer)

List of destination email address. Can be overriden with 'CamelAwsSesTo' header.

 

List

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

accessKey (security)

Amazon AWS Access Key

 

String

secretKey (security)

Amazon AWS Secret Key

 

String

Required SES component options

You have to provide the amazonSESClient in the Registry or your accessKey and secretKey to access the Amazon’s SES.

33.3. Usage

33.3.1. Message headers evaluated by the SES producer

Expand
HeaderTypeDescription

CamelAwsSesFrom

String

The sender’s email address.

CamelAwsSesTo

List<String>

The destination(s) for this email.

CamelAwsSesSubject

String

The subject of the message.

CamelAwsSesReplyToAddresses

List<String>

The reply-to email address(es) for the message.

CamelAwsSesReturnPath

String

The email address to which bounce notifications are to be forwarded.

CamelAwsSesHtmlEmail

Boolean

Since Camel 2.12.3 The flag to show if email content is HTML.

33.3.2. Message headers set by the SES producer

Expand
HeaderTypeDescription

CamelAwsSesMessageId

String

The Amazon SES message ID.

33.3.3. Advanced AmazonSimpleEmailService configuration

If you need more control over the AmazonSimpleEmailService instance configuration you can create your own instance and refer to it from the URI:

from("direct:start")
.to("aws-ses://example@example.com?amazonSESClient=#client");
Copy to Clipboard Toggle word wrap

The #client refers to a AmazonSimpleEmailService in the Registry.

For example if your Camel Application is running behind a firewall:

AWSCredentials awsCredentials = new BasicAWSCredentials("myAccessKey", "mySecretKey");
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);
AmazonSimpleEmailService client = new AmazonSimpleEmailServiceClient(awsCredentials, clientConfiguration);

registry.bind("client", client);
Copy to Clipboard Toggle word wrap

33.4. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.8.4 or higher).

33.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 34. AWS Simple Notification System Component

Available as of Camel version 2.8

The SNS component allows messages to be sent to an Amazon Simple Notification Topic. The implementation of the Amazon API is provided by the AWS SDK.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon SNS. More information are available at Amazon SNS.

34.1. URI Format

aws-sns://topicNameOrArn[?options]
Copy to Clipboard Toggle word wrap

The topic will be created if they don’t already exists.
You can append query options to the URI in the following format, ?options=value&option2=value&…​

34.2. URI Options

The AWS Simple Notification System component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS SNS default configuration

 

SnsConfiguration

accessKey (producer)

Amazon AWS Access Key

 

String

secretKey (producer)

Amazon AWS Secret Key

 

String

region (producer)

The region in which SNS client needs to work

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS Simple Notification System endpoint is configured using URI syntax:

aws-sns:topicNameOrArn
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

34.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

topicNameOrArn

Required Topic name or ARN

 

String

34.2.2. Query Parameters (11 parameters):

Expand
NameDescriptionDefaultType

amazonSNSClient (producer)

To use the AmazonSNS as the client

 

AmazonSNS

headerFilterStrategy (producer)

To use a custom HeaderFilterStrategy to map headers to/from Camel.

 

HeaderFilterStrategy

messageStructure (producer)

The message structure to use such as json

 

String

policy (producer)

The policy for this queue

 

String

proxyHost (producer)

To define a proxy host when instantiating the SNS client

 

String

proxyPort (producer)

To define a proxy port when instantiating the SNS client

 

Integer

region (producer)

The region in which SNS client needs to work

 

String

subject (producer)

The subject which is used if the message header 'CamelAwsSnsSubject' is not present.

 

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

accessKey (security)

Amazon AWS Access Key

 

String

secretKey (security)

Amazon AWS Secret Key

 

String

Required SNS component options

You have to provide the amazonSNSClient in the Registry or your accessKey and secretKey to access the Amazon’s SNS.

34.3. Usage

34.3.1. Message headers evaluated by the SNS producer

Expand
HeaderTypeDescription

CamelAwsSnsSubject

String

The Amazon SNS message subject. If not set, the subject from the SnsConfiguration is used.

34.3.2. Message headers set by the SNS producer

Expand
HeaderTypeDescription

CamelAwsSnsMessageId

String

The Amazon SNS message ID.

34.3.3. Advanced AmazonSNS configuration

If you need more control over the AmazonSNS instance configuration you can create your own instance and refer to it from the URI:

from("direct:start")
.to("aws-sns://MyTopic?amazonSNSClient=#client");
Copy to Clipboard Toggle word wrap

The #client refers to a AmazonSNS in the Registry.

For example if your Camel Application is running behind a firewall:

AWSCredentials awsCredentials = new BasicAWSCredentials("myAccessKey", "mySecretKey");
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);
AmazonSNS client = new AmazonSNSClient(awsCredentials, clientConfiguration);

registry.bind("client", client);
Copy to Clipboard Toggle word wrap

34.4. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.8 or higher).

34.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 35. AWS Simple Queue Service Component

Available as of Camel version 2.6

The sqs component supports sending and receiving messages to Amazon’s SQS service.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon SQS. More information are available at Amazon SQS.

35.1. URI Format

aws-sqs://queueNameOrArn[?options]
Copy to Clipboard Toggle word wrap

The queue will be created if they don’t already exists.
You can append query options to the URI in the following format, ?options=value&option2=value&…​

35.2. URI Options

The AWS Simple Queue Service component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS SQS default configuration

 

SqsConfiguration

accessKey (common)

Amazon AWS Access Key

 

String

secretKey (common)

Amazon AWS Secret Key

 

String

region (common)

Specify the queue region which could be used with queueOwnerAWSAccountId to build the service URL.

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS Simple Queue Service endpoint is configured using URI syntax:

aws-sqs:queueNameOrArn
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

35.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

queueNameOrArn

Required Queue name or ARN

 

String

35.2.2. Query Parameters (46 parameters):

Expand
NameDescriptionDefaultType

amazonAWSHost (common)

The hostname of the Amazon AWS cloud.

amazonaws.com

String

amazonSQSClient (common)

To use the AmazonSQS as client

 

AmazonSQS

headerFilterStrategy (common)

To use a custom HeaderFilterStrategy to map headers to/from Camel.

 

HeaderFilterStrategy

queueOwnerAWSAccountId (common)

Specify the queue owner aws account id when you need to connect the queue with different account owner.

 

String

region (common)

Specify the queue region which could be used with queueOwnerAWSAccountId to build the service URL.

 

String

attributeNames (consumer)

A list of attribute names to receive when consuming. Multiple names can be separated by comma.

 

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

concurrentConsumers (consumer)

Allows you to use multiple threads to poll the sqs queue to increase throughput

1

int

defaultVisibilityTimeout (consumer)

The default visibility timeout (in seconds)

 

Integer

deleteAfterRead (consumer)

Delete message from SQS after it has been read

true

boolean

deleteIfFiltered (consumer)

Whether or not to send the DeleteMessage to the SQS queue if an exchange fails to get through a filter. If 'false' and exchange does not make it through a Camel filter upstream in the route, then don’t send DeleteMessage.

true

boolean

extendMessageVisibility (consumer)

If enabled then a scheduled background task will keep extending the message visibility on SQS. This is needed if it takes a long time to process the message. If set to true defaultVisibilityTimeout must be set. See details at Amazon docs.

false

boolean

maxMessagesPerPoll (consumer)

Gets the maximum number of messages as a limit to poll at each polling. Is default unlimited, but use 0 or negative number to disable it as unlimited.

 

int

messageAttributeNames (consumer)

A list of message attribute names to receive when consuming. Multiple names can be separated by comma.

 

String

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

visibilityTimeout (consumer)

The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved by a ReceiveMessage request to set in the com.amazonaws.services.sqs.model.SetQueueAttributesRequest. This only make sense if its different from defaultVisibilityTimeout. It changes the queue visibility timeout attribute permanently.

 

Integer

waitTimeSeconds (consumer)

Duration in seconds (0 to 20) that the ReceiveMessage action call will wait until a message is in the queue to include in the response.

 

Integer

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

pollStrategy (consumer)

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

 

PollingConsumerPoll Strategy

delaySeconds (producer)

Delay sending messages for a number of seconds.

 

Integer

messageDeduplicationId Strategy (producer)

Only for FIFO queues. Strategy for setting the messageDeduplicationId on the message. Can be one of the following options: useExchangeId, useContentBasedDeduplication. For the useContentBasedDeduplication option, no messageDeduplicationId will be set on the message.

useExchangeId

MessageDeduplicationId Strategy

messageGroupIdStrategy (producer)

Only for FIFO queues. Strategy for setting the messageGroupId on the message. Can be one of the following options: useConstant, useExchangeId, usePropertyValue. For the usePropertyValue option, the value of property CamelAwsMessageGroupId will be used.

 

MessageGroupIdStrategy

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

 

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

 

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

 

int

delay (scheduler)

Milliseconds before the next poll. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

initialDelay (scheduler)

Milliseconds before the first poll starts. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

1000

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

 

ScheduledExecutor Service

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz2 component

none

ScheduledPollConsumer Scheduler

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz2, Spring based scheduler.

 

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

proxyHost (proxy)

To define a proxy host when instantiating the SQS client

 

String

proxyPort (proxy)

To define a proxy port when instantiating the SQS client

 

Integer

maximumMessageSize (queue)

The maximumMessageSize (in bytes) an SQS message can contain for this queue.

 

Integer

messageRetentionPeriod (queue)

The messageRetentionPeriod (in seconds) a message will be retained by SQS for this queue.

 

Integer

policy (queue)

The policy for this queue

 

String

receiveMessageWaitTime Seconds (queue)

If you do not specify WaitTimeSeconds in the request, the queue attribute ReceiveMessageWaitTimeSeconds is used to determine how long to wait.

 

Integer

redrivePolicy (queue)

Specify the policy that send message to DeadLetter queue. See detail at Amazon docs.

 

String

accessKey (security)

Amazon AWS Access Key

 

String

secretKey (security)

Amazon AWS Secret Key

 

String

Required SQS component options

You have to provide the amazonSQSClient in the Registry or your accessKey and secretKey to access the Amazon’s SQS.

35.3. Batch Consumer

This component implements the Batch Consumer.

This allows you for instance to know how many messages exists in this batch and for instance let the Aggregator aggregate this number of messages.

35.4. Usage

35.4.1. Message headers set by the SQS producer

Expand
HeaderTypeDescription

CamelAwsSqsMD5OfBody

String

The MD5 checksum of the Amazon SQS message.

CamelAwsSqsMessageId

String

The Amazon SQS message ID.

CamelAwsSqsDelaySeconds

Integer

Since Camel 2.11, the delay seconds that the Amazon SQS message can be see by others.

35.4.2. Message headers set by the SQS consumer

Expand
HeaderTypeDescription

CamelAwsSqsMD5OfBody

String

The MD5 checksum of the Amazon SQS message.

CamelAwsSqsMessageId

String

The Amazon SQS message ID.

CamelAwsSqsReceiptHandle

String

The Amazon SQS message receipt handle.

CamelAwsSqsAttributes

Map<String, String>

The Amazon SQS message attributes.

35.4.3. Advanced AmazonSQS configuration

If your Camel Application is running behind a firewall or if you need to have more control over the AmazonSQS instance configuration, you can create your own instance:

AWSCredentials awsCredentials = new BasicAWSCredentials("myAccessKey", "mySecretKey");

ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);

AmazonSQS client = new AmazonSQSClient(awsCredentials, clientConfiguration);

registry.bind("client", client);
Copy to Clipboard Toggle word wrap

and refer to it in your Camel aws-sqs component configuration:

from("aws-sqs://MyQueue?amazonSQSClient=#client&delay=5000&maxMessagesPerPoll=5")
.to("mock:result");
Copy to Clipboard Toggle word wrap

35.5. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.6 or higher).

35.6. JMS-style Selectors

SQS does not allow selectors, but you can effectively achieve this by using the Camel Filter EIP and setting an appropriate visibilityTimeout. When SQS dispatches a message, it will wait up to the visibility timeout before it will try to dispatch the message to a different consumer unless a DeleteMessage is received. By default, Camel will always send the DeleteMessage at the end of the route, unless the route ended in failure. To achieve appropriate filtering and not send the DeleteMessage even on successful completion of the route, use a Filter:

from("aws-sqs://MyQueue?amazonSQSClient=#client&defaultVisibilityTimeout=5000&deleteIfFiltered=false")
.filter("${header.login} == true")
.to("mock:result");
Copy to Clipboard Toggle word wrap

In the above code, if an exchange doesn’t have an appropriate header, it will not make it through the filter AND also not be deleted from the SQS queue. After 5000 miliseconds, the message will become visible to other consumers.

35.7. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • AWS Component

Chapter 36. AWS Simple Workflow Component

Available as of Camel version 2.13

The Simple Workflow component supports managing workflows from Amazon’s Simple Workflow service.

Prerequisites

You must have a valid Amazon Web Services developer account, and be signed up to use Amazon Simple Workflow. More information are available at Amazon Simple Workflow.

36.1. URI Format

aws-swf://<workflow|activity>[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?options=value&option2=value&…​

36.2. URI Options

The AWS Simple Workflow component supports 5 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

The AWS SWF default configuration

 

SWFConfiguration

accessKey (common)

Amazon AWS Access Key.

 

String

secretKey (common)

Amazon AWS Secret Key.

 

String

region (common)

Amazon AWS Region.

 

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The AWS Simple Workflow endpoint is configured using URI syntax:

aws-swf:type
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

36.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

type

Required Activity or workflow

 

String

36.2.2. Query Parameters (30 parameters):

Expand
NameDescriptionDefaultType

amazonSWClient (common)

To use the given AmazonSimpleWorkflowClient as client

 

AmazonSimpleWorkflow Client

dataConverter (common)

An instance of com.amazonaws.services.simpleworkflow.flow.DataConverter to use for serializing/deserializing the data.

 

DataConverter

domainName (common)

The workflow domain to use.

 

String

eventName (common)

The workflow or activity event name to use.

 

String

region (common)

Amazon AWS Region.

 

String

version (common)

The workflow or activity event version to use.

 

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

clientConfiguration Parameters (advanced)

To configure the ClientConfiguration using the key/values from the Map.

 

Map

startWorkflowOptions Parameters (advanced)

To configure the StartWorkflowOptions using the key/values from the Map.

 

Map

sWClientParameters (advanced)

To configure the AmazonSimpleWorkflowClient using the key/values from the Map.

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

activityList (activity)

The list name to consume activities from.

 

String

activitySchedulingOptions (activity)

Activity scheduling options

 

ActivityScheduling Options

activityThreadPoolSize (activity)

Maximum number of threads in work pool for activity.

100

int

activityTypeExecution Options (activity)

Activity execution options

 

ActivityTypeExecution Options

activityTypeRegistration Options (activity)

Activity registration options

 

ActivityType RegistrationOptions

childPolicy (workflow)

The policy to use on child workflows when terminating a workflow.

 

String

executionStartToClose Timeout (workflow)

Set the execution start to close timeout.

3600

String

operation (workflow)

Workflow operation

START

String

signalName (workflow)

The name of the signal to send to the workflow.

 

String

stateResultType (workflow)

The type of the result when a workflow state is queried.

 

String

taskStartToCloseTimeout (workflow)

Set the task start to close timeout.

600

String

terminationDetails (workflow)

Details for terminating a workflow.

 

String

terminationReason (workflow)

The reason for terminating a workflow.

 

String

workflowList (workflow)

The list name to consume workflows from.

 

String

workflowTypeRegistration Options (workflow)

Workflow registration options

 

WorkflowType RegistrationOptions

accessKey (security)

Amazon AWS Access Key.

 

String

secretKey (security)

Amazon AWS Secret Key.

 

String

Required SWF component options

You have to provide the amazonSWClient in the Registry or your accessKey and secretKey to access the Amazon’s Simple Workflow Service.

36.3. Usage

A workflow producer allows interacting with a workflow. It can start a new workflow execution, query its state, send signals to a running workflow, or terminate and cancel it.

Expand
HeaderTypeDescription

CamelSWFOperation

String

The operation to perform on the workflow. Supported operations are:
SIGNAL, CANCEL, TERMINATE, GET_STATE, START, DESCRIBE, GET_HISTORY.

CamelSWFWorkflowId

String

A workflow ID to use.

CamelAwsDdbKeyCamelSWFRunId

String

A worfklow run ID to use.

CamelSWFStateResultType

String

The type of the result when a workflow state is queried.

CamelSWFEventName

String

The workflow or activity event name to use.

CamelSWFVersion

String

The workflow or activity event version to use.

CamelSWFReason

String

The reason for terminating a workflow.

CamelSWFDetails

String

Details for terminating a workflow.

CamelSWFChildPolicy

String

The policy to use on child workflows when terminating a workflow.

36.3.2. Message headers set by the SWF Workflow Producer

Expand
HeaderTypeDescription

CamelSWFWorkflowId

String

The worfklow ID used or newly generated.

CamelAwsDdbKeyCamelSWFRunId

String

The worfklow run ID used or generated.

36.3.3. Message headers set by the SWF Workflow Consumer

A workflow consumer represents the workflow logic. When it is started, it will start polling workflow decision tasks and process them. In addition to processing decision tasks, a workflow consumer route, will also receive signals (send from a workflow producer) or state queries. The primary purpose of a workflow consumer is to schedule activity tasks for execution using activity producers. Actually activity tasks can be scheduled only from a thread started by a workflow consumer.

Expand
HeaderTypeDescription

CamelSWFAction

String

Indicates what type is the current event: CamelSWFActionExecute, CamelSWFSignalReceivedAction or CamelSWFGetStateAction.

CamelSWFWorkflowReplaying

boolean

Indicates whether the current decision task is a replay or not.

CamelSWFWorkflowStartTime

long

The time of the start event for this decision task.

36.3.4. Message headers set by the SWF Activity Producer

An activity producer allows scheduling activity tasks. An activity producer can be used only from a thread started by a workflow consumer ie, it can process synchronous exchanges started by a workflow consumer.

Expand
HeaderTypeDescription

CamelSWFEventName

String

The activity name to schedule.

CamelSWFVersion

String

The activity version to schedule.

36.3.5. Message headers set by the SWF Activity Consumer

Expand
HeaderTypeDescription

CamelSWFTaskToken

String

The task token that is required to report task completion for manually completed tasks.

36.3.6. Advanced amazonSWClient configuration

If you need more control over the AmazonSimpleWorkflowClient instance configuration you can create your own instance and refer to it from the URI:

The #client refers to a AmazonSimpleWorkflowClient in the Registry.

For example if your Camel Application is running behind a firewall:

AWSCredentials awsCredentials = new BasicAWSCredentials("myAccessKey", "mySecretKey");
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("http://myProxyHost");
clientConfiguration.setProxyPort(8080);

AmazonSimpleWorkflowClient client = new AmazonSimpleWorkflowClient(awsCredentials, clientConfiguration);

registry.bind("client", client);
Copy to Clipboard Toggle word wrap

36.4. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-aws</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.13 or higher).

36.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started

AWS Component

Chapter 37. AWS XRay Component

Available as of Camel 2.21

The camel-aws-xray component is used for tracing and timing incoming and outgoing Camel messages using AWS XRay.

Events (subsegments) are captured for incoming and outgoing messages being sent to/from Camel.

37.1. Dependency

In order to include AWS XRay support into Camel, the archive containing the Camel related AWS XRay related classes need to be added to the project. In addition to that, AWS XRay libraries also need to be available.

To include both, AWS XRay and Camel, dependencies use the following Maven imports:

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-xray-recorder-sdk-bom</artifactId>
        <version>1.3.1</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
      <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-aws-xray</artifactId>
      </dependency>

      <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-xray-recorder-sdk-core</artifactId>
      </dependency>
      <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-xray-recorder-sdk-aws-sdk</artifactId>
      </dependency>
  <dependencies>
Copy to Clipboard Toggle word wrap

37.2. Configuration

The configuration properties for the AWS XRay tracer are:

Expand
OptionDefaultDescription

addExcludePatterns

 

Sets exclude pattern(s) that will disable tracing for Camel messages that matches the pattern. The content is a Set<String> where the key is a pattern matching routeId’s. The pattern uses the rules from Intercept.

setTracingStrategy

NoopTracingStrategy

Allows a custom Camel InterceptStrategy to be provided in order to track invoked processor definitions like BeanDefinition or ProcessDefinition. TraceAnnotatedTracingStrategy will track any classes invoked via .bean(…​) or .process(…​) that contain a @XRayTrace annotation at class level.

There is currently only one way an AWS XRay tracer can be configured to provide distributed tracing for a Camel application:

37.2.1. Explicit

Include the camel-aws-xray component in your POM, along with any specific dependencies associated with the AWS XRay Tracer.

To explicitly configure AWS XRay support, instantiate the XRayTracer and initialize the camel context. You can optionally specify a Tracer, or alternatively it can be implicitly discovered using the Registry or ServiceLoader.

XRayTracer xrayTracer = new XRayTracer();
// By default it uses a NoopTracingStrategy, but you can override it with a specific InterceptStrategy implementation.
xrayTracer.setTracingStrategy(...);
// And then initialize the context
xrayTracer.init(camelContext);
Copy to Clipboard Toggle word wrap

To use XRayTracer in XML, all you need to do is to define the AWS XRay tracer bean. Camel will automatically discover and use it.

  <bean id="tracingStrategy" class="..."/>
  <bean id="aws-xray-tracer" class="org.apache.camel.component.aws.xray.XRayTracer" />
    <property name="tracer" ref="tracingStrategy"/>
  </bean>
Copy to Clipboard Toggle word wrap

In case of the default NoopTracingStrategy only the creation and deletion of exchanges is tracked but not the invocation of certain beans or EIP patterns.

37.2.2. Tracking of comprehensive route execution

In order to track the execution of an exchange among multiple routes, on exchange creation a unique trace ID is generated and stored in the headers if no corresponding value was yet available. This trace ID is copied over to new exchanges in order to keep a consistent view of the processed exchange.

As AWS XRay traces work on a thread-local basis the current sub/segment should be copied over to the new thread and set as explained in in the AWS XRay documentation. The Camel AWS XRay component therefore provides an additional header field that the component will use in order to set the passed AWS XRay Entity to the new thread and thus keep the tracked data to the route rather than exposing a new segment which seems uncorrelated with any of the executed routes.

The component will use the following constants found in the headers of the exchange:

Expand
HeaderDescription

Camel-AWS-XRay-Trace-ID

Contains a reference to the AWS XRay TraceID object to provide a comprehensive view of the invoked routes

Camel-AWS-XRay-Trace-Entity

Contains a reference to the actual AWS XRay Segment or Subsegment which is copied over to the new thread. This header should be set in case a new thread is spawned and the performed tasks should be exposed as part of the executed route instead of creating a new unrelated segment.

Note that the AWS XRay Entity (i.e., Segment and Subsegment) are not serializable and therefore should not get passed to other JVM processes.

37.3. Example

You can find an example demonstrating the way to configure AWS XRay tracing within the tests accompanying this project.

Chapter 38. Camel Components for Windows Azure Services

The Camel Components for Windows Azure Services provide connectivity to Azure services from Camel.

 

Expand
Azure ServiceCamel ComponentCamel VersionComponent Description

Storage Blob Service

Azure-Blob

2.9.0

Supports storing and retrieving of blobs

Storage Queue Service

Azure-Queue

2.9.0

Supports storing and retrieving of messages in the queues

Chapter 39. Azure Storage Blob Service Component

Available as of Camel version 2.19

The Azure Blob component supports storing and retrieving the blobs to/from Azure Storage Blob service.

Prerequisites

You must have a valid Windows Azure Storage account. More information is available at Azure Documentation Portal.

39.1. URI Format

azure-blob://accountName/containerName[/blobName][?options]
Copy to Clipboard Toggle word wrap

In most cases a blobName is required and the blob will be created if it does not already exist.
You can append query options to the URI in the following format: ?options=value&option2=value&…​

For example, to download a blob content from the public block blob blockBlob located on the container1 in the camelazure storage account, use the following snippet:

from("azure-blob:camelazure/container1/blockBlob").
to("file://blobdirectory");
Copy to Clipboard Toggle word wrap

39.2. URI Options

The Azure Storage Blob Service component has no options.

The Azure Storage Blob Service endpoint is configured using URI syntax:

azure-blob:containerOrBlobUri
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

39.2.1. Path Parameters (1 parameter)

Expand
NameDescriptionDefaultType

containerOrBlobUri

Required: Container or Blob compact URI.

 

String

39.2.2. Query Parameters (19 parameters)

Expand
NameDescriptionDefaultType

azureBlobClient (common)

The blob service client.

 

CloudBlob

blobOffset (common)

Set the blob offset for the upload or download operations, default is 0.

0

Long

blobType (common)

Set a blob type, blockblob is default.

blockblob

BlobType

closeStreamAfterRead (common)

Close the stream after read or keep it open, default is true.

true

boolean

credentials (common)

Set the storage credentials, required in most cases.

 

StorageCredentials

dataLength (common)

Set the data length for the download or page blob upload operations.

 

Long

fileDir (common)

Set the file directory where the downloaded blobs will be saved.

 

String

publicForRead (common)

Storage resources can be public for reading their content. If this property is enabled, the credentials do not have to be set.

false

boolean

streamReadSize (common)

Set the minimum read size in bytes when reading the blob content.

 

int

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler. This means any exceptions that occurred (for example, while the consumer was trying to pick up incoming messages), will now be processed as a message and handled by the routing Error Handler. By default, the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, which will be logged at WARN or ERROR level and ignored.

false

boolean

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Note that if the option bridgeErrorHandler is enabled, this option is not in use. By default, the consumer will deal with exceptions, which will be logged at WARN or ERROR level and ignored.

 

ExceptionHandler

exchangePattern (consumer)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

blobMetadata (producer)

Set the blob metadata.

 

Map

blobPrefix (producer)

Set a prefix that can be used for listing the blobs.

 

String

closeStreamAfterWrite (producer)

Close the stream after write or keep it open, default is true.

true

boolean

operation (producer)

Blob service operation hint to the producer.

listBlobs

BlobServiceOperations

streamWriteSize (producer)

Set the size of the buffer for writing block and page blocks.

 

int

useFlatListing (producer)

Specify if the flat or hierarchical blob listing should be used.

true

boolean

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Required Azure Storage Blob Service component options

You must provide the containerOrBlob name and the credentials if the private blob needs to be accessed.

39.3. Usage

Expand
HeaderTypeDescription

CamelFileName

String

The file name for the downloaded blob content.

Expand
HeaderTypeDescription

CamelFileName

String

The file name for the downloaded blob content.

39.3.3. Azure Blob Service operations

Operations common to all block types

Expand
OperationDescription

getBlob

Get the content of the blob. You can restrict the output of this operation to a blob range.

deleteBlob

Delete the blob.

listBlobs

List the blobs.

Block blob operations

Expand
OperationDescription

updateBlockBlob

Put block blob content that either creates a new block blob or overwrites the existing block blob content.

uploadBlobBlocks

Upload block blob content, by first generating a sequence of blob blocks and then committing them to a blob. If you enable the message CommitBlockListLater property, you can execute the commit later with the commitBlobBlockList operation. You can later update individual block blobs.

commitBlobBlockList

Commit a sequence of blob blocks to the block list that you previously uploaded to the blob service (by using the updateBlockBlob operation with the message CommitBlockListLater property enabled).

getBlobBlockList

Get the block blob list.

Append blob operations

Expand
OperationDescription

createAppendBlob

Create an append block. By default, if the block already exists then it is not reset. Note that you can alternately create an append blob by enabling the message AppendBlobCreated property and using the updateAppendBlob operation.

updateAppendBlob

Append the new content to the blob. This operation also creates the blob if it does not already exist and if you enabled a message AppendBlobCreated property.

Page Block operations

Expand
OperationDescription

createPageBlob

Create a page block. By default, if the block already exists then it is not reset. Note that you can also create a page blob (and set its contents) by enabling a message PageBlobCreated property and by using the updatePageBlob operation.

updatePageBlob

Create a page block (unless you enable a message PageBlobCreated property and the identically named block already exists) and set the content of this blob.

resizePageBlob

Resize the page blob.

clearPageBlob

Clear the page blob.

getPageBlobRanges

Get the page blob page ranges.

39.3.4. Azure Blob Client configuration

If your Camel application is running behind a firewall or if you need more control over the Azure Blob Client configuration, you can create your own instance:

StorageCredentials credentials = new StorageCredentialsAccountAndKey(accountName, accessKey);
CloudBlob client = new CloudBlockBlob(URI.create("https://"
                    + accountName + ".blob.core.windows.net/" + containerName
                    + "/" + fileName), credentials);
registry.bind("azureBlobClient", client);
Copy to Clipboard Toggle word wrap

Refer to this instance in your Camel azure-blob component configuration:

from("azure-blob://" + accountName + "/" + containerName + "/" + fileName + "?azureBlobClient=#client")
.to("mock:result");
Copy to Clipboard Toggle word wrap

39.4. Dependencies

Maven users must add the following dependency to their pom.xml:

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-azure</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.19.0 or higher).

39.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • Azure Component

Chapter 40. Azure Storage Queue Service Component

Available as of Camel version 2.19

The Azure Queue component supports storing and retrieving the messages to/from Azure Storage Queue service.

Prerequisites

You must have a valid Windows Azure Storage account. More information is available at Azure Documentation Portal.

40.1. URI Format

azure-queue://accountName/queueName[?options]
Copy to Clipboard Toggle word wrap

The queue will be created if it does not already exist.
You can append query options to the URI in the following format: ?options=value&option2=value&…​

For example, to get a message content from the queue messageQueue in the camelazure storage account, use the following snippet:

from("azure-queue:camelazure/messageQueue").
to("file://queuedirectory");
Copy to Clipboard Toggle word wrap

40.2. URI Options

The Azure Storage Queue Service component has no options.

The Azure Storage Queue Service endpoint is configured using URI syntax:

azure-queue:containerAndQueueUri
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

40.2.1. Path Parameters (1 parameter)

Expand
NameDescriptionDefaultType

containerAndQueueUri

Required: Container Queue compact URI.

 

String

40.2.2. Query Parameters (10 parameters)

Expand
NameDescriptionDefaultType

azureQueueClient (common)

The queue service client.

 

CloudQueue

credentials (common)

Set the storage credentials, required in most cases

 

StorageCredentials

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler. This means any exceptions that occurred (for example, while the consumer was trying to pick up incoming messages) will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Note that if the option bridgeErrorHandler is enabled, 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

messageTimeToLive (producer)

Message Time To Live in seconds.

 

int

messageVisibilityDelay (producer)

Message Visibility Delay in seconds.

 

int

operation (producer)

Queue service operation hint to the producer.

listQueues

QueueServiceOperations

queuePrefix (producer)

Set a prefix which can be used for listing the queues.

 

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Required Azure Storage Queue Service component options

You must provide the containerAndQueue URI and the credentials.

40.3. Usage

40.3.1. Azure Queue Service operations

Expand
OperationDescription

listQueues

List the queues.

createQueue

Create the queue.

deleteQueue

Delete the queue.

addMessage

Add a message to the queue.

retrieveMessage

Retrieve a message from the queue.

peekMessage

View the message inside the queue, for example, to determine whether the message arrived at the correct queue.

updateMessage

Update the message in the queue.

deleteMessage

Delete the message in the queue.

40.3.2. Azure Queue Client configuration

If your Camel Application is running behind a firewall or if you need to have more control over the Azure Queue Client configuration, you can create your own instance:

StorageCredentials credentials = new StorageCredentialsAccountAndKey("camelazure", "thekey");

CloudQueue client = new CloudQueue("camelazure", credentials);

registry.bind("azureQueueClient", client);
Copy to Clipboard Toggle word wrap

and refer to it in your Camel azure-queue component configuration:

from("azure-queue:camelazure/messageQueue?azureQueueClient=#client")
.to("mock:result");
Copy to Clipboard Toggle word wrap

40.4. Dependencies

Maven users must add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-azure</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.19.0 or higher).

40.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • Azure Component

Chapter 41. Barcode DataFormat

Available as of Camel version 2.14

The barcode data format is based on the zxing library. The goal of this component is to create a barcode image from a String (marshal) and a String from a barcode image (unmarshal). You’re free to use all features that zxing offers.

41.1. Dependencies

To use the barcode data format in your camel routes you need to add the a dependency on camel-barcode which implements this data format.

If you use maven you could just add the following to your pom.xml, substituting the version number for the latest & greatest release (see the download page for the latest versions).

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-barcode</artifactId>
  <version>x.x.x</version>
</dependency>
Copy to Clipboard Toggle word wrap

41.2. Barcode Options

The Barcode dataformat supports 5 options which are listed below.

Expand
NameDefaultJava TypeDescription

width

 

Integer

Width of the barcode

height

 

Integer

Height of the barcode

imageType

 

String

Image type of the barcode such as png

barcodeFormat

 

String

Barcode format such as QR-Code

contentTypeHeader

false

Boolean

Whether the data format should set the Content-Type header with the type from the data format if the data format is capable of doing so. For example application/xml for data formats marshalling to XML, or application/json for data formats marshalling to JSon etc.

41.3. Using the Java DSL

First you have to initialize the barcode data fomat class. You can use the default constructor, or one of parameterized (see JavaDoc). The default values are:

Expand
ParameterDefault Value

image type (BarcodeImageType)

PNG

width

100 px

height

100 px

encoding

UTF-8

barcode format (BarcodeFormat)

QR-Code

// QR-Code default
DataFormat code = new BarcodeDataFormat();
Copy to Clipboard Toggle word wrap

If you want to use zxing hints, you can use the 'addToHintMap' method of your BarcodeDataFormat instance:

code.addToHintMap(DecodeHintType.TRY_HARDER, Boolean.true);
Copy to Clipboard Toggle word wrap

For possible hints, please consult the xzing documentation.

41.3.1. Marshalling

from("direct://code")
  .marshal(code)
  .to("file://barcode_out");
Copy to Clipboard Toggle word wrap

You can call the route from a test class with:

template.sendBody("direct://code", "This is a testmessage!");
Copy to Clipboard Toggle word wrap

You should find inside the 'barcode_out' folder this image:

image

41.3.2. Unmarshalling

The unmarshaller is generic. For unmarshalling you can use any BarcodeDataFormat instance. If you’ve two instances, one for (generating) QR-Code and one for PDF417, it doesn’t matter which one will be used.

from("file://barcode_in?noop=true")
  .unmarshal(code) // for unmarshalling, the instance doesn't matter
  .to("mock:out");
Copy to Clipboard Toggle word wrap

If you’ll paste the QR-Code image above into the 'barcode_in' folder, you should find ‘This is a testmessage!’ inside the mock. You can find the barcode data format as header variable:

Expand
NameTypeDescription

BarcodeFormat

String

Value of com.google.zxing.BarcodeFormat.

 

 

Chapter 42. Base64 DataFormat

Available as of Camel version 2.11

The Base64 data format is used for base64 encoding and decoding.

42.1. Options

The Base64 dataformat supports 4 options which are listed below.

Expand
NameDefaultJava TypeDescription

lineLength

76

Integer

To specific a maximum line length for the encoded data. By default 76 is used.

lineSeparator

 

String

The line separators to use. Uses new line characters (CRLF) by default.

urlSafe

false

Boolean

Instead of emitting '' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode operations. Decoding seamlessly handles both modes. Is by default false.

contentTypeHeader

false

Boolean

Whether the data format should set the Content-Type header with the type from the data format if the data format is capable of doing so. For example application/xml for data formats marshalling to XML, or application/json for data formats marshalling to JSon etc.

In Spring DSL, you configure the data format using this tag:

<camelContext>
    <dataFormats>
        <!-- for a newline character (\n), use the HTML entity notation coupled with the ASCII code. -->
        <base64 lineSeparator="&#10;" id="base64withNewLine" />
        <base64 lineLength="64" id="base64withLineLength64" />
    </dataFormats>
    ...
</camelContext>
Copy to Clipboard Toggle word wrap

Then you can use it later by its reference:

<route>
     <from uri="direct:startEncode" />
     <marshal ref="base64withLineLength64" />
     <to uri="mock:result" />
</route>
Copy to Clipboard Toggle word wrap

Most of the time, you won’t need to declare the data format if you use the default options. In that case, you can declare the data format inline as shown below.

42.2. Marshal

In this example we marshal the file content to base64 object.

from("file://data.bin")
    .marshal().base64()
    .to("jms://myqueue");
Copy to Clipboard Toggle word wrap

In Spring DSL:

 <from uri="file://data.bin">
 <marshal>
     <base64/>
 </marshal>
 <to uri="jms://myqueue"/>
Copy to Clipboard Toggle word wrap

42.3. Unmarshal

In this example we unmarshal the payload from the JMS queue to a byte[] object, before its processed by the newOrder processor.

from("jms://queue/order")
    .unmarshal().base64()
    .process("newOrder");
Copy to Clipboard Toggle word wrap

In Spring DSL:

 <from uri="jms://queue/order">
 <marshal>
     <base64/>
 </marshal>
 <to uri="bean:newOrder"/>
Copy to Clipboard Toggle word wrap

42.4. Dependencies

To use Base64 in your Camel routes you need to add a dependency on camel-base64 which implements this data format.

If you use Maven you can just add the following to your pom.xml:

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-base64</artifactId>
  <version>x.x.x</version>  <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

Chapter 43. Bean Component

Available as of Camel version 1.0

The bean: component binds beans to Camel message exchanges.

43.1. URI format

bean:beanName[?options]
Copy to Clipboard Toggle word wrap

Where beanID can be any string which is used to look up the bean in the Registry

43.2. Options

The Bean component has no options.

The Bean endpoint is configured using URI syntax:

bean:beanName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

43.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

beanName

Required Sets the name of the bean to invoke

 

String

43.2.2. Query Parameters (5 parameters):

Expand
NameDescriptionDefaultType

method (producer)

Sets the name of the method to invoke on the bean

 

String

cache (advanced)

If enabled, Camel will cache the result of the first Registry look-up. Cache can be enabled if the bean in the Registry is defined as a singleton scope.

false

boolean

multiParameterArray (advanced)

Deprecated How to treat the parameters which are passed from the message body; if it is true, the message body should be an array of parameters. Note: This option is used internally by Camel, and is not intended for end users to use. Deprecation note: This option is used internally by Camel, and is not intended for end users to use.

false

boolean

parameters (advanced)

Used for configuring additional properties on the bean

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

You can append query options to the URI in the following format, ?option=value&option=value&…​

43.3. Using

The object instance that is used to consume messages must be explicitly registered with the Registry. For example, if you are using Spring you must define the bean in the Spring configuration, spring.xml; or if you don’t use Spring, by registering the bean in JNDI.

Error formatting macro: snippet: java.lang.IndexOutOfBoundsException: Index: 20, Size: 20

Once an endpoint has been registered, you can build Camel routes that use it to process exchanges.

A bean: endpoint cannot be defined as the input to the route; i.e. you cannot consume from it, you can only route from some inbound message Endpoint to the bean endpoint as output. So consider using a direct: or queue: endpoint as the input.

You can use the createProxy() methods on ProxyHelper to create a proxy that will generate BeanExchanges and send them to any endpoint:

And the same route using Spring DSL:

<route>
   <from uri="direct:hello">
   <to uri="bean:bye"/>
</route>
Copy to Clipboard Toggle word wrap

43.4. Bean as endpoint

Camel also supports invoking Bean as an Endpoint. In the route below:

What happens is that when the exchange is routed to the myBean Camel will use the Bean Binding to invoke the bean.
The source for the bean is just a plain POJO:

Camel will use Bean Binding to invoke the sayHello method, by converting the Exchange’s In body to the String type and storing the output of the method on the Exchange Out body.

43.5. Java DSL bean syntax

Java DSL comes with syntactic sugar for the Bean component. Instead of specifying the bean explicitly as the endpoint (i.e. to("bean:beanName")) you can use the following syntax:

// Send message to the bean endpoint
// and invoke method resolved using Bean Binding.
from("direct:start").beanRef("beanName");

// Send message to the bean endpoint
// and invoke given method.
from("direct:start").beanRef("beanName", "methodName");
Copy to Clipboard Toggle word wrap

Instead of passing name of the reference to the bean (so that Camel will lookup for it in the registry), you can specify the bean itself:

// Send message to the given bean instance.
from("direct:start").bean(new ExampleBean());

// Explicit selection of bean method to be invoked.
from("direct:start").bean(new ExampleBean(), "methodName");

// Camel will create the instance of bean and cache it for you.
from("direct:start").bean(ExampleBean.class);
Copy to Clipboard Toggle word wrap

43.6. Bean Binding

How bean methods to be invoked are chosen (if they are not specified explicitly through the method parameter) and how parameter values are constructed from the Message are all defined by the Bean Binding mechanism which is used throughout all of the various Bean Integration mechanisms in Camel.

43.7. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • Class component
  • Bean Binding
  • Bean Integration

Chapter 44. BeanIO DataFormat

Available as of Camel version 2.10

The BeanIO Data Format uses BeanIO to handle flat payloads (such as XML, CSV, delimited, or fixed length formats).

BeanIO is configured using a mappings XML file where you define the mapping from the flat format to Objects (POJOs). This mapping file is mandatory to use.

44.1. Options

The BeanIO dataformat supports 9 options which are listed below.

Expand
NameDefaultJava TypeDescription

mapping

 

String

The BeanIO mapping file. Is by default loaded from the classpath. You can prefix with file:, http:, or classpath: to denote from where to load the mapping file.

streamName

 

String

The name of the stream to use.

ignoreUnidentifiedRecords

false

Boolean

Whether to ignore unidentified records.

ignoreUnexpectedRecords

false

Boolean

Whether to ignore unexpected records.

ignoreInvalidRecords

false

Boolean

Whether to ignore invalid records.

encoding

 

String

The charset to use. Is by default the JVM platform default charset.

beanReaderErrorHandlerType

 

String

To use a custom org.apache.camel.dataformat.beanio.BeanIOErrorHandler as error handler while parsing. Configure the fully qualified class name of the error handler. Notice the options ignoreUnidentifiedRecords, ignoreUnexpectedRecords, and ignoreInvalidRecords may not be in use when you use a custom error handler.

unmarshalSingleObject

false

Boolean

This options controls whether to unmarshal as a list of objects or as a single object only. The former is the default mode, and the latter is only intended in special use-cases where beanio maps the Camel message to a single POJO bean.

contentTypeHeader

false

Boolean

Whether the data format should set the Content-Type header with the type from the data format if the data format is capable of doing so. For example application/xml for data formats marshalling to XML, or application/json for data formats marshalling to JSon etc.

44.2. Usage

An example of a mapping file is here.

44.2.1. Using Java DSL

To use the BeanIODataFormat you need to configure the data format with the mapping file, as well the name of the stream.
In Java DSL this can be done as shown below. The streamName is "employeeFile".

Then we have two routes. The first route is for transforming CSV data into a List<Employee> Java objects. Which we then split, so the mock endpoint
receives a message for each row.

The 2nd route is for the reverse operation, to transform a List<Employee> into a stream of CSV data.

The CSV data could for example be as below:

44.2.2. Using XML DSL

To use the BeanIO data format in XML, you need to configure it using the <beanio> XML tag as shown below. The routes is similar to the example above.

44.3. Dependencies

To use BeanIO in your Camel routes you need to add a dependency on camel-beanio which implements this data format.

If you use Maven you can just add the following to your pom.xml, substituting the version number for the latest & greatest release (see the download page for the latest versions).

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-beanio</artifactId>
  <version>2.10.0</version>
</dependency>
Copy to Clipboard Toggle word wrap

Chapter 45. Beanstalk Component

Available as of Camel version 2.15

camel-beanstalk project provides a Camel component for job retrieval and post-processing of Beanstalk jobs.

You can find the detailed explanation of Beanstalk job lifecycle at Beanstalk protocol.

45.1. Dependencies

Maven users need to add the following dependency to their pom.xml

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-beanstalk</artifactId>
  <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.15.0 or higher).

45.2. URI format

beanstalk://[host[:port]][/tube][?options]
Copy to Clipboard Toggle word wrap

You may omit either port or both host and port: for the Beanstalk defaults to be used (“localhost” and 11300). If you omit tube, Beanstalk component will use the tube with name “default”.

When listening, you may probably want to watch for jobs from several tubes. Just separate them with plus sign, e.g.

beanstalk://localhost:11300/tube1+tube2
Copy to Clipboard Toggle word wrap

Tube name will be URL decoded, so if your tube names include special characters like + or ?, you need to URL-encode them appropriately, or use the RAW syntax, see more details here.

By the way, you cannot specify several tubes when you are writing jobs into Beanstalk.

45.3. Beanstalk options

The Beanstalk component supports 2 options which are listed below.

Expand
NameDescriptionDefaultType

connectionSettings Factory (common)

Custom ConnectionSettingsFactory. Specify which ConnectionSettingsFactory to use to make connections to Beanstalkd. Especially useful for unit testing without beanstalkd daemon (you can mock ConnectionSettings)

 

ConnectionSettings Factory

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Beanstalk endpoint is configured using URI syntax:

beanstalk:connectionSettings
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

45.3.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

connectionSettings

Connection settings host:port/tube

 

String

45.3.2. Query Parameters (26 parameters):

Expand
NameDescriptionDefaultType

command (common)

put means to put the job into Beanstalk. Job body is specified in the Camel message body. Job ID will be returned in beanstalk.jobId message header. delete, release, touch or bury expect Job ID in the message header beanstalk.jobId. Result of the operation is returned in beanstalk.result message header kick expects the number of jobs to kick in the message body and returns the number of jobs actually kicked out in the message header beanstalk.result.

 

BeanstalkCommand

jobDelay (common)

Job delay in seconds.

0

int

jobPriority (common)

Job priority. (0 is the highest, see Beanstalk protocol)

1000

long

jobTimeToRun (common)

Job time to run in seconds. (when 0, the beanstalkd daemon raises it to 1 automatically, see Beanstalk protocol)

60

int

awaitJob (consumer)

Whether to wait for job to complete before ack the job from beanstalk

true

boolean

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

onFailure (consumer)

Command to use when processing failed.

 

BeanstalkCommand

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

useBlockIO (consumer)

Whether to use blockIO.

true

boolean

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

pollStrategy (consumer)

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

 

PollingConsumerPoll Strategy

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

 

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

 

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

 

int

delay (scheduler)

Milliseconds before the next poll. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

initialDelay (scheduler)

Milliseconds before the first poll starts. You can also specify time values using units, such as 60s (60 seconds), 5m30s (5 minutes and 30 seconds), and 1h (1 hour).

1000

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

 

ScheduledExecutor Service

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz2 component

none

ScheduledPollConsumer Scheduler

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz2, Spring based scheduler.

 

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

Producer behavior is affected by the command parameter which tells what to do with the job, it can be

The consumer may delete the job immediately after reserving it or wait until Camel routes process it. While the first scenario is more like a “message queue”, the second is similar to “job queue”. This behavior is controlled by consumer.awaitJob parameter, which equals true by default (following Beanstalkd nature).

When synchronous, the consumer calls delete on successful job completion and calls bury on failure. You can choose which command to execute in the case of failure by specifying consumer.onFailure parameter in the URI. It can take values of burydelete or release.

There is a boolean parameter consumer.useBlockIO which corresponds to the same parameter in JavaBeanstalkClient library. By default it is true.

Be careful when specifying release, as the failed job will immediately become available in the same tube and your consumer will try to acquire it again. You can release and specify jobDelay though.

The beanstalk consumer is a Scheduled Polling Consumer which means there is more options you can configure, such as how frequent the consumer should poll. For more details see Polling Consumer.

45.4. Consumer Headers

The consumer stores a number of job headers in the Exchange message:

Expand
PropertyTypeDescription

beanstalk.jobId

long

Job ID

beanstalk.tube

string

the name of the tube that contains this job

beanstalk.state

string

“ready” or “delayed” or “reserved” or “buried” (must be “reserved”)

beanstalk.priority

long

the priority value set

beanstalk.age

int

the time in seconds since the put command that created this job

beanstalk.time-left

int

the number of seconds left until the server puts this job into the ready queue

beanstalk.timeouts

int

the number of times this job has timed out during a reservation

beanstalk.releases

int

the number of times a client has released this job from a reservation

beanstalk.buries

int

the number of times this job has been buried

beanstalk.kicks

int

the number of times this job has been kicked

45.5. Examples

This Camel component lets you both request the jobs for processing and supply them to Beanstalkd daemon. Our simple demo routes may look like

from("beanstalk:testTube").
   log("Processing job #${property.beanstalk.jobId} with body ${in.body}").
   process(new Processor() {
     @Override
     public void process(Exchange exchange) {
       // try to make integer value out of body
       exchange.getIn().setBody( Integer.valueOf(exchange.getIn().getBody(classOf[String])) );
     }
   }).
   log("Parsed job #${property.beanstalk.jobId} to body ${in.body}");
Copy to Clipboard Toggle word wrap
from("timer:dig?period=30seconds").
   setBody(constant(10)).log("Kick ${in.body} buried/delayed tasks").
   to("beanstalk:testTube?command=kick");
Copy to Clipboard Toggle word wrap

In the first route we are listening for new jobs in tube “testTube”. When they are arriving, we are trying to parse integer value from the message body. If done successful, we log it and this successful exchange completion makes Camel component to delete this job from Beanstalk automatically. Contrary, when we cannot parse the job data, the exchange failed and the Camel component buries it by default, so that it can be processed later or probably we are going to inspect failed jobs manually.

So the second route periodically requests Beanstalk to kick 10 jobs out of buried and/or delayed state to the normal queue.

 

45.6. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started

Chapter 46. Bean Validator Component

Available as of Camel version 2.3

The Validator component performs bean validation of the message body using the Java Bean Validation API (JSR 303). Camel uses the reference implementation, which is Hibernate Validator.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-bean-validator</artifactId>
    <version>x.y.z</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

46.1. URI format

bean-validator:label[?options]
Copy to Clipboard Toggle word wrap

or

bean-validator://label[?options]
Copy to Clipboard Toggle word wrap

Where label is an arbitrary text value describing the endpoint.
You can append query options to the URI in the following format, ?option=value&option=value&…​

46.2. URI Options

The Bean Validator component has no options.

The Bean Validator endpoint is configured using URI syntax:

bean-validator:label
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

46.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

label

Required Where label is an arbitrary text value describing the endpoint

 

String

46.2.2. Query Parameters (6 parameters):

Expand
NameDescriptionDefaultType

constraintValidatorFactory (producer)

To use a custom ConstraintValidatorFactory

 

ConstraintValidator Factory

group (producer)

To use a custom validation group

javax.validation.groups.Default

String

messageInterpolator (producer)

To use a custom MessageInterpolator

 

MessageInterpolator

traversableResolver (producer)

To use a custom TraversableResolver

 

TraversableResolver

validationProviderResolver (producer)

To use a a custom ValidationProviderResolver

 

ValidationProvider Resolver

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

46.3. OSGi deployment

To use Hibernate Validator in the OSGi environment use dedicated ValidationProviderResolver implementation, just as org.apache.camel.component.bean.validator.HibernateValidationProviderResolver. The snippet below demonstrates this approach. Keep in mind that you can use HibernateValidationProviderResolver starting from the Camel 2.13.0.

Using HibernateValidationProviderResolver

from("direct:test").
  to("bean-validator://ValidationProviderResolverTest?validationProviderResolver=#myValidationProviderResolver");

...

<bean id="myValidationProviderResolver" class="org.apache.camel.component.bean.validator.HibernateValidationProviderResolver"/>
Copy to Clipboard Toggle word wrap

If no custom ValidationProviderResolver is defined and the validator component has been deployed into the OSGi environment, the HibernateValidationProviderResolver will be automatically used.

46.4. Example

Assumed we have a java bean with the following annotations

Car.java

public class Car {

    @NotNull
    private String manufacturer;

    @NotNull
    @Size(min = 5, max = 14, groups = OptionalChecks.class)
    private String licensePlate;

    // getter and setter
}
Copy to Clipboard Toggle word wrap

and an interface definition for our custom validation group

OptionalChecks.java

public interface OptionalChecks {
}
Copy to Clipboard Toggle word wrap

with the following Camel route, only the @NotNull constraints on the attributes manufacturer and licensePlate will be validated (Camel uses the default group javax.validation.groups.Default).

from("direct:start")
.to("bean-validator://x")
.to("mock:end")
Copy to Clipboard Toggle word wrap

If you want to check the constraints from the group OptionalChecks, you have to define the route like this

from("direct:start")
.to("bean-validator://x?group=OptionalChecks")
.to("mock:end")
Copy to Clipboard Toggle word wrap

If you want to check the constraints from both groups, you have to define a new interface first

AllChecks.java

@GroupSequence({Default.class, OptionalChecks.class})
public interface AllChecks {
}
Copy to Clipboard Toggle word wrap

and then your route definition should looks like this

from("direct:start")
.to("bean-validator://x?group=AllChecks")
.to("mock:end")
Copy to Clipboard Toggle word wrap

And if you have to provide your own message interpolator, traversable resolver and constraint validator factory, you have to write a route like this

<bean id="myMessageInterpolator" class="my.ConstraintValidatorFactory" />
<bean id="myTraversableResolver" class="my.TraversableResolver" />
<bean id="myConstraintValidatorFactory" class="my.ConstraintValidatorFactory" />

from("direct:start")
.to("bean-validator://x?group=AllChecks&messageInterpolator=#myMessageInterpolator
&traversableResolver=#myTraversableResolver&constraintValidatorFactory=#myConstraintValidatorFactory")
.to("mock:end")
Copy to Clipboard Toggle word wrap

It’s also possible to describe your constraints as XML and not as Java annotations. In this case, you have to provide the file META-INF/validation.xml which could looks like this

validation.xml

<?xml version="1.0" encoding="UTF-8"?>
<validation-config
    xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration">
    <default-provider>org.hibernate.validator.HibernateValidator</default-provider>
    <message-interpolator>org.hibernate.validator.engine.ResourceBundleMessageInterpolator</message-interpolator>
    <traversable-resolver>org.hibernate.validator.engine.resolver.DefaultTraversableResolver</traversable-resolver>
    <constraint-validator-factory>org.hibernate.validator.engine.ConstraintValidatorFactoryImpl</constraint-validator-factory>

    <constraint-mapping>/constraints-car.xml</constraint-mapping>
</validation-config>
Copy to Clipboard Toggle word wrap

and the constraints-car.xml file

constraints-car.xml

<?xml version="1.0" encoding="UTF-8"?>
<constraint-mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd"
    xmlns="http://jboss.org/xml/ns/javax/validation/mapping">
    <default-package>org.apache.camel.component.bean.validator</default-package>

    <bean class="CarWithoutAnnotations" ignore-annotations="true">
        <field name="manufacturer">
            <constraint annotation="javax.validation.constraints.NotNull" />
        </field>

        <field name="licensePlate">
            <constraint annotation="javax.validation.constraints.NotNull" />

            <constraint annotation="javax.validation.constraints.Size">
                <groups>
                    <value>org.apache.camel.component.bean.validator.OptionalChecks</value>
                </groups>
                <element name="min">5</element>
                <element name="max">14</element>
            </constraint>
        </field>
    </bean>
</constraint-mappings>
Copy to Clipboard Toggle word wrap

Here is the XML syntax for the example route definition where OrderedChecks can be https://github.com/apache/camel/blob/master/components/camel-bean-validator/src/test/java/org/apache/camel/component/bean/validator/OrderedChecks.java

Note that the body should include an instance of a class to validate.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
        <route>
            <from uri="direct:start"/>
            <to uri="bean-validator://x?group=org.apache.camel.component.bean.validator.OrderedChecks"/>
        </route>
    </camelContext>
</beans>
Copy to Clipboard Toggle word wrap

46.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started

Chapter 47. Binding Component (deprecated)

Available as of Camel version 2.11

In Camel terms a binding is a way of wrapping an Endpoint in a contract; such as a Data Format, a Content Enricher or validation step. Bindings are completely optional and you can choose to use them on any camel endpoint.

Bindings are inspired by the work of SwitchYard project adding service contracts to various technologies like Camel and many others. But rather than the SwitchYard approach of wrapping Camel in SCA, Camel Bindings provide a way of wrapping Camel endpoints with contracts inside the Camel framework itself; so you can use them easily inside any Camel route.

47.1. Options

The Binding component has no options.

The Binding endpoint is configured using URI syntax:

binding:bindingName:delegateUri
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

47.1.1. Path Parameters (2 parameters):

Expand
NameDescriptionDefaultType

bindingName

Required Name of the binding to lookup in the Camel registry.

 

String

delegateUri

Required Uri of the delegate endpoint.

 

String

47.1.2. Query Parameters (4 parameters):

Expand
NameDescriptionDefaultType

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN/ERROR level and ignored.

false

boolean

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options is not in use. By default the consumer will deal with exceptions, that will be logged at WARN/ERROR level and ignored.

 

ExceptionHandler

exchangePattern (consumer)

Sets the default exchange pattern when creating an exchange.

 

ExchangePattern

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

47.2. Using Bindings

A Binding is currently a bean which defines the contract (though we’ll hopefully add bindings to the Camel DSL).

There are a few approaches to defining a bound endpoint (i.e. an endpoint bound with a Binding).

47.3. Using the binding URI

You can prefix any endpoint URI with binding:nameOfBinding: where nameOfBinding is the name of the Binding bean in your registry.

from("binding:jaxb:activemq:myQueue").to("binding:jaxb:activemq:anotherQueue")
Copy to Clipboard Toggle word wrap

Here we are using the "jaxb" binding which may, for example, use the JAXB Data Format to marshal and unmarshal messages.

47.4. Using a BindingComponent

There is a Component called BindingComponent which can be configured in your Registry by dependency injection which allows the creation of endpoints which are already bound to some binding.

For example if you registered a new component called "jsonmq" in your registry using code like this

JacksonDataFormat format = new JacksonDataFormat(MyBean.class);
context.bind("jsonmq", new BindingComponent(new DataFormatBinding(format), "activemq:foo."));
Copy to Clipboard Toggle word wrap

Then you could use the endpoint as if it were any other endpoint.

from("jsonmq:myQueue").to("jsonmq:anotherQueue")
Copy to Clipboard Toggle word wrap

which would be using the queueus "foo.myQueue" and "foo.anotherQueue" and would use the given Jackson Data Format to marshal on and off the queue.

47.5. When to use Bindings

If you only use an endpoint once in a single route; a binding may actually be more complex and more work than just using the 'raw' endpoint directly and using explicit marshalling and validation in the camel route as normal.

However bindings can help when you are composing many routes together; or using a single route as a 'template' that is configured input and output endpoints; bindings then provide a nice way to wrap up a contract and endpoint together.

Another good use case for bindings is when you are using many endpoints which use the same binding; rather than always having to mention a specific data format or validation rule, you can just use the BindingComponent to wrap the endpoints in the binding of your choice.

So bindings are a composition tool really; only use them when they make sense - the extra complexity may not be worth it unless you have lots of routes or endpoints.

Chapter 48. Bindy DataFormat

Available as of Camel version 2.0

The goal of this component is to allow the parsing/binding of non-structured data (or to be more precise non-XML data)
to/from Java Beans that have binding mappings defined with annotations. Using Bindy, you can bind data from sources such as :

  • CSV records,
  • Fixed-length records,
  • FIX messages,
  • or almost any other non-structured data

to one or many Plain Old Java Object (POJO). Bindy converts the data according to the type of the java property. POJOs can be linked together with one-to-many relationships available in some cases. Moreover, for data type like Date, Double, Float, Integer, Short, Long and BigDecimal, you can provide the pattern to apply during the formatting of the property.

For the BigDecimal numbers, you can also define the precision and the decimal or grouping separators.

Expand
TypeFormat TypePattern exampleLink

Date

DateFormat

dd-MM-yyyy

http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html

Decimal*

Decimalformat

..##

http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html

Decimal* = Double, Integer, Float, Short, Long

*Format supported*
Copy to Clipboard Toggle word wrap

This first release only support comma separated values fields and key value pair fields (e.g. : FIX messages).

To work with camel-bindy, you must first define your model in a package (e.g. com.acme.model) and for each model class (e.g. Order, Client, Instrument, …​) add the required annotations (described hereafter) to the Class or field.

*Multiple models*
Copy to Clipboard Toggle word wrap

If you use multiple models, each model has to be placed in it’s own package to prevent unpredictable results.

From Camel 2.16 onwards this is no longer the case, as you can safely have multiple models in the same package, as you configure bindy using class names instead of package names now.

48.1. Options

The Bindy dataformat supports 5 options which are listed below.

Expand
NameDefaultJava TypeDescription

type

 

BindyType

Whether to use csv, fixed or key value pairs mode. The default value is either Csv or KeyValue depending on chosen dataformat.

classType

 

String

Name of model class to use.

locale

 

String

To configure a default locale to use, such as us for united states. To use the JVM platform default locale then use the name default

unwrapSingleInstance

true

Boolean

When unmarshalling should a single instance be unwrapped and returned instead of wrapped in a java.util.List.

contentTypeHeader

false

Boolean

Whether the data format should set the Content-Type header with the type from the data format if the data format is capable of doing so. For example application/xml for data formats marshalling to XML, or application/json for data formats marshalling to JSon etc.

48.2. Annotations

The annotations created allow to map different concept of your model to the POJO like :

  • Type of record (csv, key value pair (e.g. FIX message), fixed length …​),
  • Link (to link object in another object),
  • DataField and their properties (int, type, …​),
  • KeyValuePairField (for key = value format like we have in FIX financial messages),
  • Section (to identify header, body and footer section),
  • OneToMany,
  • BindyConverter (since 2.18.0),
  • FormatFactories (since 2.18.0)

This section will describe them :

48.3. 1. CsvRecord

The CsvRecord annotation is used to identified the root class of the model. It represents a record = a line of a CSV file and can be linked to several children model classes.

Expand
Annotation nameRecord typeLevel

CsvRecord

csv

Class

Expand
Parameter nametypeInfo

separator

string

mandatory - can be ',' or ';' or 'anything'. This value is interpreted as a regular expression. If you want to use a sign which has a special meaning in regular expressions, e.g. the '|' sign, than you have to mask it, like '|'

skipFirstLine

boolean

optional - default value = false - allow to skip the first line of the CSV file

crlf

string

optional - possible values = WINDOWS,UNIX,MAC, or custom; default value. WINDOWS - allow to define the carriage return character to use. If you specify a value other than the three listed before, the value you enter (custom) will be used as the CRLF character(s)

generateHeaderColumns

boolean

optional - default value = false - uses to generate the header columns of the CSV generates

autospanLine

boolean

Camel 2.13/2.12.2: optional - default value = false - if enabled then the last column is auto spanned to end of line, for example if its a comment, etc this allows the line to contain all characters, also the delimiter char.

isOrdered

boolean

optional - default value = false - allow to change the order of the fields when CSV is generated

quote

String

Camel 2.8.3/2.9: option - allow to specify a quote character of the fields when CSV is generated. This annotation is associated to the root class of the model and must be declared one time.

quoting

boolean

*Camel 2.11:*optional - default value = false - Indicate if the values (and headers) must be quoted when marshaling when CSV is generated.

endWithLineBreak

boolean

Camel 2.21: optional - default value = true - Indicate if the CSV generated file should end with a line break.

case 1 : separator = ','

The separator used to segregate the fields in the CSV record is ',' :

10, J, Pauline, M, XD12345678, Fortis Dynamic 15/15, 2500,
USD,08-01-2009
Copy to Clipboard Toggle word wrap
@CsvRecord( separator = "," )
public Class Order {

}
Copy to Clipboard Toggle word wrap

case 2 : separator = ';'

Compare to the previous case, the separator here is ';' instead of ',' :

10; J; Pauline; M; XD12345678; Fortis Dynamic 15/15; 2500; USD; 08-01-2009

@CsvRecord( separator = ";" )
public Class Order {

}
Copy to Clipboard Toggle word wrap

case 3 : separator = '|'

Compare to the previous case, the separator here is '|' instead of ';' :

10| J| Pauline| M| XD12345678| Fortis Dynamic 15/15| 2500| USD|
08-01-2009
Copy to Clipboard Toggle word wrap
@CsvRecord( separator = "\\|" )
public Class Order {

}
Copy to Clipboard Toggle word wrap

case 4 : separator = '\",\"'

Applies for Camel 2.8.2 or older

When the field to be parsed of the CSV record contains ',' or ';' which is also used as separator, we whould find another strategy
to tell camel bindy how to handle this case. To define the field containing the data with a comma, you will use simple or double quotes
as delimiter (e.g : '10', 'Street 10, NY', 'USA' or "10", "Street 10, NY", "USA").
Remark : In this case, the first and last character of the line which are a simple or double quotes will removed by bindy

"10","J","Pauline"," M","XD12345678","Fortis Dynamic 15,15"
2500","USD","08-01-2009"
Copy to Clipboard Toggle word wrap
@CsvRecord( separator = "\",\"" )
public Class Order {

}
Copy to Clipboard Toggle word wrap

From Camel 2.8.3/2.9 or never bindy will automatic detect if the record is enclosed with either single or double quotes and automatic remove those quotes when unmarshalling from CSV to Object. Therefore do not include the quotes in the separator, but simple do as below:

"10","J","Pauline"," M","XD12345678","Fortis Dynamic 15,15"
2500","USD","08-01-2009"
Copy to Clipboard Toggle word wrap
@CsvRecord( separator = "," )
public Class Order {

}
Copy to Clipboard Toggle word wrap

Notice that if you want to marshal from Object to CSV and use quotes, then you need to specify which quote character to use, using the quote attribute on the @CsvRecord as shown below:

@CsvRecord( separator = ",", quote = "\"" )
public Class Order {

}
Copy to Clipboard Toggle word wrap

case 5 : separator & skipfirstline

The feature is interesting when the client wants to have in the first line of the file, the name of the data fields :

order id, client id, first name, last name, isin code, instrument name, quantity, currency, date

To inform bindy that this first line must be skipped during the parsing process, then we use the attribute :

@CsvRecord(separator = ",", skipFirstLine = true)
public Class Order {

}
Copy to Clipboard Toggle word wrap

case 6 : generateHeaderColumns

To add at the first line of the CSV generated, the attribute generateHeaderColumns must be set to true in the annotation like this :

@CsvRecord( generateHeaderColumns = true )
public Class Order {

}
Copy to Clipboard Toggle word wrap

As a result, Bindy during the unmarshaling process will generate CSV like this :

order id, client id, first name, last name, isin code, instrument name, quantity, currency, date

10, J, Pauline, M, XD12345678, Fortis Dynamic 15/15, 2500, USD,08-01-2009
Copy to Clipboard Toggle word wrap

case 7 : carriage return

If the platform where camel-bindy will run is not Windows but Macintosh or Unix, than you can change the crlf property like this. Three values are available : WINDOWS, UNIX or MAC

@CsvRecord(separator = ",", crlf="MAC")
public Class Order {

}
Copy to Clipboard Toggle word wrap

Additionally, if for some reason you need to add a different line ending character, you can opt to specify it using the crlf parameter. In the following example, we can end the line with a comma followed by the newline character:

@CsvRecord(separator = ",", crlf=",\n")
public Class Order {

}
Copy to Clipboard Toggle word wrap

case 8 : isOrdered

Sometimes, the order to follow during the creation of the CSV record from the model is different from the order used during the parsing. Then, in this case, we can use the attribute isOrdered = true to indicate this in combination with attribute 'position' of the DataField annotation.

@CsvRecord(isOrdered = true)
public Class Order {

   @DataField(pos = 1, position = 11)
   private int orderNr;

   @DataField(pos = 2, position = 10)
   private String clientNr;

}
Copy to Clipboard Toggle word wrap

Remark : pos is used to parse the file, stream while positions is used to generate the CSV

48.5. 3. DataField

The DataField annotation defines the property of the field. Each datafield is identified by its position in the record, a type (string, int, date, …​) and optionally of a pattern

Expand
Annotation nameRecord typeLevel

DataField

all

Property

Expand
Parameter nametypeInfo

pos

int

mandatory - The input position of the field. digit number starting from 1 to …​ - See the position parameter.

pattern

string

optional - default value = "" - will be used to format Decimal, Date,

length

int

optional - represents the length of the field for fixed length format

precision

int

optional - represents the precision to be used when the Decimal number will be formatted/parsed

pattern

string

optional - default value = "" - is used by the Java formatter (SimpleDateFormat by example) to format/validate data. If using pattern, then setting locale on bindy data format is recommended. Either set to a known locale such as "us" or use "default" to use platform default locale. Notice that "default" requires Camel 2.14/2.13.3/2.12.5.

position

int

optional - must be used when the position of the field in the CSV generated (output message) must be different compare to input position (pos). See the pos parameter.

required

boolean

optional - default value = "false"

trim

boolean

optional - default value = "false"

defaultValue

string

Camel 2.10: optional - default value = "" - defines the field’s default value when the respective CSV field is empty/not available

impliedDecimalSeparator

boolean

Camel 2.11: optional - default value = "false" - Indicates if there is a decimal point implied at a specified location

lengthPos

int

Camel 2.11: optional - can be used to identify a data field in a fixed-length record that defines the fixed length for this field

align

string

optional - default value = "R" - Align the text to the right or left within a fixed-length field. Use values 'R' or 'L'

delimiter

string

Camel 2.11: optional - can be used to demarcate the end of a variable-length field within a fixed-length record

case 1 : pos

This parameter/attribute represents the position of the field in the csv record

Position

@CsvRecord(separator = ",")
public class Order {

    @DataField(pos = 1)
    private int orderNr;

    @DataField(pos = 5)
    private String isinCode;

}
Copy to Clipboard Toggle word wrap

As you can see in this example the position starts at '1' but continues at '5' in the class Order. The numbers from '2' to '4' are defined in the class Client (see here after).

Position continues in another model class

public class Client {

    @DataField(pos = 2)
    private String clientNr;

    @DataField(pos = 3)
    private String firstName;

    @DataField(pos = 4)
    private String lastName;
}
Copy to Clipboard Toggle word wrap

case 2 : pattern

The pattern allows to enrich or validates the format of your data

Pattern

@CsvRecord(separator = ",")
public class Order {

    @DataField(pos = 1)
    private int orderNr;

    @DataField(pos = 5)
    private String isinCode;

    @DataField(name = "Name", pos = 6)
    private String instrumentName;

    @DataField(pos = 7, precision = 2)
    private BigDecimal amount;

    @DataField(pos = 8)
    private String currency;

    // pattern used during parsing or when the date is created
    @DataField(pos = 9, pattern = "dd-MM-yyyy")
    private Date orderDate;
}
Copy to Clipboard Toggle word wrap

case 3 : precision

The precision is helpful when you want to define the decimal part of your number

Precision

@CsvRecord(separator = ",")
public class Order {

    @DataField(pos = 1)
    private int orderNr;

    @Link
    private Client client;

    @DataField(pos = 5)
    private String isinCode;

    @DataField(name = "Name", pos = 6)
    private String instrumentName;

    @DataField(pos = 7, precision = 2)
    private BigDecimal amount;

    @DataField(pos = 8)
    private String currency;

    @DataField(pos = 9, pattern = "dd-MM-yyyy")
    private Date orderDate;
}
Copy to Clipboard Toggle word wrap

case 4 : Position is different in output

The position attribute will inform bindy how to place the field in the CSV record generated. By default, the position used corresponds to the position defined with the attribute 'pos'. If the position is different (that means that we have an asymetric processus comparing marshaling from unmarshaling) than we can use 'position' to indicate this.

Here is an example

Position is different in output

@CsvRecord(separator = ",", isOrdered = true)
public class Order {

    // Positions of the fields start from 1 and not from 0

    @DataField(pos = 1, position = 11)
    private int orderNr;

    @DataField(pos = 2, position = 10)
    private String clientNr;

    @DataField(pos = 3, position = 9)
    private String firstName;

    @DataField(pos = 4, position = 8)
    private String lastName;

    @DataField(pos = 5, position = 7)
    private String instrumentCode;

    @DataField(pos = 6, position = 6)
    private String instrumentNumber;
}
Copy to Clipboard Toggle word wrap

This attribute of the annotation @DataField must be used in combination with attribute isOrdered = true of the annotation @CsvRecord

case 5 : required

If a field is mandatory, simply use the attribute 'required' setted to true

Required

@CsvRecord(separator = ",")
public class Order {

    @DataField(pos = 1)
    private int orderNr;

    @DataField(pos = 2, required = true)
    private String clientNr;

    @DataField(pos = 3, required = true)
    private String firstName;

    @DataField(pos = 4, required = true)
    private String lastName;
}
Copy to Clipboard Toggle word wrap

If this field is not present in the record, than an error will be raised by the parser with the following information :

Some fields are missing (optional or mandatory), line :

case 6 : trim

If a field has leading and/or trailing spaces which should be removed before they are processed, simply use the attribute 'trim' setted to true

Trim

@CsvRecord(separator = ",")
public class Order {

    @DataField(pos = 1, trim = true)
    private int orderNr;

    @DataField(pos = 2, trim = true)
    private Integer clientNr;

    @DataField(pos = 3, required = true)
    private String firstName;

    @DataField(pos = 4)
    private String lastName;
}
Copy to Clipboard Toggle word wrap

case 7 : defaultValue

If a field is not defined then uses the value indicated by the defaultValue attribute

Default value

@CsvRecord(separator = ",")
public class Order {

    @DataField(pos = 1)
    private int orderNr;

    @DataField(pos = 2)
    private Integer clientNr;

    @DataField(pos = 3, required = true)
    private String firstName;

    @DataField(pos = 4, defaultValue = "Barin")
    private String lastName;
}
Copy to Clipboard Toggle word wrap

This attribute is only applicable to optional fields.

48.6. 4. FixedLengthRecord

The FixedLengthRecord annotation is used to identified the root class of the model. It represents a record = a line of a file/message containing data fixed length formatted and can be linked to several children model classes. This format is a bit particular beause data of a field can be aligned to the right or to the left.
When the size of the data does not fill completely the length of the field, we can then add 'padd' characters.

Expand
Annotation nameRecord typeLevel

FixedLengthRecord

fixed

Class

Expand
Parameter nametypeInfo

crlf

string

optional - possible values = WINDOWS,UNIX,MAC, or custom; default value. WINDOWS - allow to define the carriage return character to use. If you specify a value other than the three listed before, the value you enter (custom) will be used as the CRLF character(s). This option is used only during marshalling, whereas unmarshalling uses system default JDK provided line delimiter unless eol is customized

eol

string

optional - default="" which is empty string. Character to be used to process considering end of line after each record while unmarshalling (optional - default = "" which help default JDK provided line delimiter to be used unless any other line delimiter provided). This option is used only during unmarshalling, where marshalling uses system default provided line delimiter as "WINDOWS" unless any other value is provided

paddingChar

char

mandatory - default value = ' '

length

int

mandatory = size of the fixed length record

hasHeader

boolean

Camel 2.11 - optional - Indicates that the record(s) of this type may be preceded by a single header record at the beginning of the file / stream

hasFooter

boolean

Camel 2.11 - optional - Indicates that the record(s) of this type may be followed by a single footer record at the end of the file / stream

skipHeader

boolean

Camel 2.11 - optional - Configures the data format to skip marshalling / unmarshalling of the header record. Configure this parameter on the primary record (e.g., not the header or footer).

skipFooter

boolean

Camel 2.11 - optional - Configures the data format to skip marshalling / unmarshalling of the footer record Configure this parameter on the primary record (e.g., not the header or footer)..

isHeader

boolean

Camel 2.11 - optional - Identifies this FixedLengthRecord as a header record

isFooter

boolean

Camel 2.11 - optional - Identifies this FixedLengthRecords as a footer record

ignoreTrailingChars

boolean

Camel 2.11.1 - optional - Indicates that characters beyond the last mapped filed can be ignored when unmarshalling / parsing. This annotation is associated to the root class of the model and must be declared one time.

The hasHeader/hasFooter parameters are mutually exclusive with isHeader/isFooter. A record may not be both a header/footer and a primary fixed-length record.

case 1 : Simple fixed length record

This simple example shows how to design the model to parse/format a fixed message

10A9PaulineMISINXD12345678BUYShare2500.45USD01-08-2009
Copy to Clipboard Toggle word wrap

Fixed-simple

@FixedLengthRecord(length=54, paddingChar=' ')
public static class Order {

    @DataField(pos = 1, length=2)
    private int orderNr;

    @DataField(pos = 3, length=2)
    private String clientNr;

    @DataField(pos = 5, length=7)
    private String firstName;

    @DataField(pos = 12, length=1, align="L")
    private String lastName;

    @DataField(pos = 13, length=4)
    private String instrumentCode;

    @DataField(pos = 17, length=10)
    private String instrumentNumber;

    @DataField(pos = 27, length=3)
    private String orderType;

    @DataField(pos = 30, length=5)
    private String instrumentType;

    @DataField(pos = 35, precision = 2, length=7)
    private BigDecimal amount;

    @DataField(pos = 42, length=3)
    private String currency;

    @DataField(pos = 45, length=10, pattern = "dd-MM-yyyy")
    private Date orderDate;
}
Copy to Clipboard Toggle word wrap

case 2 : Fixed length record with alignment and padding

This more elaborated example show how to define the alignment for a field and how to assign a padding character which is ' ' here''

10A9 PaulineM ISINXD12345678BUYShare2500.45USD01-08-2009
Copy to Clipboard Toggle word wrap

Fixed-padding-align

@FixedLengthRecord(length=60, paddingChar=' ')
public static class Order {

    @DataField(pos = 1, length=2)
    private int orderNr;

    @DataField(pos = 3, length=2)
    private String clientNr;

    @DataField(pos = 5, length=9)
    private String firstName;

    @DataField(pos = 14, length=5, align="L")   // align text to the LEFT zone of the block
    private String lastName;

    @DataField(pos = 19, length=4)
    private String instrumentCode;

    @DataField(pos = 23, length=10)
    private String instrumentNumber;

    @DataField(pos = 33, length=3)
    private String orderType;

    @DataField(pos = 36, length=5)
    private String instrumentType;

    @DataField(pos = 41, precision = 2, length=7)
    private BigDecimal amount;

    @DataField(pos = 48, length=3)
    private String currency;

    @DataField(pos = 51, length=10, pattern = "dd-MM-yyyy")
    private Date orderDate;
}
Copy to Clipboard Toggle word wrap

case 3 : Field padding

Sometimes, the default padding defined for record cannnot be applied to the field as we have a number format where we would like to padd with '0' instead of ' '. In this case, you can use in the model the attribute paddingField to set this value.

10A9 PaulineM ISINXD12345678BUYShare000002500.45USD01-08-2009
Copy to Clipboard Toggle word wrap

Fixed-padding-field

@FixedLengthRecord(length = 65, paddingChar = ' ')
public static class Order {

    @DataField(pos = 1, length = 2)
    private int orderNr;

    @DataField(pos = 3, length = 2)
    private String clientNr;

    @DataField(pos = 5, length = 9)
    private String firstName;

    @DataField(pos = 14, length = 5, align = "L")
    private String lastName;

    @DataField(pos = 19, length = 4)
    private String instrumentCode;

    @DataField(pos = 23, length = 10)
    private String instrumentNumber;

    @DataField(pos = 33, length = 3)
    private String orderType;

    @DataField(pos = 36, length = 5)
    private String instrumentType;

    @DataField(pos = 41, precision = 2, length = 12, paddingChar = '0')
    private BigDecimal amount;

    @DataField(pos = 53, length = 3)
    private String currency;

    @DataField(pos = 56, length = 10, pattern = "dd-MM-yyyy")
    private Date orderDate;
}
Copy to Clipboard Toggle word wrap

case 4: Fixed length record with delimiter

Fixed-length records sometimes have delimited content within the record. The firstName and lastName fields are delimited with the '^' character in the following example:

10A9Pauline^M^ISINXD12345678BUYShare000002500.45USD01-08-2009
Copy to Clipboard Toggle word wrap

Fixed-delimited

@FixedLengthRecord()
public static class Order {

    @DataField(pos = 1, length = 2)
    private int orderNr;

    @DataField(pos = 2, length = 2)
    private String clientNr;

    @DataField(pos = 3, delimiter = "^")
    private String firstName;

    @DataField(pos = 4, delimiter = "^")
    private String lastName;

    @DataField(pos = 5, length = 4)
    private String instrumentCode;

    @DataField(pos = 6, length = 10)
    private String instrumentNumber;

    @DataField(pos = 7, length = 3)
    private String orderType;

    @DataField(pos = 8, length = 5)
    private String instrumentType;

    @DataField(pos = 9, precision = 2, length = 12, paddingChar = '0')
    private BigDecimal amount;

    @DataField(pos = 10, length = 3)
    private String currency;

    @DataField(pos = 11, length = 10, pattern = "dd-MM-yyyy")
    private Date orderDate;
}
Copy to Clipboard Toggle word wrap

As of Camel 2.11 the 'pos' value(s) in a fixed-length record may optionally be defined using ordinal, sequential values instead of precise column numbers.

case 5 : Fixed length record with record-defined field length

Occasionally a fixed-length record may contain a field that define the expected length of another field within the same record. In the following example the length of the instrumentNumber field value is defined by the value of instrumentNumberLen field in the record.

10A9Pauline^M^ISIN10XD12345678BUYShare000002500.45USD01-08-2009
Copy to Clipboard Toggle word wrap

Fixed-delimited

@FixedLengthRecord()
public static class Order {

    @DataField(pos = 1, length = 2)
    private int orderNr;

    @DataField(pos = 2, length = 2)
    private String clientNr;

    @DataField(pos = 3, delimiter = "^")
    private String firstName;

    @DataField(pos = 4, delimiter = "^")
    private String lastName;

    @DataField(pos = 5, length = 4)
    private String instrumentCode;

    @DataField(pos = 6, length = 2, align = "R", paddingChar = '0')
    private int instrumentNumberLen;

    @DataField(pos = 7, lengthPos=6)
    private String instrumentNumber;

    @DataField(pos = 8, length = 3)
    private String orderType;

    @DataField(pos = 9, length = 5)
    private String instrumentType;

    @DataField(pos = 10, precision = 2, length = 12, paddingChar = '0')
    private BigDecimal amount;

    @DataField(pos = 11, length = 3)
    private String currency;

    @DataField(pos = 12, length = 10, pattern = "dd-MM-yyyy")
    private Date orderDate;
}
Copy to Clipboard Toggle word wrap

case 6 : Fixed length record with header and footer

Bindy will discover fixed-length header and footer records that are configured as part of the model – provided that the annotated classes exist either in the same package as the primary @FixedLengthRecord class, or within one of the configured scan packages. The following text illustrates two fixed-length records that are bracketed by a header record and footer record.

101-08-2009
10A9 PaulineM ISINXD12345678BUYShare000002500.45USD01-08-2009
10A9 RichN ISINXD12345678BUYShare000002700.45USD01-08-2009
9000000002
Copy to Clipboard Toggle word wrap

Fixed-header-and-footer-main-class

@FixedLengthRecord(hasHeader = true, hasFooter = true)
public class Order {

    @DataField(pos = 1, length = 2)
    private int orderNr;

    @DataField(pos = 2, length = 2)
    private String clientNr;

    @DataField(pos = 3, length = 9)
    private String firstName;

    @DataField(pos = 4, length = 5, align = "L")
    private String lastName;

    @DataField(pos = 5, length = 4)
    private String instrumentCode;

    @DataField(pos = 6, length = 10)
    private String instrumentNumber;

    @DataField(pos = 7, length = 3)
    private String orderType;

    @DataField(pos = 8, length = 5)
    private String instrumentType;

    @DataField(pos = 9, precision = 2, length = 12, paddingChar = '0')
    private BigDecimal amount;

    @DataField(pos = 10, length = 3)
    private String currency;

    @DataField(pos = 11, length = 10, pattern = "dd-MM-yyyy")
    private Date orderDate;
}

@FixedLengthRecord(isHeader = true)
public  class OrderHeader {
    @DataField(pos = 1, length = 1)
    private int recordType = 1;

    @DataField(pos = 2, length = 10, pattern = "dd-MM-yyyy")
    private Date recordDate;
}

@FixedLengthRecord(isFooter = true)
public class OrderFooter {

    @DataField(pos = 1, length = 1)
    private int recordType = 9;

    @DataField(pos = 2, length = 9, align = "R", paddingChar = '0')
    private int numberOfRecordsInTheFile;
}
Copy to Clipboard Toggle word wrap

case 7 : Skipping content when parsing a fixed length record. (Camel 2.11.1)

It is common to integrate with systems that provide fixed-length records containing more information than needed for the target use case. It is useful in this situation to skip the declaration and parsing of those fields that we do not need. To accomodate this, Bindy will skip forward to the next mapped field within a record if the 'pos' value of the next declared field is beyond the cursor position of the last parsed field. Using absolute 'pos' locations for the fields of interest (instead of ordinal values) causes Bindy to skip content between two fields.

Similarly, it is possible that none of the content beyond some field is of interest. In this case, you can tell Bindy to skip parsing of everything beyond the last mapped field by setting the ignoreTrailingChars property on the @FixedLengthRecord declaration.

@FixedLengthRecord(ignoreTrailingChars = true)
public static class Order {

    @DataField(pos = 1, length = 2)
    private int orderNr;

    @DataField(pos = 3, length = 2)
    private String clientNr;

    // any characters that appear beyond the last mapped field will be ignored

}
Copy to Clipboard Toggle word wrap

48.7. 5. Message

The Message annotation is used to identified the class of your model who will contain key value pairs fields. This kind of format is used mainly in Financial Exchange Protocol Messages (FIX). Nevertheless, this annotation can be used for any other format where data are identified by keys. The key pair values are separated each other by a separator which can be a special character like a tab delimitor (unicode representation : \u0009) or a start of heading (unicode representation : \u0001)

*"FIX information"*
Copy to Clipboard Toggle word wrap

More information about FIX can be found on this web site : http://www.fixprotocol.org/. To work with FIX messages, the model must contain a Header and Trailer classes linked to the root message class which could be a Order class. This is not mandatory but will be very helpful when you will use camel-bindy in combination with camel-fix which is a Fix gateway based on quickFix project http://www.quickfixj.org/.

Expand
Annotation nameRecord typeLevel

Message

key value pair

Class

Expand
Parameter nametypeInfo

pairSeparator

string

mandatory - can be '=' or ';' or 'anything'

keyValuePairSeparair

string

mandatory - can be '\u0001', '\u0009', '#' or 'anything'

crlf

string

optional - possible values = WINDOWS,UNIX,MAC, or custom; default value = WINDOWS - allow to define the carriage return character to use. If you specify a value other than the three listed before, the value you enter (custom) will be used as the CRLF character(s)

type

string

optional - define the type of message (e.g. FIX, EMX, …​)

version

string

optional - version of the message (e.g. 4.1)

isOrdered

boolean

optional - default value = false - allow to change the order of the fields when FIX message is generated. This annotation is associated to the message class of the model and must be declared one time.

case 1 : separator = 'u0001'

The separator used to segregate the key value pair fields in a FIX message is the ASCII '01' character or in unicode format '\u0001'. This character must be escaped a second time to avoid a java runtime error. Here is an example :

8=FIX.4.1 9=20 34=1 35=0 49=INVMGR 56=BRKR 1=BE.CHM.001 11=CHM0001-01
22=4 ...
Copy to Clipboard Toggle word wrap

and how to use the annotation

FIX - message

@Message(keyValuePairSeparator = "=", pairSeparator = "\u0001", type="FIX", version="4.1")
public class Order {

}
Copy to Clipboard Toggle word wrap
*Look at test cases*
Copy to Clipboard Toggle word wrap

The ASCII character like tab, …​ cannot be displayed in WIKI page. So, have a look to the test case of camel-bindy to see exactly how the FIX message looks like (src\test\data\fix\fix.txt) and the Order, Trailer, Header classes (src\test\java\org\apache\camel\dataformat\bindy\model\fix\simple\Order.java)

48.8. 6. KeyValuePairField

The KeyValuePairField annotation defines the property of a key value pair field. Each KeyValuePairField is identified by a tag (= key) and its value associated, a type (string, int, date, …​), optionaly a pattern and if the field is required

Expand
Annotation nameRecord typeLevel

KeyValuePairField

Key Value Pair - FIX

Property

Expand
Parameter nametypeInfo

tag

int

mandatory - digit number identifying the field in the message - must be unique

pattern

string

optional - default value = "" - will be used to format Decimal, Date, …​

precision

int

optional - digit number - represents the precision to be used when the Decimal number will be formatted/parsed

position

int

optional - must be used when the position of the key/tag in the FIX message must be different

required

boolean

optional - default value = "false"

impliedDecimalSeparator

boolean

Camel 2.11: optional - default value = "false" - Indicates if there is a decimal point implied at a specified location

case 1 : tag

This parameter represents the key of the field in the message

FIX message - Tag

@Message(keyValuePairSeparator = "=", pairSeparator = "\u0001", type="FIX", version="4.1")
public class Order {

    @Link Header header;

    @Link Trailer trailer;

    @KeyValuePairField(tag = 1) // Client reference
    private String Account;

    @KeyValuePairField(tag = 11) // Order reference
    private String ClOrdId;

    @KeyValuePairField(tag = 22) // Fund ID type (Sedol, ISIN, ...)
    private String IDSource;

    @KeyValuePairField(tag = 48) // Fund code
    private String SecurityId;

    @KeyValuePairField(tag = 54) // Movement type ( 1 = Buy, 2 = sell)
    private String Side;

    @KeyValuePairField(tag = 58) // Free text
    private String Text;
}
Copy to Clipboard Toggle word wrap

case 2 : Different position in output

If the tags/keys that we will put in the FIX message must be sorted according to a predefine order, then use the attribute 'position' of the annotation @KeyValuePairField

FIX message - Tag - sort

@Message(keyValuePairSeparator = "=", pairSeparator = "\\u0001", type = "FIX", version = "4.1", isOrdered = true)
public class Order {

    @Link Header header;

    @Link Trailer trailer;

    @KeyValuePairField(tag = 1, position = 1) // Client reference
    private String account;

    @KeyValuePairField(tag = 11, position = 3) // Order reference
    private String clOrdId;
}
Copy to Clipboard Toggle word wrap

48.9. 7. Section

In FIX message of fixed length records, it is common to have different sections in the representation of the information : header, body and section. The purpose of the annotation @Section is to inform bindy about which class of the model represents the header (= section 1), body (= section 2) and footer (= section 3)

Only one attribute/parameter exists for this annotation.

Expand
Annotation nameRecord typeLevel

Section

FIX

Class

Expand
Parameter nametypeInfo

number

int

digit number identifying the section position

case 1 : Section

Definition of the header section

FIX message - Section - Header

@Section(number = 1)
public class Header {

    @KeyValuePairField(tag = 8, position = 1) // Message Header
    private String beginString;

    @KeyValuePairField(tag = 9, position = 2) // Checksum
    private int bodyLength;
}
Copy to Clipboard Toggle word wrap

Definition of the body section

FIX message - Section - Body

@Section(number = 2)
@Message(keyValuePairSeparator = "=", pairSeparator = "\\u0001", type = "FIX", version = "4.1", isOrdered = true)
public class Order {

    @Link Header header;

    @Link Trailer trailer;

    @KeyValuePairField(tag = 1, position = 1) // Client reference
    private String account;

    @KeyValuePairField(tag = 11, position = 3) // Order reference
    private String clOrdId;
Copy to Clipboard Toggle word wrap

Definition of the footer section

FIX message - Section - Footer

@Section(number = 3)
public class Trailer {

    @KeyValuePairField(tag = 10, position = 1)
    // CheckSum
    private int checkSum;

    public int getCheckSum() {
        return checkSum;
    }
Copy to Clipboard Toggle word wrap

48.10. 8. OneToMany

The purpose of the annotation @OneToMany is to allow to work with a List<?> field defined a POJO class or from a record containing repetitive groups.

*Restrictions OneToMany*
Copy to Clipboard Toggle word wrap

Be careful, the one to many of bindy does not allow to handle repetitions defined on several levels of the hierarchy

The relation OneToMany ONLY WORKS in the following cases :

  • Reading a FIX message containing repetitive groups (= group of tags/keys)
  • Generating a CSV with repetitive data
Expand
Annotation nameRecord typeLevel

OneToMany

all

property

Expand
Parameter nametypeInfo

mappedTo

string

optional - string - class name associated to the type of the List<Type of the Class>

case 1 : Generating CSV with repetitive data

Here is the CSV output that we want :

Claus,Ibsen,Camel in Action 1,2010,35
Claus,Ibsen,Camel in Action 2,2012,35
Claus,Ibsen,Camel in Action 3,2013,35
Claus,Ibsen,Camel in Action 4,2014,35
Copy to Clipboard Toggle word wrap

Remark : the repetitive data concern the title of the book and its publication date while first, last name and age are common

and the classes used to modeling this. The Author class contains a List of Book.

Generate CSV with repetitive data

@CsvRecord(separator=",")
public class Author {

    @DataField(pos = 1)
    private String firstName;

    @DataField(pos = 2)
    private String lastName;

    @OneToMany
    private List<Book> books;

    @DataField(pos = 5)
    private String Age;
}

public class Book {

    @DataField(pos = 3)
    private String title;

    @DataField(pos = 4)
    private String year;
}
Copy to Clipboard Toggle word wrap

Very simple isn’t it !!!

case 2 : Reading FIX message containing group of tags/keys

Here is the message that we would like to process in our model :

8=FIX 4.19=2034=135=049=INVMGR56=BRKR
1=BE.CHM.00111=CHM0001-0158=this is a camel - bindy test
22=448=BE000124567854=1
22=548=BE000987654354=2
22=648=BE000999999954=3
10=220
Copy to Clipboard Toggle word wrap

tags 22, 48 and 54 are repeated

and the code

Reading FIX message containing group of tags/keys

public class Order {

    @Link Header header;

    @Link Trailer trailer;

    @KeyValuePairField(tag = 1) // Client reference
    private String account;

    @KeyValuePairField(tag = 11) // Order reference
    private String clOrdId;

    @KeyValuePairField(tag = 58) // Free text
    private String text;

    @OneToMany(mappedTo = "org.apache.camel.dataformat.bindy.model.fix.complex.onetomany.Security")
    List<Security> securities;
}

public class Security {

    @KeyValuePairField(tag = 22) // Fund ID type (Sedol, ISIN, ...)
    private String idSource;

    @KeyValuePairField(tag = 48) // Fund code
    private String securityCode;

    @KeyValuePairField(tag = 54) // Movement type ( 1 = Buy, 2 = sell)
    private String side;
}
Copy to Clipboard Toggle word wrap

48.11. 9. BindyConverter

The purpose of the annotation @BindyConverter is define a converter to be used on field level. The provided class must implement the Format interface.

@FixedLengthRecord(length = 10, paddingChar = ' ')
public static class DataModel {
    @DataField(pos =  1, length = 10, trim = true)
    @BindyConverter(CustomConverter.class)
    public String field1;
}

public static class CustomConverter implements Format<String> {
    @Override
    public String format(String object) throws Exception {
        return (new StringBuilder(object)).reverse().toString();
    }

    @Override
    public String parse(String string) throws Exception {
        return (new StringBuilder(string)).reverse().toString();
    }
}
Copy to Clipboard Toggle word wrap

48.12. 10. FormatFactories

The purpose of the annotation @FormatFactories is to define a set of converters at record-level. The provided classes must implement the FormatFactoryInterface interface.

@CsvRecord(separator = ",")
@FormatFactories({OrderNumberFormatFactory.class})
public static class Order {

    @DataField(pos = 1)
    private OrderNumber orderNr;

    @DataField(pos = 2)
    private String firstName;
}

public static class OrderNumber {
    private int orderNr;

    public static OrderNumber ofString(String orderNumber) {
        OrderNumber result = new OrderNumber();
        result.orderNr = Integer.valueOf(orderNumber);
        return result;
    }
}

public static class OrderNumberFormatFactory extends AbstractFormatFactory {

    {
        supportedClasses.add(OrderNumber.class);
    }

    @Override
    public Format<?> build(FormattingOptions formattingOptions) {
        return new Format<OrderNumber>() {
            @Override
            public String format(OrderNumber object) throws Exception {
                return String.valueOf(object.orderNr);
            }

            @Override
            public OrderNumber parse(String string) throws Exception {
                return OrderNumber.ofString(string);
            }
        };
    }
}
Copy to Clipboard Toggle word wrap

48.13. Supported Datatypes

The DefaultFormatFactory makes formatting of the following datatype available by returning an instance of the interface FormatFactoryInterface based on the provided FormattingOptions:

  • BigDecimal
  • BigInteger
  • Boolean
  • Byte
  • Character
  • Date
  • Double
  • Enums
  • Float
  • Integer
  • LocalDate (java 8, since 2.18.0)
  • LocalDateTime (java 8, since 2.18.0)
  • LocalTime (java 8, since 2.18.0)
  • Long
  • Short
  • String

The DefaultFormatFactory can be overridden by providing an instance of FactoryRegistry in the registry in use (e.g. spring or JNDI).

48.14. Using the Java DSL

The next step consists in instantiating the DataFormat bindy class associated with this record type and providing Java package name(s) as parameter.

For example the following uses the class BindyCsvDataFormat (who correspond to the class associated with the CSV record type) which is configured with com.acme.model package name to initialize the model objects configured in this package.

// Camel 2.15 or older (configure by package name)
DataFormat bindy = new BindyCsvDataFormat("com.acme.model");

 
// Camel 2.16 onwards (configure by class name)
DataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);
Copy to Clipboard Toggle word wrap

48.14.1. Setting locale

Bindy supports configuring the locale on the dataformat, such as 

// Camel 2.15 or older (configure by package name)
BindyCsvDataFormat bindy = new BindyCsvDataFormat("com.acme.model");
// Camel 2.16 onwards (configure by class name)
BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);

bindy.setLocale("us");
Copy to Clipboard Toggle word wrap

Or to use the platform default locale then use "default" as the locale name. Notice this requires Camel 2.14/2.13.3/2.12.5.

// Camel 2.15 or older (configure by package name)
BindyCsvDataFormat bindy = new BindyCsvDataFormat("com.acme.model");
// Camel 2.16 onwards (configure by class name)
BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);

bindy.setLocale("default");
Copy to Clipboard Toggle word wrap

for older releases you can set it using Java code as shown

// Camel 2.15 or older (configure by package name)
BindyCsvDataFormat bindy = new BindyCsvDataFormat("com.acme.model");
// Camel 2.16 onwards (configure by class name)
BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);

bindy.setLocale(Locale.getDefault().getISO3Country());
Copy to Clipboard Toggle word wrap

48.14.2. Unmarshaling

from("file://inbox")
  .unmarshal(bindy)
  .to("direct:handleOrders");
Copy to Clipboard Toggle word wrap

Alternatively, you can use a named reference to a data format which can then be defined in your Registry e.g. your Spring XML file:

from("file://inbox")
  .unmarshal("myBindyDataFormat")
  .to("direct:handleOrders");
Copy to Clipboard Toggle word wrap

The Camel route will pick-up files in the inbox directory, unmarshall CSV records into a collection of model objects and send the collection
to the route referenced by 'handleOrders'.

The collection returned is a List of Map objects. Each Map within the list contains the model objects that were marshalled out of each line of the CSV. The reason behind this is that each line can correspond to more than one object. This can be confusing when you simply expect one object to be returned per line.

Each object can be retrieve using its class name.

List<Map<String, Object>> unmarshaledModels = (List<Map<String, Object>>) exchange.getIn().getBody();

int modelCount = 0;
for (Map<String, Object> model : unmarshaledModels) {
  for (String className : model.keySet()) {
     Object obj = model.get(className);
     LOG.info("Count : " + modelCount + ", " + obj.toString());
  }
 modelCount++;
}

LOG.info("Total CSV records received by the csv bean : " + modelCount);
Copy to Clipboard Toggle word wrap

Assuming that you want to extract a single Order object from this map for processing in a route, you could use a combination of a Splitter and a Processor as per the following:

from("file://inbox")
    .unmarshal(bindy)
    .split(body())
        .process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                Message in = exchange.getIn();
                Map<String, Object> modelMap = (Map<String, Object>) in.getBody();
                in.setBody(modelMap.get(Order.class.getCanonicalName()));
            }
        })
        .to("direct:handleSingleOrder")
    .end();
Copy to Clipboard Toggle word wrap

Take care of the fact that Bindy uses CHARSET_NAME property or the CHARSET_NAME header as define in the Exchange interface to do a characterset conversion of the inputstream received for unmarshalling. In some producers (e.g. file-endpoint) you can define a characterset. The characterset conversion can already been done by this producer. Sometimes you need to remove this property or header from the exchange before sending it to the unmarshal. If you don’t remove it the conversion might be done twice which might lead to unwanted results.

from("file://inbox?charset=Cp922")
  .removeProperty(Exchange.CHARSET_NAME)
  .unmarshal("myBindyDataFormat")
  .to("direct:handleOrders");
Copy to Clipboard Toggle word wrap

48.14.3. Marshaling

To generate CSV records from a collection of model objects, you create the following route :

from("direct:handleOrders")
   .marshal(bindy)
   .to("file://outbox")
Copy to Clipboard Toggle word wrap

48.15. Using Spring XML

This is really easy to use Spring as your favorite DSL language to declare the routes to be used for camel-bindy. The following example shows two routes where the first will pick-up records from files, unmarshal the content and bind it to their model. The result is then send to a pojo (doing nothing special) and place them into a queue.

The second route will extract the pojos from the queue and marshal the content to generate a file containing the csv record. The example above is for using Camel 2.16 onwards.

spring dsl

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring
       http://camel.apache.org/schema/spring/camel-spring.xsd">

    <!-- Queuing engine - ActiveMq - work locally in mode virtual memory -->
    <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent">
        <property name="brokerURL" value="vm://localhost:61616"/>
    </bean>

    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <dataFormats>
          <bindy id="bindyDataformat" type="Csv" classType="org.apache.camel.bindy.model.Order"/>
        </dataFormats>

        <route>
            <from uri="file://src/data/csv/?noop=true" />
            <unmarshal ref="bindyDataformat" />
            <to uri="bean:csv" />
            <to uri="activemq:queue:in" />
        </route>

        <route>
            <from uri="activemq:queue:in" />
            <marshal ref="bindyDataformat" />
            <to uri="file://src/data/csv/out/" />
        </route>
    </camelContext>
</beans>
Copy to Clipboard Toggle word wrap
Note

Please verify that your model classes implements serializable otherwise the queue manager will raise an error

48.16. Dependencies

To use Bindy in your camel routes you need to add the a dependency on camel-bindy which implements this data format.

If you use maven you could just add the following to your pom.xml, substituting the version number for the latest & greatest release (see the download page for the latest versions).

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-bindy</artifactId>
  <version>x.x.x</version>
</dependency>
Copy to Clipboard Toggle word wrap

Chapter 49. Using OSGi blueprint with Camel

A custom XML namespace for Blueprint has been created to let you leverage the nice XML dialect. Given Blueprint custom namespaces are not standardized yet, this namespace can only be used on the Apache Aries Blueprint implementation, which is the one used by Apache Karaf.

49.1. Overview

The XML schema is mostly the same as the one for Spring, so all the xml snippets throughout the documentation referring to Spring XML also apply to Blueprint routes.

Here is a very simple route definition using blueprint:

<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">

    <camelContext xmlns="http://camel.apache.org/schema/blueprint">
        <route>
            <from uri="timer:test" />
            <to uri="log:test" />
        </route>
    </camelContext>

</blueprint>
Copy to Clipboard Toggle word wrap

There are a few limitations at this point about the supported xml elements (compared to the Spring xml syntax):

  • beanPostProcessor are specific to Spring and aren’t allowed

However, using blueprint when you deploy your applications in an OSGi enviroment has several advantages:

  • when upgrading to a new camel version, you don’t have to change the namespace, as the correct version will be selected based on the camel packages that are imported by your bundle
  • no startup ordering issue with respect to the custom namespaces and your bundles
  • you can use Blueprint property placeholders

49.2. Using camel-blueprint

To leverage camel-blueprint in OSGi, you only need the Aries Blueprint bundle and the camel-blueprint bundle, in addition to camel-core and its dependencies.

If you use Karaf, you can use the feature named camel-blueprint which will install all the required bundles.

Chapter 50. Bonita Component

Available as of Camel version 2.19

Used for communicating with a remote Bonita BPM process engine.

50.1. URI format

bonita://[operation]?[options]
Copy to Clipboard Toggle word wrap

Where operation is the specific action to perform on Bonita.

50.2. General Options

The Bonita component has no options.

The Bonita endpoint is configured using URI syntax:

bonita:operation
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

50.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

operation

Required Operation to use

 

BonitaOperation

50.2.2. Query Parameters (9 parameters):

Expand
NameDescriptionDefaultType

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

hostname (consumer)

Hostname where Bonita engine runs

localhost

String

port (consumer)

Port of the server hosting Bonita engine

8080

String

processName (consumer)

Name of the process involved in the operation

 

String

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

password (security)

Password to authenticate to Bonita engine.

 

String

username (security)

Username to authenticate to Bonita engine.

 

String

50.3. Body content

For the startCase operation, the input variables are retrieved from the body message. This one has to contains a Map<String,Serializable>.

50.4. Examples

The following example start a new case in Bonita:

from("direct:start").to("bonita:startCase?hostname=localhost&amp;port=8080&amp;processName=TestProcess&amp;username=install&amp;password=install")
Copy to Clipboard Toggle word wrap

50.5. Dependencies

To use Bonita in your Camel routes you need to add a dependency on camel-bonita, which implements the component.

If you use Maven you can just add the following to your pom.xml, substituting the version number for the latest and greatest release (see the download page for the latest versions).

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-bonita</artifactId>
  <version>x.x.x</version>
</dependency>
Copy to Clipboard Toggle word wrap

Chapter 51. Boon DataFormat

Available as of Camel version 2.16

Boon is a Data Format which uses the Boon JSON marshalling library to unmarshal an JSON payload into Java objects or to marshal Java objects into an JSON payload. Boon aims to be a simple and fast parser than other common parsers currently used.

51.1. Options

The Boon dataformat supports 3 options which are listed below.

Expand
NameDefaultJava TypeDescription

unmarshalTypeName

 

String

Class name of the java type to use when unarmshalling

useList

false

Boolean

To unarmshal to a List of Map or a List of Pojo.

contentTypeHeader

false

Boolean

Whether the data format should set the Content-Type header with the type from the data format if the data format is capable of doing so. For example application/xml for data formats marshalling to XML, or application/json for data formats marshalling to JSon etc.

51.2. Using the Java DSL

DataFormat boonDataFormat = new BoonDataFormat("com.acme.model.Person");

from("activemq:My.Queue")
  .unmarshal(boonDataFormat)
  .to("mqseries:Another.Queue");
Copy to Clipboard Toggle word wrap

51.3. Using Blueprint XML

<bean id="boonDataFormat" class="org.apache.camel.component.boon.BoonDataFormat">
  <argument value="com.acme.model.Person"/>
</bean>

<camelContext id="camel" xmlns="http://camel.apache.org/schema/blueprint">
  <route>
    <from uri="activemq:My.Queue"/>
    <unmarshal ref="boonDataFormat"/>
    <to uri="mqseries:Another.Queue"/>
  </route>
</camelContext>
Copy to Clipboard Toggle word wrap

51.4. Dependencies

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-boon</artifactId>
  <version>x.x.x</version>
</dependency>
Copy to Clipboard Toggle word wrap

Chapter 52. Box Component

Available as of Camel version 2.14

The Box component provides access to all of the Box.com APIs accessible using https://github.com/box/box-java-sdk. It allows producing messages to upload and download files, create, edit, and manage folders, etc. It also supports APIs that allow polling for updates to user accounts and even changes to enterprise accounts, etc.

Box.com requires the use of OAuth2.0 for all client application authentication. In order to use camel-box with your account, you’ll need to create a new application within Box.com at https://developer.box.com. The Box application’s client id and secret will allow access to Box APIs which require a current user. A user access token is generated and managed by the API for an end user.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-box</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

52.1. Connection Authentication Types

The Box component supports three different types of authenticated connections.

52.1.1. Standard Authentication

Standard Authentication uses the OAuth 2.0 three-legged authentication process to authenticate its connections with Box.com. This type of authentication enables Box managed users and external users to access, edit, and save their Box content through the Box component.

52.1.2. App Enterprise Authentication

App Enterprise Authentication uses the OAuth 2.0 with JSON Web Tokens (JWT) to authenticate its connections as a Service Account for a Box Application. This type of authentication enables a service account to access, edit, and save the Box content of its Box Application through the Box component.

52.1.3. App User Authentication

App User Authentication uses the OAuth 2.0 with JSON Web Tokens (JWT) to authenticate its connections as an App User for a Box Application. This type of authentication enables app users to access, edit, and save their Box content in its Box Application through the Box component.

52.2. Box Options

The Box component supports 2 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (common)

To use the shared configuration

 

BoxConfiguration

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Box endpoint is configured using URI syntax:

box:apiName/methodName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

52.2.1. Path Parameters (2 parameters):

Expand
NameDescriptionDefaultType

apiName

Required What kind of operation to perform

 

BoxApiName

methodName

Required What sub operation to use for the selected operation

 

String

52.2.2. Query Parameters (20 parameters):

Expand
NameDescriptionDefaultType

clientId (common)

Box application client ID

 

String

enterpriseId (common)

The enterprise ID to use for an App Enterprise.

 

String

inBody (common)

Sets the name of a parameter to be passed in the exchange In Body

 

String

userId (common)

The user ID to use for an App User.

 

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

httpParams (advanced)

Custom HTTP params for settings like proxy host

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

accessTokenCache (security)

Custom Access Token Cache for storing and retrieving access tokens.

 

IAccessTokenCache

clientSecret (security)

Box application client secret

 

String

encryptionAlgorithm (security)

The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512

RSA_SHA_256

EncryptionAlgorithm

maxCacheEntries (security)

The maximum number of access tokens in cache.

100

int

authenticationType (authentication)

The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens

APP_USER_AUTHENTICATION

String

privateKeyFile (security)

The private key for generating the JWT signature.

 

String

privateKeyPassword (security)

The password for the private key.

 

String

publicKeyId (security)

The ID for public key for validating the JWT signature.

 

String

sslContextParameters (security)

To configure security using SSLContextParameters.

 

SSLContextParameters

userName (security)

Box user name, MUST be provided

 

String

userPassword (security)

Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call

 

String

52.3. URI format

box:apiName/methodName
Copy to Clipboard Toggle word wrap

apiName can be one of:

  • collaborations
  • comments
  • event-logs
  • files
  • folders
  • groups
  • events
  • search
  • tasks
  • users

52.4. Producer Endpoints:

Producer endpoints can use endpoint prefixes followed by endpoint names and associated options described next. A shorthand alias can be used for some endpoints. The endpoint URI MUST contain a prefix.

Endpoint options that are not mandatory are denoted by []. When there are no mandatory options for an endpoint, one of the set of [] options MUST be provided. Producer endpoints can also use a special option inBody that in turn should contain the name of the endpoint option whose value will be contained in the Camel Exchange In message.

Any of the endpoint options can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format CamelBox.<option>. Note that the inBody option overrides message header, i.e. the endpoint option inBody=option would override a CamelBox.option header.

If a value is not provided for the option defaultRequest either in the endpoint URI or in a message header, it will be assumed to be null. Note that the null value will only be used if other options do not satisfy matching endpoints.

In case of Box API errors the endpoint will throw a RuntimeCamelException with a com.box.sdk.BoxAPIException derived exception cause.

52.4.1. Endpoint Prefix collaborations

For more information on Box collaborations see https://developer.box.com/reference#collaboration-object. The following endpoints can be invoked with the prefix collaborations as follows:

box:collaborations/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

addFolderCollaboration

add

folderId, collaborator, role

com.box.sdk.BoxCollaboration

addFolderCollaborationByEmail

addByEmail

folderId, email, role

com.box.sdk.BoxCollaboration

deleteCollaboration

delete

collaborationId

 

getFolderCollaborations

collaborations

folderId

java.util.Collection

getPendingCollaborations

pendingCollaborations

 

java.util.Collection

getCollaborationInfo

info

collaborationId

com.box.sdk.BoxCollaboration.Info

updateCollaborationInfo

updateInfo

collaborationId, info

com.box.sdk.BoxCollaboration

URI Options for collaborations

Expand
NameType

collaborationId

String

collaborator

com.box.sdk.BoxCollaborator

role

com.box.sdk.BoxCollaboration.Role

folderId

String

email

String

info

com.box.sdk.BoxCollaboration.Info

52.4.2. Endpoint Prefix comments

For more information on Box comments see https://developer.box.com/reference#comment-object. The following endpoints can be invoked with the prefix comments as follows:

box:comments/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

addFileComment

add

fileId, message

com.box.sdk.BoxFile

changeCommentMessage

updateMessage

commentId, message

com.box.sdk.BoxComment

deleteComment

delete

commentId

 

getCommentInfo

info

commentId

com.box.sdk.BoxComment.Info

getFileComments

comments

fileId

java.util.List

replyToComment

reply

commentId, message

com.box.sdk.BoxComment

URI Options for collaborations

Expand
NameType

commentId

String

fileId

String

message

String

52.4.3. Endpoint Prefix events-logs

For more information on Box event logs see https://developer.box.com/reference#events. The following endpoints can be invoked with the prefix events as follows:

box:event-logs/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

getEnterpriseEvents

events

position, after, before, [types]

java.util.List

URI Options for event-logs

Expand
NameType

position

String

after

Date

before

Date

types

com.box.sdk.BoxEvent.Types[]

52.4.4. Endpoint Prefix files

For more information on Box files see https://developer.box.com/reference#file-object. The following endpoints can be invoked with the prefix files as follows.

box:files/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

uploadFile

upload

parentFolderId, content, fileName, [created], [modified], [size], [listener]

com.box.sdk.BoxFile

downloadFile

download

fileId, output, [rangeStart], [rangeEnd], [listener]

java.io.OutputStream

copyFile

copy

fileId, destinationFolderId, [newName]

com.box.sdk.BoxFile

moveFile

move

fileId, destinationFolderId, [newName]

com.box.sdk.BoxFile

renameFile

rename

fileId, newFileName

com.box.sdk.BoxFile

createFileSharedLink

link

fileId, access, [unshareDate], [permissions]

com.box.sdk.BoxSharedLink

deleteFile

delete

fileId

 

uploadNewFileVersion

uploadVersion

fileId, fileContent, [modified], [fileSize], [listener]

com.box.boxsdk.BoxFile

promoteFileVersion

promoteVersion

fileId, version

com.box.sdk.BoxFileVersion

getFileVersions

versions

fileId

java.util.Collection

downloadPreviousFileVersions

downloadVersion

fileId, version, output, [listener]

java.io.OutputStream

deleteFileVersion

deleteVersion

fileId, version

 

getFileInfo

info

fileId, fields

com.box.sdk.BoxFile.Info

updateFileInfo

updateInfo

fileId, info

com.box.sdk.BoxFile

createFileMetadata

createMetadata

fileId, metadata, [typeName]

com.box.sdk.Metadata

getFileMetadata

metadata

fileId, [typeName]

com.box.sdk.Metadata

updateFileMetadata

updateMetadata

fileId, metadata

com.box.sdk.Metadata

deleteFileMetadata

deleteMetadata

fileId

 

getDownloadUrl

url

fileId

java.net.URL

getPreviewLink

preview

fileId

java.net.URL

getFileThumbnail

thumbnail

fileId, fileType, minWidth, minHeight, maxWidth, maxHeight

byte[]

URI Options for files

Expand
NameType

parentFolderId

String

content

java.io.InputStream

fileName

String

created

Date

modified

Date

size

Long

listener

com.box.sdk.ProgressListener

output

java.io.OutputStream

rangeStart

Long

rangeEnd

Long

outputStreams

java.io.OutputStream[]

destinationFolderId

String

newName

String

fields

String[]

info

com.box.sdk.BoxFile.Info

fileSize

Long

version

Integer

access

com.box.sdk.BoxSharedLink.Access

unshareDate

Date

permissions

com.box.sdk.BoxSharedLink.Permissions

fileType

com.box.sdk.BoxFile.ThumbnailFileType

minWidth

Integer

minHeight

Integer

maxWidth

Integer

maxHeight

Integer

metadata

com.box.sdk.Metadata

typeName

String

52.4.5. Endpoint Prefix folders

For more information on Box folders see https://developer.box.com/reference#folder-object. The following endpoints can be invoked with the prefix folders as follows.

box:folders/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

getRootFolder

root

 

com.box.sdk.BoxFolder

createFolder

create

parentFolderId, folderName

com.box.sdk.BoxFolder

createFolder

create

parentFolderId, path

com.box.sdk.BoxFolder

copyFolder

copy

folderId, destinationfolderId, [newName]

com.box.sdk.BoxFolder

moveFolder

move

folderId, destinationFolderId, newName

com.box.sdk.BoxFolder

renameFolder

rename

folderId, newFolderName

com.box.sdk.BoxFolder

createFolderSharedLink

link

folderId, access, [unsharedDate], [permissions]

java.util.List

deleteFolder

delete

folderId

 

getFolder

folder

path

com.box.sdk.BoxFolder

getFolderInfo

info

folderId, fields

com.box.sdk.BoxFolder.Info

getFolderItems

items

folderId, offset, limit, fields

com.box.sdk.BoxFolder

updateFolderInfo

updateInfo

folderId, info

com.box.sdk.BoxFolder

URI Options for folders

Expand
NameType

path

String[]

folderId

String

offset

Long

limit

Long

fields

String[]

parentFolderId

String

folderName

String

destinationFolderId

String

newName

String

newFolderName

String

info

String

access

com.box.sdk.BoxSharedLink.Access

unshareDate

Date

permissions

com.box.sdk.BoxSharedLink.Permissions

52.4.6. Endpoint Prefix groups

For more information on Box groups see https://developer.box.com/reference#group-object. The following endpoints can be invoked with the prefix groups as follows:

box:groups/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

createGroup

create

name, [provenance, externalSyncIdentifier, description, invitabilityLevel, memberViewabilityLevel]

com.box.sdk.BoxGroup

addGroupMembership

createMembership

groupId, userId, role

com.box.sdk.BoxGroupMembership

deleteGroup

delete

groupId

 

getAllGroups

groups

 

java.util.Collection

getGroupInfo

info

groupId

com.box.sdk.BoxGroup.Info

updateGroupInfo

updateInfo

groupId, groupInfo

com.box.sdk.BoxGroup

addGroupMembership

addMembership

groupId, userId, role

com.box.sdk.BoxGroupMembership

deleteGroupMembership

deleteMembership

groupMembershipId

 

getGroupMemberships

memberships

groupId

java.uti.Collection

getGroupMembershipInfo

membershipInfo

groupMemebershipId

com.box.sdk.BoxGroup.Info

updateGroupMembershipInfo

updateMembershipInfo

groupMemebershipId, info

com.box.sdk.BoxGroupMembership

URI Options for groups

Expand
NameType

name

String

groupId

String

userId

String

role

com.box.sdk.BoxGroupMembership.Role

groupMembershipId

String

info

com.box.sdk.BoxGroupMembership.Info

52.4.7. Endpoint Prefix search

For more information on Box search API see https://developer.box.com/reference#searching-for-content. The following endpoints can be invoked with the prefix search as follows:

box:search/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

searchFolder

search

folderId, query

java.util.Collection

URI Options for search

Expand
NameType

folderId

String

query

String

52.4.8. Endpoint Prefix tasks

For information on Box tasks see https://developer.box.com/reference#task-object-1. The following endpoints can be invoked with the prefix tasks as follows:

box:tasks/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

addFileTask

add

fileId, action, dueAt, [message]

com.box.sdk.BoxUser

deleteTask

delete

taskId

 

getFileTasks

tasks

fileId

java.util.List

getTaskInfo

info

taskId

com.box.sdk.BoxTask.Info

updateTaskInfo

updateInfo

taskId, info

com.box.sdk.BoxTask

addAssignmentToTask

addAssignment

taskId, assignTo

com.box.sdk.BoxTask

deleteTaskAssignment

deleteAssignment

taskAssignmentId

 

getTaskAssignments

assignments

taskId

java.util.List

getTaskAssignmentInfo

assignmentInfo

taskAssignmentId

com.box.sdk.BoxTaskAssignment.Info

URI Options for tasks

Expand
NameType

fileId

String

action

com.box.sdk.BoxTask.Action

dueAt

Date

message

String

taskId

String

info

com.box.sdk.BoxTask.Info

assignTo

com.box.sdk.BoxUser

taskAssignmentId

String

52.4.9. Endpoint Prefix users

For information on Box users see https://developer.box.com/reference#user-object. The following endpoints can be invoked with the prefix users as follows:

box:users/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

getCurrentUser

currentUser

 

com.box.sdk.BoxUser

getAllEnterpriseOrExternalUsers

users

filterTerm, [fields]

com.box.sdk.BoxUser

createAppUser

create

name, [params]

com.box.sdk.BoxUser

createEnterpriseUser

create

login, name, [params]

com.box.sdk.BoxUser

deleteUser

delete

userId, notifyUser, force

 

getUserEmailAlias

emailAlias

userId

com.box.sdk.BoxUser

deleteUserEmailAlias

deleteEmailAlias

userId, emailAliasId

java.util.List

getUserInfo

info

userId

com.box.sdk.BoxUser.Info

updateUserInfo

updateInfo

userId, info

com.box.sdk.BoxUser

moveFolderToUser

-

userId, sourceUserId

com.box.sdk.BoxFolder.Info

URI Options for users

Expand
NameType

defaultRequest

com.box.restclientv2.requestsbase.BoxDefaultRequestObject

emailAliasRequest

com.box.boxjavalibv2.requests.requestobjects.BoxEmailAliasRequestObject

emailId

String

filterTerm

String

folderId

String

simpleUserRequest

com.box.boxjavalibv2.requests.requestobjects.BoxSimpleUserRequestObject

userDeleteRequest

com.box.boxjavalibv2.requests.requestobjects.BoxUserDeleteRequestObject

userId

String

userRequest

com.box.boxjavalibv2.requests.requestobjects.BoxUserRequestObject

userUpdateLoginRequest

com.box.boxjavalibv2.requests.requestobjects.BoxUserUpdateLoginRequestObject

52.5. Consumer Endpoints:

For more information on Box events see https://developer.box.com/reference#events. Consumer endpoints can only use the endpoint prefix events as shown in the example next.

box:events/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

events

 

[startingPosition]

com.box.sdk.BoxEvent

URI Options for events

Expand
NameType

startingPosition

Long

52.6. Message header

Any of the options can be provided in a message header for producer endpoints with CamelBox. prefix.

52.7. Message body

All result message bodies utilize objects provided by the Box Java SDK. Producer endpoints can specify the option name for incoming message body in the inBody endpoint parameter.

52.8. Samples

The following route uploads new files to the user’s root folder:

from("file:...")
    .to("box://files/upload/inBody=fileUploadRequest");
Copy to Clipboard Toggle word wrap

The following route polls user’s account for updates:

from("box://events/listen?startingPosition=-1")
    .to("bean:blah");
Copy to Clipboard Toggle word wrap

The following route uses a producer with dynamic header options. The fileId property has the Box file id and the output property has the output stream of the file contents, so they are assigned to the CamelBox.fileId header and CamelBox.output header respectively as follows:

from("direct:foo")
    .setHeader("CamelBox.fileId", header("fileId"))
    .setHeader("CamelBox.output", header("output"))
    .to("box://files/download")
    .to("file://...");
Copy to Clipboard Toggle word wrap

Chapter 53. Braintree Component

Available as of Camel version 2.17

The Braintree component provides access to Braintree Payments trough through theirs Java SDK.

All client applications need API credential in order to process payments. In order to use camel-braintree with your account, you’ll need to create a new Sandbox or Production account.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-braintree</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

 

53.1. Braintree Options

The Braintree component supports 2 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (common)

To use the shared configuration

 

BraintreeConfiguration

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Braintree endpoint is configured using URI syntax:

braintree:apiName/methodName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

53.1.1. Path Parameters (2 parameters):

Expand
NameDescriptionDefaultType

apiName

Required What kind of operation to perform

 

BraintreeApiName

methodName

What sub operation to use for the selected operation

 

String

53.1.2. Query Parameters (14 parameters):

Expand
NameDescriptionDefaultType

environment (common)

The environment Either SANDBOX or PRODUCTION

 

String

inBody (common)

Sets the name of a parameter to be passed in the exchange In Body

 

String

merchantId (common)

The merchant id provided by Braintree.

 

String

privateKey (common)

The private key provided by Braintree.

 

String

publicKey (common)

The public key provided by Braintree.

 

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

accessToken (advanced)

The access token granted by a merchant to another in order to process transactions on their behalf. Used in place of environment, merchant id, public key and private key fields.

 

String

httpReadTimeout (advanced)

Set read timeout for http calls.

 

Integer

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

httpLogLevel (logging)

Set logging level for http calls, see java.util.logging.Level

 

String

proxyHost (proxy)

The proxy host

 

String

proxyPort (proxy)

The proxy port

 

Integer

53.2. URI format

 

braintree://endpoint-prefix/endpoint?[options]
Copy to Clipboard Toggle word wrap

 

Endpoint prefix can be one of:

  • addOn
  • address
  • clientToken
  • creditCardverification
  • customer
  • discount
  • merchantAccount
  • paymentmethod
  • paymentmethodNonce
  • plan
  • settlementBatchSummary
  • subscription
  • transaction
  • webhookNotification

 

53.3. BraintreeComponent

The Braintree Component can be configured with the options below. These options can be provided using the component’s bean property configuration of type org.apache.camel.component.braintree.BraintreeConfiguration.

Expand
OptionTypeDescription

environment

String

Value that specifies where requests should be directed – sandbox or production

merchantId

String

A unique identifier for your gateway account, which is different than your merchant account ID

publicKey

String

User-specific public identifier

privateKey

String

User-specific secure identifier that should not be shared – even with us!

accessToken

String

Token granted to a merchant using Braintree Auth allowing them to process transactions on another’s behalf. Used in place of the environment, merchantId, publicKey and privateKey options.

All the options above are provided by Braintree Payments

53.4. Producer Endpoints:

Producer endpoints can use endpoint prefixes followed by endpoint names and associated options described next. A shorthand alias can be used for some endpoints. The endpoint URI MUST contain a prefix.

Endpoint options that are not mandatory are denoted by []. When there are no mandatory options for an endpoint, one of the set of [] options MUST be provided. Producer endpoints can also use a special option inBody that in turn should contain the name of the endpoint option whose value will be contained in the Camel Exchange In message.

Any of the endpoint options can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format CamelBraintree.<option>. Note that the inBody option overrides message header, i.e. the endpoint option inBody=option would override a CamelBraintree.option header.

For more information on the endpoints and options see Braintree references at https://developers.braintreepayments.com/reference/overview

 

53.4.1. Endpoint prefix addOn

The following endpoints can be invoked with the prefix addOn as follows:

 

braintree://addOn/endpoint
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

all

 

 

List<com.braintreegateway.Addon>

53.4.2. Endpoint prefix address

The following endpoints can be invoked with the prefix address as follows:

 

braintree://address/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

create

 

customerId, request

com.braintreegateway.Result<com.braintreegateway.Address>

delete

 

customerId, id

com.braintreegateway.Result<com.braintreegateway.Address> 

find

 

customerId, id

com.braintreegateway.Address

update

 

customerId, id, request

com.braintreegateway.Result<com.braintreegateway.Address> 

URI Options for address

Expand
NameType

customerId

String

request

com.braintreegateway.AddressRequest

id

String

53.4.3. Endpoint prefix clientToken

The following endpoints can be invoked with the prefix clientToken as follows:

 

braintree://clientToken/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

generate

 

 request

String

URI Options for clientToken

Expand
NameType

request

com.braintreegateway.ClientTokenrequest

53.4.4. Endpoint prefix creditCardVerification

The following endpoints can be invoked with the prefix creditCardverification as follows:

 

braintree://creditCardVerification/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

find

 

 id

com.braintreegateway.CreditCardVerification

search

 

query

com.braintreegateway.ResourceCollection<com.braintreegateway.CreditCardVerification>

URI Options for creditCardVerification

Expand
NameType

id

String

query

com.braintreegateway.CreditCardVerificationSearchRequest

53.4.5. Endpoint prefix customer

The following endpoints can be invoked with the prefix customer as follows:

 

braintree://customer/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

all

 

 

 

create

 

request

com.braintreegateway.Result<com.braintreegateway.Customer>

delete

 

id

com.braintreegateway.Result<com.braintreegateway.Customer>

find

 

id

com.braintreegateway.Customer

search

 

query

com.braintreegateway.ResourceCollection<com.braintreegateway.Customer>

update

 

id, request

com.braintreegateway.Result<com.braintreegateway.Customer>

URI Options for customer

Expand
NameType

id

String

request

com.braintreegateway.CustomerRequest

query

com.braintreegateway.CustomerSearchRequest

53.4.6. Endpoint prefix discount

The following endpoints can be invoked with the prefix discount as follows:

 

braintree://discount/endpoint
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

all

 

 

List<com.braintreegateway.Discount>

+
Copy to Clipboard Toggle word wrap
+
Copy to Clipboard Toggle word wrap

53.4.7. Endpoint prefix merchantAccount

The following endpoints can be invoked with the prefix merchantAccount as follows:

 

braintree://merchantAccount/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

create

 

request

com.braintreegateway.Result<com.braintreegateway.MerchantAccount>

createForCurrency

 

currencyRequest

com.braintreegateway.Result<com.braintreegateway.MerchantAccount>

find

 

id

com.braintreegateway.MerchantAccount

update

 

id, request

com.braintreegateway.Result<com.braintreegateway.MerchantAccount>

URI Options for merchantAccount

Expand
NameType

id

String

request

com.braintreegateway.MerchantAccountRequest

currencyRequest

com.braintreegateway.MerchantAccountCreateForCurrencyRequest

53.4.8. Endpoint prefix paymentMethod

The following endpoints can be invoked with the prefix paymentMethod as follows:

 

braintree://paymentMethod/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

create

 

request

com.braintreegateway.Result<com.braintreegateway.PaymentMethod>

delete

 

token, deleteRequest

com.braintreegateway.Result<com.braintreegateway.PaymentMethod>

find

 

token

com.braintreegateway.PaymentMethod

update

 

token, request

com.braintreegateway.Result<com.braintreegateway.PaymentMethod>

URI Options for paymentMethod

Expand
NameType

token

String

request

com.braintreegateway.PaymentMethodRequest

deleteRequest

com.braintreegateway.PaymentMethodDeleteRequest

53.4.9. Endpoint prefix paymentMethodNonce

The following endpoints can be invoked with the prefix paymentMethodNonce as follows:

 

braintree://paymentMethodNonce/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

create

 

paymentMethodToken

com.braintreegateway.Result<com.braintreegateway.PaymentMethodNonce>

find

 

paymentMethodNonce

com.braintreegateway.PaymentMethodNonce

URI Options for paymentMethodNonce

Expand
NameType

paymentMethodToken

String

paymentMethodNonce

String

53.4.10. Endpoint prefix plan

The following endpoints can be invoked with the prefix plan as follows:

 

braintree://plan/endpoint
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

all

 

 

List<com.braintreegateway.Plan>

 

53.4.11. Endpoint prefix settlementBatchSummary

The following endpoints can be invoked with the prefix settlementBatchSummary as follows:

 

braintree://settlementBatchSummary/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

generate

 

 request

com.braintreegateway.Result<com.braintreegateway.SettlementBatchSummary>

URI Options for settlementBatchSummary

Expand
NameType

settlementDate

Calendar

groupByCustomField

String

53.4.12. Endpoint prefix subscription

The following endpoints can be invoked with the prefix subscription as follows:

 

braintree://subscription/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

cancel

 

 id

 com.braintreegateway.Result<com.braintreegateway.Subscription>

create

 

request

com.braintreegateway.Result<com.braintreegateway.Subscription>

delete

 

customerId, id

com.braintreegateway.Result<com.braintreegateway.Subscription>

find

 

id

com.braintreegateway.Subscription

retryCharge

 

subscriptionId, amount

com.braintreegateway.Result<com.braintreegateway.Transaction>

search

 

searchRequest

com.braintreegateway.ResourceCollection<com.braintreegateway.Subscription>

update

 

id, request

com.braintreegateway.Result<com.braintreegateway.Subscription>

URI Options for subscription

Expand
NameType

id

String

request

com.braintreegateway.SubscriptionRequest

customerId

String

subscriptionId

String

amount

BigDecimal

searchRequest

com.braintreegateway.SubscriptionSearchRequest.

 

53.4.13. Endpoint prefix transaction

The following endpoints can be invoked with the prefix transaction as follows:

 

braintree://transaction/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

cancelRelease

 

id

com.braintreegateway.Result<com.braintreegateway.Transaction>

cloneTransaction

 

id, cloneRequest

com.braintreegateway.Result<com.braintreegateway.Transaction>

credit

 

request

com.braintreegateway.Result<com.braintreegateway.Transaction>

find

 

id

com.braintreegateway.Transaction

holdInEscrow

 

id

com.braintreegateway.Result<com.braintreegateway.Transaction>

releaseFromEscrow

 

id

com.braintreegateway.Result<com.braintreegateway.Transaction>

refund

 

id, amount, refundRequest

com.braintreegateway.Result<com.braintreegateway.Transaction>

sale

 

request

com.braintreegateway.Result<com.braintreegateway.Transaction>

search

 

query

com.braintreegateway.ResourceCollection<com.braintreegateway.Transaction>

submitForPartialSettlement

 

id, amount

com.braintreegateway.Result<com.braintreegateway.Transaction>

submitForSettlement

 

id, amount, request

com.braintreegateway.Result<com.braintreegateway.Transaction>

voidTransaction

 

id

com.braintreegateway.Result<com.braintreegateway.Transaction>

URI Options for transaction

Expand
NameType

id

String

request

com.braintreegateway.TransactionCloneRequest

cloneRequest

com.braintreegateway.TransactionCloneRequest

refundRequest

com.braintreegateway.TransactionRefundRequest

amount

BigDecimal

query

com.braintreegateway.TransactionSearchRequest

53.4.14. Endpoint prefix webhookNotification

The following endpoints can be invoked with the prefix webhookNotification as follows:

 

braintree://webhookNotification/endpoint?[options]
Copy to Clipboard Toggle word wrap
Expand
EndpointShorthand AliasOptionsResult Body Type

parse

 

 signature, payload

com.braintreegateway.WebhookNotification

verify

 

challenge

String

URI Options for webhookNotification

Expand
NameType

signature

String

payload

String

challenge

String

 

53.5. Consumer Endpoints

Any of the producer endpoints can be used as a consumer endpoint. Consumer endpoints can use Scheduled Poll Consumer Options with a consumer. prefix to schedule endpoint invocation. By default Consumer endpoints that return an array or collection will generate one exchange per element, and their routes will be executed once for each exchange. To change this behavior use the property consumer.splitResults=true to return a single exchange for the entire list or array. 

53.6. Message Headers

Any URI option can be provided in a message header for producer endpoints with a CamelBraintree. prefix.

53.7. Message body

All result message bodies utilize objects provided by the Braintree Java SDK. Producer endpoints can specify the option name for incoming message body in the inBody endpoint parameter.

 

 

53.8. Examples

Blueprint

<?xml version="1.0"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0"
           xsi:schemaLocation="
             http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0 http://aries.apache.org/schemas/blueprint-cm/blueprint-cm-1.0.0.xsd
             http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
             http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">


    <cm:property-placeholder id="placeholder" persistent-id="camel.braintree">
    </cm:property-placeholder>

    <bean id="braintree" class="org.apache.camel.component.braintree.BraintreeComponent">
        <property name="configuration">
            <bean class="org.apache.camel.component.braintree.BraintreeConfiguration">
                <property name="environment" value="${environment}"/>
                <property name="merchantId" value="${merchantId}"/>
                <property name="publicKey" value="${publicKey}"/>
                <property name="privateKey" value="${privateKey}"/>
            </bean>
        </property>
    </bean>

    <camelContext trace="true" xmlns="http://camel.apache.org/schema/blueprint" id="braintree-example-context">
        <route id="braintree-example-route">
            <from uri="direct:generateClientToken"/>
            <to uri="braintree://clientToken/generate"/>
            <to uri="stream:out"/>
        </route>
    </camelContext>

</blueprint>
Copy to Clipboard Toggle word wrap

53.9. See Also

* Configuring Camel * Component * Endpoint * Getting Started

 

 

Chapter 54. Browse Component

Available as of Camel version 1.3

The Browse component provides a simple BrowsableEndpoint which can be useful for testing, visualisation tools or debugging. The exchanges sent to the endpoint are all available to be browsed.

54.1. URI format

browse:someName[?options]
Copy to Clipboard Toggle word wrap

Where someName can be any string to uniquely identify the endpoint.

54.2. Options

The Browse component has no options.

The Browse endpoint is configured using URI syntax:

browse:name
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

54.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

name

Required A name which can be any string to uniquely identify the endpoint

 

String

54.2.2. Query Parameters (4 parameters):

Expand
NameDescriptionDefaultType

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN/ERROR level and ignored.

false

boolean

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options is not in use. By default the consumer will deal with exceptions, that will be logged at WARN/ERROR level and ignored.

 

ExceptionHandler

exchangePattern (consumer)

Sets the default exchange pattern when creating an exchange.

 

ExchangePattern

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

54.3. Sample

In the route below, we insert a browse: component to be able to browse the Exchanges that are passing through:

from("activemq:order.in").to("browse:orderReceived").to("bean:processOrder");
Copy to Clipboard Toggle word wrap

We can now inspect the received exchanges from within the Java code:

private CamelContext context;

public void inspectRecievedOrders() {
    BrowsableEndpoint browse = context.getEndpoint("browse:orderReceived", BrowsableEndpoint.class);
    List<Exchange> exchanges = browse.getExchanges();

    // then we can inspect the list of received exchanges from Java
    for (Exchange exchange : exchanges) {
        String payload = exchange.getIn().getBody();
        // do something with payload
    }
}
Copy to Clipboard Toggle word wrap

54.4. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started

Chapter 55. EHCache Component (deprecated)

Available as of Camel version 2.1

The cache component enables you to perform caching operations using EHCache as the Cache Implementation. The cache itself is created on demand or if a cache of that name already exists then it is simply utilized with its original settings.

This component supports producer and event based consumer endpoints.

The Cache consumer is an event based consumer and can be used to listen and respond to specific cache activities. If you need to perform selections from a pre-existing cache, use the processors defined for the cache component.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-cache</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

55.1. URI format

cache://cacheName[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?option=value&option=#beanRef&…​

55.2. Options

The EHCache component supports 4 options which are listed below.

Expand
NameDescriptionDefaultType

cacheManagerFactory (advanced)

To use the given CacheManagerFactory for creating the CacheManager. By default the DefaultCacheManagerFactory is used.

 

CacheManagerFactory

configuration (common)

Sets the Cache configuration

 

CacheConfiguration

configurationFile (common)

Sets the location of the ehcache.xml file to load from classpath or file system. By default the file is loaded from classpath:ehcache.xml

classpath:ehcache.xml

String

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The EHCache endpoint is configured using URI syntax:

cache:cacheName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

55.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

cacheName

Required Name of the cache

 

String

55.2.2. Query Parameters (19 parameters):

Expand
NameDescriptionDefaultType

diskExpiryThreadInterval Seconds (common)

The number of seconds between runs of the disk expiry thread.

 

long

diskPersistent (common)

Whether the disk store persists between restarts of the application.

false

boolean

diskStorePath (common)

Deprecated This parameter is ignored. CacheManager sets it using setter injection.

 

String

eternal (common)

Sets whether elements are eternal. If eternal, timeouts are ignored and the element never expires.

false

boolean

key (common)

The default key to use. If a key is provided in the message header, then the key from the header takes precedence.

 

String

maxElementsInMemory (common)

The number of elements that may be stored in the defined cache in memory.

1000

int

memoryStoreEvictionPolicy (common)

Which eviction strategy to use when maximum number of elements in memory is reached. The strategy defines which elements to be removed. LRU - Lest Recently Used LFU - Lest Frequently Used FIFO - First In First Out

LFU

MemoryStoreEviction Policy

objectCache (common)

Whether to turn on allowing to store non serializable objects in the cache. If this option is enabled then overflow to disk cannot be enabled as well.

false

boolean

operation (common)

The default cache operation to use. If an operation in the message header, then the operation from the header takes precedence.

 

String

overflowToDisk (common)

Specifies whether cache may overflow to disk

true

boolean

timeToIdleSeconds (common)

The maximum amount of time between accesses before an element expires

300

long

timeToLiveSeconds (common)

The maximum time between creation time and when an element expires. Is used only if the element is not eternal

300

long

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

cacheLoaderRegistry (advanced)

To configure cache loader using the CacheLoaderRegistry

 

CacheLoaderRegistry

cacheManagerFactory (advanced)

To use a custom CacheManagerFactory for creating the CacheManager to be used by this endpoint. By default the CacheManagerFactory configured on the component is used.

 

CacheManagerFactory

eventListenerRegistry (advanced)

To configure event listeners using the CacheEventListenerRegistry

 

CacheEventListener Registry

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

55.3. Sending/Receiving Messages to/from the cache

55.3.1. Message Headers up to Camel 2.7

Expand
HeaderDescription

CACHE_OPERATION

The operation to be performed on the cache. Valid options are

* GET * CHECK * ADD * UPDATE * DELETE * DELETEALL
GET and CHECK requires Camel 2.3 onwards.

CACHE_KEY

The cache key used to store the Message in the cache. The cache key is optional if the CACHE_OPERATION is DELETEALL

55.3.2. Message Headers Camel 2.8+

Header changes in Camel 2.8

The header names and supported values have changed to be prefixed with 'CamelCache' and use mixed case. This makes them easier to identify and keep separate from other headers. The CacheConstants variable names remain unchanged, just their values have been changed. Also, these headers are now removed from the exchange after the cache operation is performed.

Expand
HeaderDescription

CamelCacheOperation

The operation to be performed on the cache. The valid options are

* CamelCacheGet * CamelCacheCheck * CamelCacheAdd * CamelCacheUpdate * CamelCacheDelete * CamelCacheDeleteAll

CamelCacheKey

The cache key used to store the Message in the cache. The cache key is optional if the CamelCacheOperation is CamelCacheDeleteAll

The CamelCacheAdd and CamelCacheUpdate operations support additional headers:

Expand
HeaderTypeDescription

CamelCacheTimeToLive

Integer

Camel 2.11: Time to live in seconds.

CamelCacheTimeToIdle

Integer

Camel 2.11: Time to idle in seconds.

CamelCacheEternal

Boolean

Camel 2.11: Whether the content is eternal.

55.3.3. Cache Producer

Sending data to the cache involves the ability to direct payloads in exchanges to be stored in a pre-existing or created-on-demand cache. The mechanics of doing this involve

  • setting the Message Exchange Headers shown above.
  • ensuring that the Message Exchange Body contains the message directed to the cache

55.3.4. Cache Consumer

Receiving data from the cache involves the ability of the CacheConsumer to listen on a pre-existing or created-on-demand Cache using an event Listener and receive automatic notifications when any cache activity take place (i.e CamelCacheGet/CamelCacheUpdate/CamelCacheDelete/CamelCacheDeleteAll). Upon such an activity taking place

  • an exchange containing Message Exchange Headers and a Message Exchange Body containing the just added/updated payload is placed and sent.
  • in case of a CamelCacheDeleteAll operation, the Message Exchange Header CamelCacheKey and the Message Exchange Body are not populated.

55.3.5. Cache Processors

There are a set of nice processors with the ability to perform cache lookups and selectively replace payload content at the

  • body
  • token
  • xpath level

55.4. Cache Usage Samples

55.4.1. Example 1: Configuring the cache

from("cache://MyApplicationCache" +
          "?maxElementsInMemory=1000" +
          "&memoryStoreEvictionPolicy=" +
              "MemoryStoreEvictionPolicy.LFU" +
          "&overflowToDisk=true" +
          "&eternal=true" +
          "&timeToLiveSeconds=300" +
          "&timeToIdleSeconds=true" +
          "&diskPersistent=true" +
          "&diskExpiryThreadIntervalSeconds=300")
Copy to Clipboard Toggle word wrap

55.4.2. Example 2: Adding keys to the cache

RouteBuilder builder = new RouteBuilder() {
    public void configure() {
     from("direct:start")
     .setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_ADD))
     .setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson"))
     .to("cache://TestCache1")
   }
};
Copy to Clipboard Toggle word wrap

55.4.3. Example 2: Updating existing keys in a cache

RouteBuilder builder = new RouteBuilder() {
    public void configure() {
     from("direct:start")
     .setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_UPDATE))
     .setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson"))
     .to("cache://TestCache1")
   }
};
Copy to Clipboard Toggle word wrap

55.4.4. Example 3: Deleting existing keys in a cache

RouteBuilder builder = new RouteBuilder() {
    public void configure() {
     from("direct:start")
     .setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_DELETE))
     .setHeader(CacheConstants.CACHE_KEY", constant("Ralph_Waldo_Emerson"))
     .to("cache://TestCache1")
   }
};
Copy to Clipboard Toggle word wrap

55.4.5. Example 4: Deleting all existing keys in a cache

RouteBuilder builder = new RouteBuilder() {
    public void configure() {
     from("direct:start")
     .setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_DELETEALL))
     .to("cache://TestCache1");
    }
};
Copy to Clipboard Toggle word wrap
RouteBuilder builder = new RouteBuilder() {
    public void configure() {
     from("cache://TestCache1")
     .process(new Processor() {
        public void process(Exchange exchange)
               throws Exception {
           String operation = (String) exchange.getIn().getHeader(CacheConstants.CACHE_OPERATION);
           String key = (String) exchange.getIn().getHeader(CacheConstants.CACHE_KEY);
           Object body = exchange.getIn().getBody();
           // Do something
        }
     })
   }
};
Copy to Clipboard Toggle word wrap
RouteBuilder builder = new RouteBuilder() {
   public void configure() {
     //Message Body Replacer
     from("cache://TestCache1")
     .filter(header(CacheConstants.CACHE_KEY).isEqualTo("greeting"))
     .process(new CacheBasedMessageBodyReplacer("cache://TestCache1","farewell"))
     .to("direct:next");

    //Message Token replacer
    from("cache://TestCache1")
    .filter(header(CacheConstants.CACHE_KEY).isEqualTo("quote"))
    .process(new CacheBasedTokenReplacer("cache://TestCache1","novel","#novel#"))
    .process(new CacheBasedTokenReplacer("cache://TestCache1","author","#author#"))
    .process(new CacheBasedTokenReplacer("cache://TestCache1","number","#number#"))
    .to("direct:next");

    //Message XPath replacer
    from("cache://TestCache1").
    .filter(header(CacheConstants.CACHE_KEY).isEqualTo("XML_FRAGMENT"))
    .process(new CacheBasedXPathReplacer("cache://TestCache1","book1","/books/book1"))
    .process (new CacheBasedXPathReplacer("cache://TestCache1","book2","/books/book2"))
    .to("direct:next");
   }
};
Copy to Clipboard Toggle word wrap

55.4.8. Example 7: Getting an entry from the Cache

from("direct:start")
    // Prepare headers
    .setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_GET))
    .setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson")).
    .to("cache://TestCache1").
    // Check if entry was not found
    .choice().when(header(CacheConstants.CACHE_ELEMENT_WAS_FOUND).isNull()).
        // If not found, get the payload and put it to cache
        .to("cxf:bean:someHeavyweightOperation").
        .setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_ADD))
        .setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson"))
        .to("cache://TestCache1")
    .end()
    .to("direct:nextPhase");
Copy to Clipboard Toggle word wrap

55.4.9. Example 8: Checking for an entry in the Cache

Note: The CHECK command tests existence of an entry in the cache but doesn’t place a message in the body.

from("direct:start")
    // Prepare headers
    .setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_CHECK))
    .setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson")).
    .to("cache://TestCache1").
    // Check if entry was not found
    .choice().when(header(CacheConstants.CACHE_ELEMENT_WAS_FOUND).isNull()).
        // If not found, get the payload and put it to cache
        .to("cxf:bean:someHeavyweightOperation").
        .setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_ADD))
        .setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson"))
        .to("cache://TestCache1")
    .end();
Copy to Clipboard Toggle word wrap

55.5. Management of EHCache

EHCache has its own statistics and management from JMX.

Here’s a snippet on how to expose them via JMX in a Spring application context:

<bean id="ehCacheManagementService" class="net.sf.ehcache.management.ManagementService" init-method="init" lazy-init="false">
  <constructor-arg>
    <bean class="net.sf.ehcache.CacheManager" factory-method="getInstance"/>
  </constructor-arg>
  <constructor-arg>
    <bean class="org.springframework.jmx.support.JmxUtils" factory-method="locateMBeanServer"/>
  </constructor-arg>
  <constructor-arg value="true"/>
  <constructor-arg value="true"/>
  <constructor-arg value="true"/>
  <constructor-arg value="true"/>
</bean>
Copy to Clipboard Toggle word wrap

Of course you can do the same thing in straight Java:

ManagementService.registerMBeans(CacheManager.getInstance(), mbeanServer, true, true, true, true);
Copy to Clipboard Toggle word wrap

You can get cache hits, misses, in-memory hits, disk hits, size stats this way. You can also change CacheConfiguration parameters on the fly.

55.6. Cache replication Camel 2.8

The Camel Cache component is able to distribute a cache across server nodes using several different replication mechanisms including: RMI, JGroups, JMS and Cache Server.

There are two different ways to make it work:

1. You can configure ehcache.xml manually

OR

2. You can configure these three options:

  • cacheManagerFactory
  • eventListenerRegistry
  • cacheLoaderRegistry

Configuring Camel Cache replication using the first option is a bit of hard work as you have to configure all caches separately. So in a situation when the all names of caches are not known, using ehcache.xml is not a good idea.

The second option is much better when you want to use many different caches as you do not need to define options per cache. This is because replication options are set per CacheManager and per CacheEndpoint. Also it is the only way when cache names are not know at the development phase.

Note: It might be useful to read the EHCache manual to get a better understanding of the Camel Cache replication mechanism.

55.6.1. Example: JMS cache replication

JMS replication is the most powerful and secured replication method. Used together with Camel Cache replication makes it also rather simple. An example is available on a separate page.

Chapter 56. Caffeine Cache Component

Available as of Camel version 2.20

The caffeine-cache component enables you to perform caching operations using The simple cache from Caffeine.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-caffeine</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

56.1. URI format

caffeine-cache://cacheName[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?option=value&option=#beanRef&…​

56.2. Options

The Caffeine Cache component supports 2 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

Sets the global component configuration

 

CaffeineConfiguration

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Caffeine Cache endpoint is configured using URI syntax:

caffeine-cache:cacheName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

56.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

cacheName

Required the cache name

 

String

56.2.2. Query Parameters (19 parameters):

Expand
NameDescriptionDefaultType

createCacheIfNotExist (common)

Configure if a cache need to be created if it does exist or can’t be pre-configured.

true

boolean

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

action (producer)

To configure the default cache action. If an action is set in the message header, then the operation from the header takes precedence.

 

String

cache (producer)

To configure the default an already instantianted cache to be used

 

Cache

cacheLoader (producer)

To configure a CacheLoader in case of a LoadCache use

 

CacheLoader

evictionType (producer)

Set the eviction Type for this cache

SIZE_BASED

EvictionType

expireAfterAccessTime (producer)

Set the expire After Access Time in case of time based Eviction (in seconds)

300

int

expireAfterWriteTime (producer)

Set the expire After Access Write in case of time based Eviction (in seconds)

300

int

initialCapacity (producer)

Set the initial Capacity for the cache

10000

int

key (producer)

To configure the default action key. If a key is set in the message header, then the key from the header takes precedence.

 

Object

maximumSize (producer)

Set the maximum size for the cache

10000

int

removalListener (producer)

Set a specific removal Listener for the cache

 

RemovalListener

statsCounter (producer)

Set a specific Stats Counter for the cache stats

 

StatsCounter

statsEnabled (producer)

To enable stats on the cache

false

boolean

keyType (advanced)

The cache key type, default java.lang.Object

java.lang.Object

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

valueType (advanced)

The cache value type, default java.lang.Object

java.lang.Object

String

Chapter 57. Caffeine LoadCache Component

Available as of Camel version 2.20

The caffeine-loadcache component enables you to perform caching operations using The Load cache from Caffeine.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-caffeine</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

57.1. URI format

caffeine-loadcache://cacheName[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?option=value&option=#beanRef&…​

57.2. Options

The Caffeine LoadCache component supports 2 options which are listed below.

Expand
NameDescriptionDefaultType

configuration (advanced)

Sets the global component configuration

 

CaffeineConfiguration

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Caffeine LoadCache endpoint is configured using URI syntax:

caffeine-loadcache:cacheName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

57.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

cacheName

Required the cache name

 

String

57.2.2. Query Parameters (19 parameters):

Expand
NameDescriptionDefaultType

createCacheIfNotExist (common)

Configure if a cache need to be created if it does exist or can’t be pre-configured.

true

boolean

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

action (producer)

To configure the default cache action. If an action is set in the message header, then the operation from the header takes precedence.

 

String

cache (producer)

To configure the default an already instantianted cache to be used

 

Cache

cacheLoader (producer)

To configure a CacheLoader in case of a LoadCache use

 

CacheLoader

evictionType (producer)

Set the eviction Type for this cache

SIZE_BASED

EvictionType

expireAfterAccessTime (producer)

Set the expire After Access Time in case of time based Eviction (in seconds)

300

int

expireAfterWriteTime (producer)

Set the expire After Access Write in case of time based Eviction (in seconds)

300

int

initialCapacity (producer)

Set the initial Capacity for the cache

10000

int

key (producer)

To configure the default action key. If a key is set in the message header, then the key from the header takes precedence.

 

Object

maximumSize (producer)

Set the maximum size for the cache

10000

int

removalListener (producer)

Set a specific removal Listener for the cache

 

RemovalListener

statsCounter (producer)

Set a specific Stats Counter for the cache stats

 

StatsCounter

statsEnabled (producer)

To enable stats on the cache

false

boolean

keyType (advanced)

The cache key type, default java.lang.Object

java.lang.Object

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

valueType (advanced)

The cache value type, default java.lang.Object

java.lang.Object

String

Chapter 58. Castor DataFormat (deprecated)

Available as of Camel version 2.1

Castor is a Data Format which uses the Castor XML library to unmarshal an XML payload into Java objects or to marshal Java objects into an XML payload.

As usually you can use either Java DSL or Spring XML to work with Castor Data Format.

58.1. Using the Java DSL

from("direct:order").
  marshal().castor().
  to("activemq:queue:order");
Copy to Clipboard Toggle word wrap

For example the following uses a named DataFormat of Castor which uses default Castor data binding features.

CastorDataFormat castor = new CastorDataFormat ();

from("activemq:My.Queue").
  unmarshal(castor).
  to("mqseries:Another.Queue");
Copy to Clipboard Toggle word wrap

If you prefer to use a named reference to a data format which can then be defined in your Registry such as via your Spring XML file. e.g.

from("activemq:My.Queue").
  unmarshal("mycastorType").
  to("mqseries:Another.Queue");
Copy to Clipboard Toggle word wrap

If you want to override default mapping schema by providing a mapping file you can set it as follows.

CastorDataFormat castor = new CastorDataFormat ();
castor.setMappingFile("mapping.xml");
Copy to Clipboard Toggle word wrap

Also if you want to have more control on Castor Marshaller and Unmarshaller you can access them as below.

castor.getMarshaller();
castor.getUnmarshaller();
Copy to Clipboard Toggle word wrap

58.2. Using Spring XML

The following example shows how to use Castor to unmarshal using Spring configuring the castor data type

<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="direct:start"/>
    <unmarshal>
      <castor validation="true" />
    </unmarshal>
    <to uri="mock:result"/>
  </route>
</camelContext>
Copy to Clipboard Toggle word wrap

This example shows how to configure the data type just once and reuse it on multiple routes. You have to set the <castor> element directly in <camelContext>.

<camelContext>
<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
  <dataFormats>
    <castor id="myCastor"/>
  </dataFormats>

  <route>
    <from uri="direct:start"/>
    <marshal ref="myCastor"/>
    <to uri="direct:marshalled"/>
  </route>
  <route>
    <from uri="direct:marshalled"/>
    <unmarshal ref="myCastor"/>
    <to uri="mock:result"/>
  </route>

</camelContext>
Copy to Clipboard Toggle word wrap

58.3. Options

The Castor dataformat supports 9 options which are listed below.

Expand
NameDefaultJava TypeDescription

mappingFile

 

String

Path to a Castor mapping file to load from the classpath.

whitelistEnabled

true

Boolean

Define if Whitelist feature is enabled or not

allowedUnmarshallObjects

 

String

Define the allowed objects to be unmarshalled. You can specify the FQN class name of allowed objects, and you can use comma to separate multiple entries. It is also possible to use wildcards and regular expression which is based on the pattern defined by link org.apache.camel.util.EndpointHelpermatchPattern(String, String). Denied objects takes precedence over allowed objects.

deniedUnmarshallObjects

 

String

Define the denied objects to be unmarshalled. You can specify the FQN class name of deined objects, and you can use comma to separate multiple entries. It is also possible to use wildcards and regular expression which is based on the pattern defined by link org.apache.camel.util.EndpointHelpermatchPattern(String, String). Denied objects takes precedence over allowed objects.

validation

true

Boolean

Whether validation is turned on or off. Is by default true.

encoding

UTF-8

String

Encoding to use when marshalling an Object to XML. Is by default UTF-8

packages

 

String[]

Add additional packages to Castor XmlContext

classes

 

String[]

Add additional class names to Castor XmlContext

contentTypeHeader

false

Boolean

Whether the data format should set the Content-Type header with the type from the data format if the data format is capable of doing so. For example application/xml for data formats marshalling to XML, or application/json for data formats marshalling to JSon etc.

58.4. Dependencies

To use Castor in your camel routes you need to add the a dependency on camel-castor which implements this data format.

If you use maven you could just add the following to your pom.xml, substituting the version number for the latest & greatest release (see the download page for the latest versions).

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-castor</artifactId>
  <version>x.x.x</version>
</dependency>
Copy to Clipboard Toggle word wrap

Chapter 59. Camel CDI

The Camel CDI component provides auto-configuration for Apache Camel using CDI as dependency injection framework based on convention-over-configuration. It auto-detects Camel routes available in the application and provides beans for common Camel primitives like EndpointFluentProducerTemplate, ProducerTemplate or TypeConverter. It implements standard Camel bean integration so that Camel annotations like @Consume@Produce and @PropertyInject can be used seamlessly in CDI beans. Besides, it bridges Camel events (e.g. RouteAddedEvent, CamelContextStartedEventExchangeCompletedEvent, …​) as CDI events and provides a CDI events endpoint that can be used to consume / produce CDI events from / to Camel routes.

While the Camel CDI component is available as of Camel 2.10, it’s been rewritten in Camel 2.17 to better fit into the CDI programming model. Hence some of the features like the Camel events to CDI events bridge and the CDI events endpoint only apply starting Camel 2.17.

More details on how to test Camel CDI applications are available in Camel CDI testing.

Important

camel-cdi is deprecated in OSGi and not supported. Use OSGi Blueprint if using Camel with OSGi.

59.1. Auto-configured Camel context

Camel CDI automatically deploys and configures a CamelContext bean. That CamelContext bean is automatically instantiated, configured and started (resp. stopped) when the CDI container initializes (resp. shuts down). It can be injected in the application, e.g.:

@Inject
CamelContext context;
Copy to Clipboard Toggle word wrap

That default CamelContext bean is qualified with the built-in @Default qualifier, is scoped @ApplicationScoped and is of type DefaultCamelContext.

Note that this bean can be customized programmatically and other Camel context beans can be deployed in the application as well.

59.2. Auto-detecting Camel routes

Camel CDI automatically collects all the RoutesBuilder beans in the application, instantiates and add them to the CamelContext bean instance when the CDI container initializes. For example, adding a Camel route is as simple as declaring a class, e.g.:

class MyRouteBean extends RouteBuilder {
 
    @Override
    public void configure() {
        from("jms:invoices").to("file:/invoices");
    }
}
Copy to Clipboard Toggle word wrap

Note that you can declare as many RoutesBuilder beans as you want. Besides, RouteContainer beans are also automatically collected, instantiated and added to the CamelContext bean instance managed by Camel CDI when the container initializes.

Available as of Camel 2.19

In some situations, it may be necessary to disable the auto-configuration of the RouteBuilder and RouteContainer beans. That can be achieved by observing for the CdiCamelConfiguration event, e.g.:

static void configuration(@Observes CdiCamelConfiguration configuration) {
    configuration.autoConfigureRoutes(false);
}
Copy to Clipboard Toggle word wrap

Similarly, it is possible to deactivate the automatic starting of the configured CamelContext beans, e.g.:

static void configuration(@Observes CdiCamelConfiguration configuration) {
    configuration.autoStartContexts(false);
}
Copy to Clipboard Toggle word wrap

59.3. Auto-configured Camel primitives

Camel CDI provides beans for common Camel primitives that can be injected in any CDI beans, e.g.:

@Inject
@Uri("direct:inbound")
ProducerTemplate producerTemplate;

@Inject
@Uri("direct:inbound")
FluentProducerTemplate fluentProducerTemplate;

@Inject
MockEndpoint outbound; // URI defaults to the member name, i.e. mock:outbound

@Inject
@Uri("direct:inbound")
Endpoint endpoint;

@Inject
TypeConverter converter;
Copy to Clipboard Toggle word wrap

59.4. Camel context configuration

If you just want to change the name of the default CamelContext bean, you can used the @ContextName qualifier provided by Camel CDI, e.g.:

@ContextName("camel-context")
class MyRouteBean extends RouteBuilder {
 
    @Override
    public void configure() {
        from("jms:invoices").to("file:/invoices");
    }
}
Copy to Clipboard Toggle word wrap

Else, if more customization is needed, any CamelContext class can be used to declare a custom Camel context bean. Then, the @PostConstruct and @PreDestroy lifecycle callbacks can be done to do the customization, e.g.:

@ApplicationScoped
class CustomCamelContext extends DefaultCamelContext {

    @PostConstruct
    void customize() {
        // Set the Camel context name
        setName("custom");
        // Disable JMX
        disableJMX();
    }

    @PreDestroy
    void cleanUp() {
        // ...
    }
}
Copy to Clipboard Toggle word wrap

Producer and disposer methods can also be used as well to customize the Camel context bean, e.g.:

class CamelContextFactory {

    @Produces
    @ApplicationScoped
    CamelContext customize() {
        DefaultCamelContext context = new DefaultCamelContext();
        context.setName("custom");
        return context;
    }

    void cleanUp(@Disposes CamelContext context) {
        // ...
    }
}
Copy to Clipboard Toggle word wrap

Similarly, producer fields can be used, e.g.:

@Produces
@ApplicationScoped
CamelContext context = new CustomCamelContext();

class CustomCamelContext extends DefaultCamelContext {

    CustomCamelContext() {
        setName("custom");
    }
}
Copy to Clipboard Toggle word wrap

This pattern can be used for example to avoid having the Camel context routes started automatically when the container initializes by calling the setAutoStartup method, e.g.:

@ApplicationScoped
class ManualStartupCamelContext extends DefaultCamelContext {

    @PostConstruct
    void manual() {
        setAutoStartup(false);
    }
}
Copy to Clipboard Toggle word wrap

59.5. Multiple Camel contexts

Any number of CamelContext beans can actually be declared in the application as documented above. In that case, the CDI qualifiers declared on these CamelContext beans are used to bind the Camel routes and other Camel primitives to the corresponding Camel contexts. From example, if the following beans get declared:

@ApplicationScoped
@ContextName("foo")
class FooCamelContext extends DefaultCamelContext {
}

@ApplicationScoped
@BarContextQualifier
class BarCamelContext extends DefaultCamelContext {
}
 
@ContextName("foo")
class RouteAddedToFooCamelContext extends RouteBuilder {

    @Override
    public void configure() {
        // ...
    }
}
 
@BarContextQualifier
class RouteAddedToBarCamelContext extends RouteBuilder {

    @Override
    public void configure() {
        // ...
    }
}
 
@ContextName("baz")
class RouteAddedToBazCamelContext extends RouteBuilder {

    @Override
    public void configure() {
        // ...
    }
}
 
@MyOtherQualifier
class RouteNotAddedToAnyCamelContext extends RouteBuilder {

    @Override
    public void configure() {
        // ...
    }
}
Copy to Clipboard Toggle word wrap

The RoutesBuilder beans qualified with @ContextName are automatically added to the corresponding CamelContext beans by Camel CDI. If no such CamelContext bean exists, it gets automatically created, as for the RouteAddedToBazCamelContext bean. Note this only happens for the @ContextName qualifier provided by Camel CDI. Hence the RouteNotAddedToAnyCamelContext bean qualified with the user-defined @MyOtherQualifier qualifier does not get added to any Camel contexts. That may be useful, for example, for Camel routes that may be required to be added later during the application execution.

Note

Since Camel version 2.17.0, Camel CDI is capable of managing any kind of CamelContext beans (e.g. DefaultCamelContext). In previous versions, it is only capable of managing beans of type CdiCamelContext so it is required to extend it.

The CDI qualifiers declared on the CamelContext beans are also used to bind the corresponding Camel primitives, e.g.:

@Inject
@ContextName("foo")
@Uri("direct:inbound")
ProducerTemplate producerTemplate;

@Inject
@ContextName("foo")
@Uri("direct:inbound")
FluentProducerTemplate fluentProducerTemplate;

@Inject
@BarContextQualifier
MockEndpoint outbound; // URI defaults to the member name, i.e. mock:outbound

@Inject
@ContextName("baz")
@Uri("direct:inbound")
Endpoint endpoint;
Copy to Clipboard Toggle word wrap

59.6. Configuration properties

To configure the sourcing of the configuration properties used by Camel to resolve properties placeholders, you can declare a PropertiesComponent bean qualified with @Named("properties"), e.g.:

@Produces
@ApplicationScoped
@Named("properties")
PropertiesComponent propertiesComponent() {
    Properties properties = new Properties();
    properties.put("property", "value");
    PropertiesComponent component = new PropertiesComponent();
    component.setInitialProperties(properties);
    component.setLocation("classpath:placeholder.properties");
    return component;
}
Copy to Clipboard Toggle word wrap

If you want to use DeltaSpike configuration mechanism you can declare the following PropertiesComponent bean:

@Produces
@ApplicationScoped
@Named("properties")
PropertiesComponent properties(PropertiesParser parser) {
    PropertiesComponent component = new PropertiesComponent();
    component.setPropertiesParser(parser);
    return component;
}

// PropertiesParser bean that uses DeltaSpike to resolve properties
static class DeltaSpikeParser extends DefaultPropertiesParser {
    @Override
    public String parseProperty(String key, String value, Properties properties) {
        return ConfigResolver.getPropertyValue(key);
    }
}
Copy to Clipboard Toggle word wrap

You can see the camel-example-cdi-properties example for a working example of a Camel CDI application using DeltaSpike configuration mechanism.

59.7. Auto-configured type converters

CDI beans annotated with the @Converter annotation are automatically registered into the deployed Camel contexts, e.g.:

@Converter
public class MyTypeConverter {

    @Converter
    public Output convert(Input input) {
        //...
    }
}
Copy to Clipboard Toggle word wrap

Note that CDI injection is supported within the type converters.

59.8. Camel bean integration

59.8.1. Camel annotations

As part of the Camel bean integration, Camel comes with a set of annotations that are seamlessly supported by Camel CDI. So you can use any of these annotations in your CDI beans, e.g.:

Expand
 Camel annotationCDI equivalent

Configuration property

@PropertyInject("key")
String value;
Copy to Clipboard Toggle word wrap

If using DeltaSpike configuration mechanism:

@Inject
@ConfigProperty(name = "key")
String value;
Copy to Clipboard Toggle word wrap

See configuration properties for more details.

Producer template injection (default Camel context)

@Produce(uri = "mock:outbound")
ProducerTemplate producer;

@Produce(uri = "mock:outbound")
FluentProducerTemplate producer;
Copy to Clipboard Toggle word wrap
@Inject
@Uri("direct:outbound")
ProducerTemplate producer;

@Produce(uri = "direct:outbound")
FluentProducerTemplate producer;
Copy to Clipboard Toggle word wrap

Endpoint injection (default Camel context)

@EndpointInject(uri = "direct:inbound")
Endpoint endpoint;
Copy to Clipboard Toggle word wrap
@Inject
@Uri("direct:inbound")
Endpoint endpoint;
Copy to Clipboard Toggle word wrap

Endpoint injection (Camel context by name)

@EndpointInject(uri = "direct:inbound",
                context = "foo")
Endpoint contextEndpoint;
Copy to Clipboard Toggle word wrap
@Inject
@ContextName("foo")
@Uri("direct:inbound")
Endpoint contextEndpoint;
Copy to Clipboard Toggle word wrap

Bean injection (by type)

@BeanInject
MyBean bean;
Copy to Clipboard Toggle word wrap
@Inject
MyBean bean;
Copy to Clipboard Toggle word wrap

Bean injection (by name)

@BeanInject("foo")
MyBean bean;
Copy to Clipboard Toggle word wrap
@Inject
@Named("foo")
MyBean bean;
Copy to Clipboard Toggle word wrap

POJO consuming

@Consume(uri = "seda:inbound")
void consume(@Body String body) {
    //...
}
Copy to Clipboard Toggle word wrap

 

59.8.2. Bean component

You can refer to CDI beans, either by type or name, From the Camel DSL, e.g. with the Java Camel DSL:

class MyBean {
    //...
}

from("direct:inbound").bean(MyBean.class);
Copy to Clipboard Toggle word wrap

Or to lookup a CDI bean by name from the Java DSL:

@Named("foo")
class MyNamedBean {
    //...
}

from("direct:inbound").bean("foo");
Copy to Clipboard Toggle word wrap

59.8.3. Referring beans from Endpoint URIs

When configuring endpoints using the URI syntax you can refer to beans in the Registry using the # notation. If the URI parameter value starts with a # sign then Camel CDI will lookup for a bean of the given type by name, e.g.:

from("jms:queue:{{destination}}?transacted=true&transactionManager=#jtaTransactionManager").to("...");
Copy to Clipboard Toggle word wrap

Having the following CDI bean qualified with @Named("jtaTransactionManager"):

@Produces
@Named("jtaTransactionManager")
PlatformTransactionManager createTransactionManager(TransactionManager transactionManager, UserTransaction userTransaction) {
    JtaTransactionManager jtaTransactionManager = new JtaTransactionManager();
    jtaTransactionManager.setUserTransaction(userTransaction);
    jtaTransactionManager.setTransactionManager(transactionManager);
    jtaTransactionManager.afterPropertiesSet();
    return jtaTransactionManager;
}
Copy to Clipboard Toggle word wrap

59.9. Camel events to CDI events

Available as of Camel 2.17

Camel provides a set of management events that can be subscribed to for listening to Camel context, service, route and exchange events. Camel CDI seamlessly translates these Camel events into CDI events that can be observed using CDI observer methods, e.g.:

void onContextStarting(@Observes CamelContextStartingEvent event) {
    // Called before the default Camel context is about to start
}
Copy to Clipboard Toggle word wrap

As of Camel 2.18, it is possible to observe events for a particular route (RouteAddedEvent, RouteStartedEvent, RouteStoppedEvent and RouteRemovedEvent) should it have an explicit defined, e.g.:

from("...").routeId("foo").to("...");

void onRouteStarted(@Observes @Named("foo") RouteStartedEvent event) {
    // Called after the route "foo" has started
}
Copy to Clipboard Toggle word wrap

When multiple Camel contexts exist in the CDI container, the Camel context bean qualifiers, like @ContextName, can be used to refine the observer method resolution to a particular Camel context as specified in observer resolution, e.g.:

void onRouteStarted(@Observes @ContextName("foo") RouteStartedEvent event) {
    // Called after the route 'event.getRoute()' for the Camel context 'foo' has started
}
 
void onContextStarted(@Observes @Manual CamelContextStartedEvent event) {
    // Called after the the Camel context qualified with '@Manual' has started
}
Copy to Clipboard Toggle word wrap

Similarly, the @Default qualifier can be used to observe Camel events for the default Camel context if multiples contexts exist, e.g.:

void onExchangeCompleted(@Observes @Default ExchangeCompletedEvent event) {
    // Called after the exchange 'event.getExchange()' processing has completed
}
Copy to Clipboard Toggle word wrap

In that example, if no qualifier is specified, the @Any qualifier is implicitly assumed, so that corresponding events for all the Camel contexts get received.

Note that the support for Camel events translation into CDI events is only activated if observer methods listening for Camel events are detected in the deployment, and that per Camel context.

59.10. CDI events endpoint

Available as of Camel 2.17

The CDI event endpoint bridges the CDI events with the Camel routes so that CDI events can be seamlessly observed / consumed (resp. produced / fired) from Camel consumers (resp. by Camel producers).

The CdiEventEndpoint<T> bean provided by Camel CDI can be used to observe / consume CDI events whose event type is T, for example:

@Inject
CdiEventEndpoint<String> cdiEventEndpoint;

from(cdiEventEndpoint).log("CDI event received: ${body}");
Copy to Clipboard Toggle word wrap

This is equivalent to writing:

@Inject
@Uri("direct:event")
ProducerTemplate producer;

void observeCdiEvents(@Observes String event) {
    producer.sendBody(event);
}

from("direct:event").log("CDI event received: ${body}");
Copy to Clipboard Toggle word wrap

Conversely, the CdiEventEndpoint<T> bean can be used to produce / fire CDI events whose event type is T, for example:

@Inject
CdiEventEndpoint<String> cdiEventEndpoint;

from("direct:event").to(cdiEventEndpoint).log("CDI event sent: ${body}");
Copy to Clipboard Toggle word wrap

This is equivalent to writing:

@Inject
Event<String> event;

from("direct:event").process(new Processor() {
    @Override
    public void process(Exchange exchange) {
        event.fire(exchange.getBody(String.class));
    }
}).log("CDI event sent: ${body}");
Copy to Clipboard Toggle word wrap

Or using a Java 8 lambda expression:

@Inject
Event<String> event;

from("direct:event")
    .process(exchange -> event.fire(exchange.getIn().getBody(String.class)))
    .log("CDI event sent: ${body}");
Copy to Clipboard Toggle word wrap

The type variable T (resp. the qualifiers) of a particular CdiEventEndpoint<T> injection point are automatically translated into the parameterized event type (resp. into the event qualifiers) e.g.:

@Inject
@FooQualifier
CdiEventEndpoint<List<String>> cdiEventEndpoint;

from("direct:event").to(cdiEventEndpoint);

void observeCdiEvents(@Observes @FooQualifier List<String> event) {
    logger.info("CDI event: {}", event);
}
Copy to Clipboard Toggle word wrap

When multiple Camel contexts exist in the CDI container, the Camel context bean qualifiers, like @ContextName, can be used to qualify the CdiEventEndpoint<T> injection points, e.g.:

@Inject
@ContextName("foo")
CdiEventEndpoint<List<String>> cdiEventEndpoint;
// Only observes / consumes events having the @ContextName("foo") qualifier
from(cdiEventEndpoint).log("Camel context (foo) > CDI event received: ${body}");
// Produces / fires events with the @ContextName("foo") qualifier
from("...").to(cdiEventEndpoint);

void observeCdiEvents(@Observes @ContextName("foo") List<String> event) {
    logger.info("Camel context (foo) > CDI event: {}", event);
}
Copy to Clipboard Toggle word wrap

Note that the CDI event Camel endpoint dynamically adds an observer method for each unique combination of event type and event qualifiers and solely relies on the container typesafe observer resolution, which leads to an implementation as efficient as possible.

Besides, as the impedance between the typesafe nature of CDI and the dynamic nature of the Camel component model is quite high, it is not possible to create an instance of the CDI event Camel endpoint via URIs. Indeed, the URI format for the CDI event component is:

cdi-event://PayloadType<T1,...,Tn>[?qualifiers=QualifierType1[,...[,QualifierTypeN]...]]
Copy to Clipboard Toggle word wrap

With the authority PayloadType (resp. the QualifierType) being the URI escaped fully qualified name of the payload (resp. qualifier) raw type followed by the type parameters section delimited by angle brackets for payload parameterized type. Which leads to unfriendly URIs, e.g.:

cdi-event://org.apache.camel.cdi.example.EventPayload%3Cjava.lang.Integer%3E?qualifiers=org.apache.camel.cdi.example.FooQualifier%2Corg.apache.camel.cdi.example.BarQualifier
Copy to Clipboard Toggle word wrap

But more fundamentally, that would prevent efficient binding between the endpoint instances and the observer methods as the CDI container doesn’t have any ways of discovering the Camel context model during the deployment phase.

59.11. Camel XML configuration import

Available as of Camel 2.18

While CDI favors a typesafe dependency injection mechanism, it may be useful to reuse existing Camel XML configuration files into a Camel CDI application. In other use cases, it might be handy to rely on the Camel XML DSL to configure its Camel context(s).

You can use the @ImportResource annotation that’s provided by Camel CDI on any CDI beans and Camel CDI will automatically load the Camel XML configuration at the specified locations, e.g.:

@ImportResource("camel-context.xml")
class MyBean {
}
Copy to Clipboard Toggle word wrap

Camel CDI will load the resources at the specified locations from the classpath (other protocols may be added in the future).

Every CamelContext elements and other Camel primitives from the imported resources are automatically deployed as CDI beans during the container bootstrap so that they benefit from the auto-configuration provided by Camel CDI and become available for injection at runtime. If such an element has an explicit id attribute set, the corresponding CDI bean is qualified with the @Named qualifier, e.g., given the following Camel XML configuration:

<camelContext id="foo">
    <endpoint id="bar" uri="seda:inbound">
        <property key="queue" value="#queue"/>
        <property key="concurrentConsumers" value="10"/>
    </endpoint>
<camelContext/>
Copy to Clipboard Toggle word wrap

The corresponding CDI beans are automatically deployed and can be injected, e.g.:

@Inject
@ContextName("foo")
CamelContext context;

@Inject
@Named("bar")
Endpoint endpoint;
Copy to Clipboard Toggle word wrap

Note that the CamelContext beans are automatically qualified with both the @Named and @ContextName qualifiers. If the imported CamelContext element doesn’t have an id attribute, the corresponding bean is deployed with the built-in @Default qualifier.

Conversely, CDI beans deployed in the application can be referred to from the Camel XML configuration, usually using the ref attribute, e.g., given the following bean declared:

@Produces
@Named("baz")
Processor processor = exchange -> exchange.getIn().setHeader("qux", "quux");
Copy to Clipboard Toggle word wrap

A reference to that bean can be declared in the imported Camel XML configuration, e.g.:

<camelContext id="foo">
    <route>
        <from uri="..."/>
        <process ref="baz"/>
    </route>
<camelContext/>
Copy to Clipboard Toggle word wrap

59.12. Transaction support

Available as of Camel 2.19

Camel CDI provides support for Camel transactional client using JTA.

That support is optional hence you need to have JTA in your application classpath, e.g., by explicitly add JTA as a dependency when using Maven:

<dependency>
    <groupId>javax.transaction</groupId>
    <artifactId>javax.transaction-api</artifactId>
    <scope>runtime</scope>
</dependency>
Copy to Clipboard Toggle word wrap

You’ll have to have your application deployed in a JTA capable container or provide a standalone JTA implementation.

Important

Note that, for the time being, the transaction manager is looked up as JNDI resource with the java:/TransactionManager key.

More flexible strategies will be added in the future to support a wider range of deployment scenarios.

59.12.1. Transaction policies

Camel CDI provides implementation for the typically supported Camel TransactedPolicy as CDI beans. It is possible to have these policies looked up by name using the transacted EIP, e.g.:

class MyRouteBean extends RouteBuilder {

    @Override
    public void configure() {
        from("activemq:queue:foo")
            .transacted("PROPAGATION_REQUIRED")
            .bean("transformer")
            .to("jpa:my.application.entity.Bar")
            .log("${body.id} inserted");
    }
}
Copy to Clipboard Toggle word wrap

This would be equivalent to:

class MyRouteBean extends RouteBuilder {

    @Inject
    @Named("PROPAGATION_REQUIRED")
    Policy required;

    @Override
    public void configure() {
        from("activemq:queue:foo")
            .policy(required)
            .bean("transformer")
            .to("jpa:my.application.entity.Bar")
            .log("${body.id} inserted");
    }
}
Copy to Clipboard Toggle word wrap

The list of supported transaction policy names is:

  • PROPAGATION_NEVER,
  • PROPAGATION_NOT_SUPPORTED,
  • PROPAGATION_SUPPORTS,
  • PROPAGATION_REQUIRED,
  • PROPAGATION_REQUIRES_NEW,
  • PROPAGATION_NESTED,
  • PROPAGATION_MANDATORY.

59.12.2. Transactional error handler

Camel CDI provides a transactional error handler that extends the redelivery error handler, forces a rollback whenever an exception occurs and creates a new transaction for each redelivery.

Camel CDI provides the CdiRouteBuilder class that exposes the transactionErrorHandler helper method to enable quick access to the configuration, e.g.:

class MyRouteBean extends CdiRouteBuilder {

    @Override
    public void configure() {
        errorHandler(transactionErrorHandler()
            .setTransactionPolicy("PROPAGATION_SUPPORTS")
            .maximumRedeliveries(5)
            .maximumRedeliveryDelay(5000)
            .collisionAvoidancePercent(10)
            .backOffMultiplier(1.5));
    }
}
Copy to Clipboard Toggle word wrap

59.13. Auto-configured OSGi integration

Available as of Camel 2.17

The Camel context beans are automatically adapted by Camel CDI so that they are registered as OSGi services and the various resolvers (like ComponentResolver and DataFormatResolver) integrate with the OSGi registry. That means that the Karaf Camel commands can be used to operate the Camel contexts auto-configured by Camel CDI, e.g.:

karaf@root()> camel:context-list
 Context        Status              Total #       Failed #     Inflight #   Uptime
 -------        ------              -------       --------     ----------   ------
 camel-cdi      Started                   1              0              0   1 minute
Copy to Clipboard Toggle word wrap

See the camel-example-cdi-osgi example for a working example of the Camel CDI OSGi integration.

59.14. Lazy Injection / Programmatic Lookup

While the CDI programmatic model favors a typesafe resolution mechanism that occurs at application initialization time, it is possible to perform dynamic / lazy injection later during the application execution using the programmatic lookup mechanism.

Camel CDI provides for convenience the annotation literals corresponding to the CDI qualifiers that you can use for standard injection of Camel primitives. These annotation literals can be used in conjunction with the javax.enterprise.inject.Instance interface which is the CDI entry point to perform lazy injection / programmatic lookup.

For example, you can use the provided annotation literal for the @Uri qualifier to lazily lookup for Camel primitives, e.g. for ProducerTemplate beans:

@Any
@Inject
Instance<ProducerTemplate> producers;

ProducerTemplate inbound = producers
    .select(Uri.Literal.of("direct:inbound"))
    .get();
Copy to Clipboard Toggle word wrap

Or for Endpoint beans, e.g.:

@Any
@Inject
Instance<Endpoint> endpoints;

MockEndpoint outbound = endpoints
    .select(MockEndpoint.class, Uri.Literal.of("mock:outbound"))
    .get();
Copy to Clipboard Toggle word wrap

Similarly, you can use the provided annotation literal for the @ContextName qualifier to lazily lookup for CamelContext beans, e.g.:

@Any
@Inject
Instance<CamelContext> contexts;

CamelContext context = contexts
    .select(ContextName.Literal.of("foo"))
    .get();
Copy to Clipboard Toggle word wrap

You can also refined the selection based on the Camel context type, e.g.:

@Any
@Inject
Instance<CamelContext> contexts;

// Refine the selection by type
Instance<DefaultCamelContext> context = contexts.select(DefaultCamelContext.class);

// Check if such a bean exists then retrieve a reference
if (!context.isUnsatisfied())
    context.get();
Copy to Clipboard Toggle word wrap

Or even iterate over a selection of Camel contexts, e.g.:

@Any
@Inject
Instance<CamelContext> contexts;

for (CamelContext context : contexts)
    context.setUseBreadcrumb(true);
Copy to Clipboard Toggle word wrap

59.15. Maven Archetype

Among the available Camel Maven archetypes, you can use the provided camel-archetype-cdi to generate a Camel CDI Maven project, e.g.:

mvn archetype:generate -DarchetypeGroupId=org.apache.camel.archetypes -DarchetypeArtifactId=camel-archetype-cdi
Copy to Clipboard Toggle word wrap

59.16. Supported containers

The Camel CDI component is compatible with any CDI 1.0, CDI 1.1 and CDI 1.2 compliant runtime. It’s been successfully tested against the following runtimes:

Expand
ContainerVersionRuntime

Weld SE

1.1.28.Final

CDI 1.0 / Java SE 7

OpenWebBeans

1.2.7

CDI 1.0 / Java SE 7

Weld SE

2.4.2.Final

CDI 1.2 / Java SE 7

OpenWebBeans

1.7.2

CDI 1.2 / Java SE 7

WildFly

8.2.1.Final

CDI 1.2 / Java EE 7

WildFly

9.0.1.Final

CDI 1.2 / Java EE 7

WildFly

10.1.0.Final

CDI 1.2 / Java EE 7

59.17. Examples

The following examples are available in the examples directory of the Camel project:

Expand
ExampleDescription

camel-example-cdi

Illustrates how to work with Camel using CDI to configure components, endpoints and beans

camel-example-cdi-kubernetes

Illustrates the integration between Camel, CDI and Kubernetes

camel-example-cdi-metrics

Illustrates the integration between Camel, Dropwizard Metrics and CDI

camel-example-cdi-properties

Illustrates the integration between Camel, DeltaSpike and CDI for configuration properties

camel-example-cdi-osgi

A CDI application using the SJMS component that can be executed inside an OSGi container using PAX CDI

camel-example-cdi-rest-servlet

Illustrates the Camel REST DSL being used in a Web application that uses CDI as dependency injection framework

camel-example-cdi-test

Demonstrates the testing features that are provided as part of the integration between Camel and CDI

camel-example-cdi-xml

Illustrates the use of Camel XML configuration files into a Camel CDI application

camel-example-swagger-cdi

An example using REST DSL and Swagger Java with CDI

camel-example-widget-gadget-cdi

The Widget and Gadget use-case from the EIP book implemented in Java with CDI dependency Injection

59.18. See Also

59.19. Camel CDI for EAR deployments on {wildfly-camel}

Camel CDI EAR deployments on {wildfly-camel} have some differences in class and resource loading behaviour, compared to standard WAR or JAR deployments.

{wildfly} bootstraps Weld using the EAR deployment ClassLoader. {wildfly} also mandates that only a single CDI extension is created and shared by all EAR sub-deployments.

This results in the 'Auto-configured' CDI Camel Context using the EAR deployment ClassLoader to dynamically load classes and resources. By default, this ClassLoader does not have access to resources within EAR sub-deployments.

For EAR deployments, it is recommended that usage of the 'Auto-configured' CDI Camel Context is avoided and that RouteBuilder classes are annotated with @ContextName, or that a CamelContext is created via the @ImportResource annotation or through CDI producer methods and fields. This helps {wildfly-camel} to determine the correct ClassLoader to use with Camel.

Chapter 60. Chronicle Engine Component

Available as of Camel version 2.18

The camel chronicle-engine component let you leverage the power of OpenHFT’s Chronicle-Engine

60.1. URI Format

chronicle-engine:addresses/path[?options]
Copy to Clipboard Toggle word wrap

60.2. URI Options

The Chronicle Engine component has no options.

The Chronicle Engine endpoint is configured using URI syntax:

chronicle-engine:addresses/path
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

60.2.1. Path Parameters (2 parameters):

Expand
NameDescriptionDefaultType

addresses

Required Engine addresses. Multiple addresses can be separated by comma.

 

String

path

Required Engine path

 

String

60.2.2. Query Parameters (12 parameters):

Expand
NameDescriptionDefaultType

action (common)

The default action to perform, valid values are: - PUBLISH - PPUBLISH_AND_INDEX - PPUT - PGET_AND_PUT - PPUT_ALL - PPUT_IF_ABSENT - PGET - PGET_AND_REMOVE - PREMOVE - PIS_EMPTY - PSIZE

 

String

clusterName (common)

Cluster name for queue

 

String

filteredMapEvents (common)

A comma separated list of Map event type to filer, valid values are: INSERT, UPDATE, REMOVE.

 

String

persistent (common)

Enable/disable data persistence

true

boolean

subscribeMapEvents (common)

Set if consumer should subscribe to Map events, default true.

true

boolean

subscribeTopicEvents (common)

Set if consumer should subscribe to TopicEvents,d efault false.

false

boolean

subscribeTopologicalEvents (common)

Set if consumer should subscribe to TopologicalEvents,d efault false.

false

boolean

wireType (common)

The Wire type to use, default to binary wire.

BINARY

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Chapter 61. Chunk Component

Available as of Camel version 2.15

The chunk: component allows for processing a message using a Chunk template. This can be ideal when using Templating to generate responses for requests.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-chunk</artifactId>
<version>x.x.x</version> <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

61.1. URI format

chunk:templateName[?options]
Copy to Clipboard Toggle word wrap

Where templateName is the classpath-local URI of the template to invoke.

You can append query options to the URI in the following format, ?option=value&option=value&…​

61.2. Options

The Chunk component has no options.

The Chunk endpoint is configured using URI syntax:

chunk:resourceUri
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

61.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

resourceUri

Required Path to the resource. You can prefix with: classpath, file, http, ref, or bean. classpath, file and http loads the resource using these protocols (classpath is default). ref will lookup the resource in the registry. bean will call a method on a bean to be used as the resource. For bean you can specify the method name after dot, eg bean:myBean.myMethod.

 

String

61.2.2. Query Parameters (7 parameters):

Expand
NameDescriptionDefaultType

contentCache (producer)

Sets whether to use resource content cache or not

false

boolean

encoding (producer)

Define the encoding of the body

 

String

extension (producer)

Define the file extension of the template

 

String

themeFolder (producer)

Define the themes folder to scan

 

String

themeLayer (producer)

Define the theme layer to elaborate

 

String

themeSubfolder (producer)

Define the themes subfolder to scan

 

String

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

Chunk component will look for a specific template in themes folder with extensions .chtml or _.cxml. _If you need to specify a different folder or extensions, you will need to use the specific options listed above.

61.3. Chunk Context

Camel will provide exchange information in the Chunk context (just a Map). The Exchange is transferred as:

 

Expand
keyvalue

exchange

The Exchange itself.

exchange.properties

The Exchange properties.

headers

The headers of the In message.

camelContext

The Camel Context.

request

The In message.

body

The In message body.

response

The Out message (only for InOut message exchange pattern).

61.4. Dynamic templates

Camel provides two headers by which you can define a different resource location for a template or the template content itself. If any of these headers is set then Camel uses this over the endpoint configured resource. This allows you to provide a dynamic template at runtime.

Expand
HeaderTypeDescriptionSupport Version

ChunkConstants.CHUNK_RESOURCE_URI

String

A URI for the template resource to use instead of the endpoint configured.

 

ChunkConstants.CHUNK_TEMPLATE

String

The template to use instead of the endpoint configured.

 

61.5. Samples

For example you could use something like:

from("activemq:My.Queue").
to("chunk:template");
Copy to Clipboard Toggle word wrap

To use a Chunk template to formulate a response for a message for InOut message exchanges (where there is a JMSReplyTo header).

If you want to use InOnly and consume the message and send it to another destination you could use:

from("activemq:My.Queue").
to("chunk:template").
to("activemq:Another.Queue");
Copy to Clipboard Toggle word wrap

It’s possible to specify what template the component should use dynamically via a header, so for example:

from("direct:in").
setHeader(ChunkConstants.CHUNK_RESOURCE_URI).constant("template").
to("chunk:dummy");
Copy to Clipboard Toggle word wrap

An example of Chunk component options use:

from("direct:in").
to("chunk:file_example?themeFolder=template&themeSubfolder=subfolder&extension=chunk");
Copy to Clipboard Toggle word wrap

In this example Chunk component will look for the file file_example.chunk in the folder template/subfolder.

61.6. The Email Sample

In this sample we want to use Chunk templating for an order confirmation email. The email template is laid out in Chunk as:

 
Dear {$headers.lastName}, {$headers.firstName}

Thanks for the order of {$headers.item}.

Regards Camel Riders Bookstore
{$body}
Copy to Clipboard Toggle word wrap

61.7. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started

Chapter 62. Class Component

Available as of Camel version 2.4

The class: component binds beans to Camel message exchanges. It works in the same way as the Bean component but instead of looking up beans from a Registry it creates the bean based on the class name.

62.1. URI format

class:className[?options]
Copy to Clipboard Toggle word wrap

Where className is the fully qualified class name to create and use as bean.

62.2. Options

The Class component has no options.

The Class endpoint is configured using URI syntax:

class:beanName
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

62.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

beanName

Required Sets the name of the bean to invoke

 

String

62.2.2. Query Parameters (5 parameters):

Expand
NameDescriptionDefaultType

method (producer)

Sets the name of the method to invoke on the bean

 

String

cache (advanced)

If enabled, Camel will cache the result of the first Registry look-up. Cache can be enabled if the bean in the Registry is defined as a singleton scope.

false

boolean

multiParameterArray (advanced)

Deprecated How to treat the parameters which are passed from the message body; if it is true, the message body should be an array of parameters. Note: This option is used internally by Camel, and is not intended for end users to use. Deprecation note: This option is used internally by Camel, and is not intended for end users to use.

false

boolean

parameters (advanced)

Used for configuring additional properties on the bean

 

Map

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

62.3. Using

You simply use the class component just as the Bean component but by specifying the fully qualified classname instead.
For example to use the MyFooBean you have to do as follows:

    from("direct:start").to("class:org.apache.camel.component.bean.MyFooBean").to("mock:result");
Copy to Clipboard Toggle word wrap

You can also specify which method to invoke on the MyFooBean, for example hello:

    from("direct:start").to("class:org.apache.camel.component.bean.MyFooBean?method=hello").to("mock:result");
Copy to Clipboard Toggle word wrap

62.4. Setting properties on the created instance

In the endpoint uri you can specify properties to set on the created instance, for example if it has a setPrefix method:

   // Camel 2.17 onwards
   from("direct:start")
        .to("class:org.apache.camel.component.bean.MyPrefixBean?bean.prefix=Bye")
        .to("mock:result");
 
   // Camel 2.16 and older 
   from("direct:start")
        .to("class:org.apache.camel.component.bean.MyPrefixBean?prefix=Bye")
        .to("mock:result");
Copy to Clipboard Toggle word wrap

And you can also use the # syntax to refer to properties to be looked up in the Registry.

    // Camel 2.17 onwards
    from("direct:start")
        .to("class:org.apache.camel.component.bean.MyPrefixBean?bean.cool=#foo")
        .to("mock:result");

    // Camel 2.16 and older
    from("direct:start")
        .to("class:org.apache.camel.component.bean.MyPrefixBean?cool=#foo")
        .to("mock:result");
Copy to Clipboard Toggle word wrap

Which will lookup a bean from the Registry with the id foo and invoke the setCool method on the created instance of the MyPrefixBean class.

TIP:See more details at the Bean component as the class component works in much the same way.

62.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • Bean
  • Bean Binding
  • Bean Integration

Chapter 63. CMIS Component

Available as of Camel version 2.11

The cmis component uses the Apache Chemistry client API and allows you to add/read nodes to/from a CMIS compliant content repositories.

63.1. URI Format

cmis://cmisServerUrl[?options]
Copy to Clipboard Toggle word wrap

You can append query options to the URI in the following format, ?options=value&option2=value&…​

63.2. CMIS Options

The CMIS component supports 2 options which are listed below.

Expand
NameDescriptionDefaultType

sessionFacadeFactory (common)

To use a custom CMISSessionFacadeFactory to create the CMISSessionFacade instances

 

CMISSessionFacade Factory

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The CMIS endpoint is configured using URI syntax:

cmis:cmsUrl
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

63.2.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

cmsUrl

Required URL to the cmis repository

 

String

63.2.2. Query Parameters (13 parameters):

Expand
NameDescriptionDefaultType

pageSize (common)

Number of nodes to retrieve per page

100

int

readContent (common)

If set to true, the content of document node will be retrieved in addition to the properties

false

boolean

readCount (common)

Max number of nodes to read

 

int

repositoryId (common)

The Id of the repository to use. If not specified the first available repository is used

 

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

query (consumer)

The cmis query to execute against the repository. If not specified, the consumer will retrieve every node from the content repository by iterating the content tree recursively

 

String

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

queryMode (producer)

If true, will execute the cmis query from the message body and return result, otherwise will create a node in the cmis repository

false

boolean

sessionFacadeFactory (advanced)

To use a custom CMISSessionFacadeFactory to create the CMISSessionFacade instances

 

CMISSessionFacade Factory

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

password (security)

Password for the cmis repository

 

String

username (security)

Username for the cmis repository

 

String

63.3. Usage

63.3.1. Message headers evaluated by the producer

Expand
HeaderDefault ValueDescription

CamelCMISFolderPath

/

The current folder to use during the execution. If not specified will use the root folder

CamelCMISRetrieveContent

false

In queryMode this header will force the producer to retrieve the content of document nodes.

CamelCMISReadSize

0

Max number of nodes to read.

cmis:path

null

If CamelCMISFolderPath is not set, will try to find out the path of the node from this cmis property and it is name

cmis:name

null

If CamelCMISFolderPath is not set, will try to find out the path of the node from this cmis property and it is path

cmis:objectTypeId

null

The type of the node

cmis:contentStreamMimeType

null

The mimetype to set for a document

Expand
HeaderTypeDescription

CamelCMISResultCount

Integer

Number of nodes returned from the query.

The message body will contain a list of maps, where each entry in the map is cmis property and its value. If CamelCMISRetrieveContent header is set to true, one additional entry in the map with key CamelCMISContent will contain InputStream of the document type of nodes.

63.4. Dependencies

Maven users will need to add the following dependency to their pom.xml.

pom.xml

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-cmis</artifactId>
    <version>${camel-version}</version>
</dependency>
Copy to Clipboard Toggle word wrap

where ${camel-version} must be replaced by the actual version of Camel (2.11 or higher).

63.5. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started

Chapter 64. CM SMS Gateway Component

Available as of Camel version 2.18

Camel-Cm-Sms is an Apache Camel component for the [CM SMS Gateway](https://www.cmtelecom.com).

It allows to integrate CM SMS APIin an application as a camel component.

You must have a valid account. More information are available at CM Telecom.

cm-sms://sgw01.cm.nl/gateway.ashx?defaultFrom=DefaultSender&defaultMaxNumberOfParts=8&productToken=xxxxx
Copy to Clipboard Toggle word wrap

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
 <groupId>org.apache.camel</groupId>
 <artifactId>camel-cm-sms</artifactId>
 <version>x.x.x</version>
 <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

64.1. Options

The CM SMS Gateway component has no options.

The CM SMS Gateway endpoint is configured using URI syntax:

cm-sms:host
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

64.1.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

host

Required SMS Provider HOST with scheme

 

String

64.1.2. Query Parameters (5 parameters):

Expand
NameDescriptionDefaultType

defaultFrom (producer)

This is the sender name. The maximum length is 11 characters.

 

String

defaultMaxNumberOfParts (producer)

If it is a multipart message forces the max number. Message can be truncated. Technically the gateway will first check if a message is larger than 160 characters, if so, the message will be cut into multiple 153 characters parts limited by these parameters.

8

int

productToken (producer)

Required The unique token to use

 

String

testConnectionOnStartup (producer)

Whether to test the connection to the SMS Gateway on startup

false

boolean

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

64.2. Sample

You can try this project to see how camel-cm-sms can be integrated in a camel route.

Chapter 65. CoAP Component

Available as of Camel version 2.16

Camel-CoAP is an Apache Camel component that allows you to work with CoAP, a lightweight REST-type protocol for machine-to-machine operation. CoAP, Constrained Application Protocol is a specialized web transfer protocol for use with constrained nodes and constrained networks and it is based on RFC 7252.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
 <groupId>org.apache.camel</groupId>
 <artifactId>camel-coap</artifactId>
 <version>x.x.x</version>
 <!-- use the same version as your Camel core version -->
</dependency>
Copy to Clipboard Toggle word wrap

65.1. Options

The CoAP component has no options.

The CoAP endpoint is configured using URI syntax:

coap:uri
Copy to Clipboard Toggle word wrap

with the following path and query parameters:

65.1.1. Path Parameters (1 parameters):

Expand
NameDescriptionDefaultType

uri

The URI for the CoAP endpoint

 

URI

65.1.2. Query Parameters (5 parameters):

Expand
NameDescriptionDefaultType

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

coapMethodRestrict (consumer)

Comma separated list of methods that the CoAP consumer will bind to. The default is to bind to all methods (DELETE, GET, POST, PUT).

 

String

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

65.2. Message Headers

Expand
NameTypeDescription

CamelCoapMethod

String

The request method that the CoAP producer should use when calling the target CoAP server URI. Valid options are DELETE, GET, PING, POST & PUT.

CamelCoapResponseCode

String

The CoAP response code sent by the external server. See RFC 7252 for details of what each code means.

CamelCoapUri

String

The URI of a CoAP server to call. Will override any existing URI configured directly on the endpoint.

65.2.1. Configuring the CoAP producer request method

The following rules determine which request method the CoAP producer will use to invoke the target URI:

  1. The value of the CamelCoapMethod header
  2. GET if a query string is provided on the target CoAP server URI.
  3. POST if the message exchange body is not null.
  4. GET otherwise.

Chapter 66. Constant Language

Available as of Camel version 1.5

The Constant Expression Language is really just a way to specify constant strings as a type of expression.

Note

This is a fixed constant value that is only set once during starting up the route, do not use this if you want dynamic values during routing.

66.1. Constant Options

The Constant language supports 1 options which are listed below.

Expand
NameDefaultJava TypeDescription

trim

true

Boolean

Whether to trim the value to remove leading and trailing whitespaces and line breaks

66.2. Example usage

The setHeader element of the Spring DSL can utilize a constant expression like:

<route>
  <from uri="seda:a"/>
  <setHeader headerName="theHeader">
    <constant>the value</constant>
  </setHeader>
  <to uri="mock:b"/>
</route>
Copy to Clipboard Toggle word wrap

in this case, the Message coming from the seda:a Endpoint will have 'theHeader' header set to the constant value 'the value'.

And the same example using Java DSL:

from("seda:a")
  .setHeader("theHeader", constant("the value"))
  .to("mock:b");
Copy to Clipboard Toggle word wrap

66.3. Dependencies

The Constant language is part of camel-core.

Chapter 67. CometD Component

Available as of Camel version 2.0

The cometd: component is a transport 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>
Copy to Clipboard Toggle word wrap

67.1. URI format

cometd://host:port/channelName[?options]
Copy to Clipboard Toggle word wrap

The channelName represents a topic that can be subscribed to by the Camel endpoints.

67.2. Examples

cometd://localhost:8080/service/mychannel
cometds://localhost:8443/service/mychannel
Copy to Clipboard