Camel Components

There now follows the documentation on each Camel component.

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 JMS Component and uses Spring's JMS support for declarative transactions, using Spring's JmsTemplate for sending and a MessageListenerContainer for consuming.

URI format

activemq:[topic:]destinationName

So for example to send to queue FOO.BAR you would use

activemq:FOO.BAR

You can be completely specific if you wish via

activemq:queue:FOO.BAR

If you want to send to a topic called Stocks.Prices then you would use

activemq:topic:Stocks.Prices

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

See Also

CXF Component

The cxf: component provides integration with Apache CXF for connecting to JAX-WS services hosted in CXF.

URI format

cxf:address

See Also

Direct Component

The direct: component provides direct, synchronous invocation of any consumers when a producer sends a message exchange.
This endpoint can be used connect existing routes or if a client in the same JVM as the Camel router wants to access the routes.

URI format

direct:someName

Where someName can be any string to uniquely identify the endpoint

Options

Name Default Value Description
allowMultipleConsumers true If set to false, then when a second consumer is started on the endpoint, a IllegalStateException is thrown

See Also

File Component

The File component provides access to file systems; allowing files to be processed by any other Camel Components or messages from other components can be saved to disk.

URI format

file:fileName

Where fileName represents the underlying file name

URI Options

Name Default Value Description
initialDelay 1000 milliseconds before polling the file/directory starts
delay 500 milliseconds before the next poll of the file/directory
useFixedDelay false if true, poll once after the initial delay
recursive true if a directory, will look for changes in files in all the sub directories
lock true if true will lock the file for the duration of the processing
regexPattern null will only fire a an exchange for a file that matches the regex pattern
delete false If delete is true then the file will be deleted when it is processed (the default is to move it, see below)
noop false If true then the file is not moved or deleted in any way (see below). This option is good for read only data, or for ETL type requirements
moveNamePrefix null The prefix String prepended to the filename when moving it. For example to move processed files into the done directory, set this value to 'done/'
moveNamePostfix null The postfix String apended to the filename when moving it. For example to rename processed files from foo to foo.old set this value to '.old'

By default the file is locked for the duration of the processing. Also when files are processed they are moved into the .camel directory; so that they appear to be deleted.

Message Headers

The following message headers can be used to affect the behaviour of the component

Header Description
org.apache.camel.file.name Specifies the output file name (relative to the endpoint directory) to be used for the output message when sending to the endpoint. If this is not present then a generated message ID is used instead

See Also

FTP/SFTP/WebDAV Component

This component provides access to remote file systems over the FTP, SFTP and WebDAV protocols

URI format

ftp://host[:port]/fileName[?options]
sftp://host[:port]/fileName[?options]
webdav://host[:port]/fileName[?options]

Where fileName represents the underlying file name or directory

Options

Name Default Value Description
directory false indicates whether or not the given file name should be interpreted by default as a directory or file (as it sometimes hard to be sure with some FTP servers)
password null specifies the password to use to login to the remote file system

See Also

HTTP Component

The http: component provides HTTP based endpoints for exposing HTTP resources or consuming external HTTP resources.

URI format

http:hostname[:port][/resourceUri]

See Also

JBI Component

The jbi: component provides integration with a JBI Service Bus such as provided by Apache ServiceMix

URI format

jbi:service:serviceNamespace[sep]serviceName
jbi:endpoint:serviceNamespace[sep]serviceName[sep]endpointName
jbi:name:endpointName

The separator used will be:

  • '/' if the namespace looks like 'http://'
  • ':' if the namespace looks like 'urn:foo:bar'

For more details of valid JBI URIs see the ServiceMix URI Guide.

Using the jbi:service: or jbi:endpoint: URI forms will set the service QName on the JBI endpoint to the exact one you give. Otherwise the default Camel JBI Service QName will be used which is

{http://activemq.apache.org/camel/schema/jbi}endpoint

Examples

jbi:service:http://foo.bar.org/MyService
jbi:endpoint:urn:foo:bar:MyService:MyEndpoint
jbi:endpoint:http://foo.bar.org/MyService/MyEndpoint
jbi:name:cheese

Creating a JBI Service Unit

If you have some Camel routes you want to deploy inside JBI as a Service Unit you can use the JBI Service Unit Archetype to create a new project.

If you have an existing maven project which you need to convert into a JBI Service Unit you may want to refer to the ServiceMix Maven JBI Plugins for further help. Basically you just need to make sure

  • you have a spring XML file at src/main/resources/camel-context.xml which is used to boot up your routes inside the JBI Service Unit
  • you change the pom's packaging to jbi-service-unit

Your pom.xml should look something like this to enable the jbi-service-unit packaging.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>myGroupId</groupId>
  <artifactId>myArtifactId</artifactId>
  <packaging>jbi-service-unit</packaging>
  <version>1.0-SNAPSHOT</version>

  <name>A Camel based JBI Service Unit</name>

  <url>http://www.myorganization.org</url>

  <properties>
    <camel-version>1.0.0</camel-version>
    <servicemix-version>3.2-incubating</servicemix-version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-jbi</artifactId>
      <version>${camel-version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.servicemix</groupId>
      <artifactId>servicemix-core</artifactId>
      <version>${servicemix-version}</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <defaultGoal>install</defaultGoal>

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
        </configuration>
      </plugin>

      <!-- creates the JBI deployment unit -->
      <plugin>
        <groupId>org.apache.servicemix.tooling</groupId>
        <artifactId>jbi-maven-plugin</artifactId>
        <version>${servicemix-version}</version>
        <extensions>true</extensions>
      </plugin>
    </plugins>
  </build>
</project>

See Also

JMS Component

The JMS component allows messages to be sent to a JMS Queue or Topic; or messages to be consumed from a JMS Queue or Topic. The implementation of the JMS Component uses Spring's JMS support for declarative transactions, using Spring's JmsTemplate for sending and a MessageListenerContainer for consuming.

URI format

jms:[topic:]destinationName?properties

So for example to send to queue FOO.BAR you would use

jms:FOO.BAR

You can be completely specific if you wish via

jms:queue:FOO.BAR

If you want to send to a topic called Stocks.Prices then you would use

jms:topic:Stocks.Prices

Notes

If you wish to use durable topic subscriptions, you need to specify both clientId and durableSubscriberName. Note that the value of the clientId must be unique and can only be used by a single JMS connection instance in your entire network. You may prefer to use Virtual Topics instead to avoid this limitation. More background on durable messaging here.

If you are using ActiveMQ

Note that the JMS component reuses Spring 2's JmsTemplate for sending messages. This is not ideal for use in a non-J2EE container and typically requires some caching JMS provider to avoid performance being lousy.

So if you intent to use Apache ActiveMQ as your Message Broker - which is a good choice as ActiveMQ rocks , then we recommend that you either

  • use the ActiveMQ component which is already configured to use ActiveMQ efficiently
  • use the PoolingConnectionFactory in ActiveMQ

Properties

You can configure lots of different properties on the JMS endpoint which map to properties on the JMSConfiguration POJO.

Property Default Value Description
acceptMessagesWhileStopping false Should the consumer accept messages while it is stopping
acknowledgementModeName "AUTO_ACKNOWLEDGE" The JMS acknowledgement name which is one of: TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE
autoStartup true Should the consumer container auto-startup
cacheLevelName "CACHE_CONSUMER" Sets the cache level name for the underlying JMS resources
clientId null 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. Its typically only required for durable topic subscriptions. You may prefer to use Virtual Topics instead
concurrentConsumers 1 Specifies the default number of concurrent consumers
connectionFactory null The default JMS connection factory to use for the listenerConnectionFactory and templateConnectionFactory if neither are specified
deliveryPersistent true Is persistent delivery used by default?
durableSubscriptionName null The durable subscriber name for specifying durable topic subscriptions
exceptionListener null The JMS Exception Listener used to be notified of any underlying JMS exceptions
explicitQosEnabled false Set if the deliveryMode, priority or timeToLive should be used when sending messages
exposeListenerSession true Set if the listener session should be exposed when consuming messages
idleTaskExecutionLimit 1 Specify 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 case of dynamic scheduling; see the "maxConcurrentConsumers" setting).
listenerConnectionFactory null The JMS connection factory used for consuming messages
maxConcurrentConsumers 1 Specifies the maximum number of concurrent consumers
maxMessagesPerTask 1 The number of messages per task
messageConverter null The Spring Message Converter
messageIdEnabled true When sending, should message IDs be added
messageTimestampEnabled true Should timestamps be enabled by default on sending messages
priority -1 Values of > 1 specify the message priority when sending, if the explicitQosEnabled property is specified
receiveTimeout none The timeout when receiving messages
recoveryInterval none The recovery interval
serverSessionFactory null The JMS ServerSessionFactory if you wish to use ServerSessionFactory for consumption
subscriptionDurable false Enabled by default if you specify a durableSubscriberName and a clientId
taskExecutor null Allows you to specify a custom task executor for consuming messages
templateConnectionFactory null The JMS connection factory used for sending messages
timeToLive null Is a time to live specified when sending messages
transacted false Is transacted mode used for sending/receiving messages?
transactionManager null The Spring transaction manager to use
transactionName null The name of the transaction to use
transactionTimeout null The timeout value of the transaction if using transacted mode
useVersion102 false Should the old JMS API be used

See Also

JPA Component

The jpa: component allows you to work with databases using JPA (EJB 3 Persistence) such as for working with OpenJPA, Hibernate, TopLink to work with relational databases.

Sending to the endpoint

Sending POJOs to the JPA endpoint inserts entities into the database. The body of the message is assumed to be an entity bean (i.e. a POJO with an @Entity annotation on it).

If the body does not contain an entity bean then use a Message Translator in front of the endpoint to perform the necessary conversion first.

Consuming from the endpoint

Consuming messages removes (or updates) entities in the database. This allows you to use a database table as a logical queue, consumerse take messages from the queue and then delete/update them to logically remove them from the queue.

If you do not wish to delete the entity when it has been processed you can specify ?consumeDelete=false on the URI. This will result in the entity being processed each poll.

If you would rather perform some update on the entity to mark it as processed (such as to exclude it from a future query) then you can annotate a method with @Consumed which will be invoked on your entity bean when the entity bean is consumed.

URI format

jpa:[entityClassName]

For sending to the endpoint, the entityClassName is optional. If specified it is used to help use the Type Conversion to ensure the body is of the correct type.

For consuming the entityClassName is mandatory.

Options

Name Default Value Description
persistenceUnit camel the JPA persistence unit used by default
consumeDelete true Enables / disables whether or not the entity is deleted after it is consumed

See Also

Mail Component

The mail: component provides access to Email via Spring's Mail support and the underlying JavaMail system

URI format

pop://[user-info@]host[:port][?password=somepwd]
imap://[user-info@]host[:port][?password=somepwd]
smtp://[user-info@]host[:port][?password=somepwd]

which supports either POP, IMAP or SMTP underlying protocols.

Property Description
host the host name or IP address to connect to
port the TCP port number to connect on
user-info the user name on the email server
password the users password to use

See Also

MINA Component

The mina: component is a transport for working with Apache MINA

URI format

mina:tcp://hostname[:port]
mina:udp://hostname[:port]
mina:multicast://hostname[:port]

Options

Name Default Value Description

See Also

|

Mock Component

Testing of distributed and asynchronous processing is notoriously difficult. The Mock Component provides a great tool for creating good integration test cases based on the Enterprise Integration Patterns using the various Components in Camel.

The Mock component provides a powerful declarative testing mechanism which is similar to jMock in that it allows declarative expectations to be created on any Mock endpoint before a test begins. Then the test is ran which typically fires messages to one or more endpoints and finally the expectations can be asserted in a test case to ensure the system worked as expected.

This allows you to test various things like

  • the correct number of messages are received on each endpoint
  • that the correct payloads are received, in the right order
  • that messages arrive on an endpoint in order, using some Expression to create an order testing function
  • that messages arrive match some kind of Predicate such as that specific headers have certain values, or that parts of the messages match some predicate such as by evaluating an XPath or XQuery Expression

URI format

mock:someName

Where someName can be any string to uniquely identify the endpoint

Examples

Here's a simple example of MockEndpoint in use. First the endpoint is resolved on the context. Then we set an expectation, then after the test has run we assert our expectations are met.

MockEndpoint resultEndpoint = context.resolveEndpoint("mock:foo", MockEndpoint.class);

resultEndpoint.expectedMessageCount(2);

// send some messages
...

// now lets assert that the mock:foo endpoint received 2 messages
resultEndpoint.assertIsSatisfied();

You typically always call the assertIsSatisfied() method to test that the expectations were met after running a test.

Setting expectations

You can see from the javadoc of MockEndpoint the various helper methods you can use to set expectations. The mail methods available are as follows

Method Description
expectedMessageCount(int) to define the expected message count on the endpoint
expectedMinimumMessageCount(int) to define the minimum number of expected messages on the endpoint
expectedBodiesReceived(...) to define the expected bodies that should be received (in order)
expectsAscending(Expression) to add an expectation that messages are received in order using the given Expression to compare messages
expectsDescending(Expression) to add an expectation that messages are received in order using the given Expression to compare messages
expectsNoDuplicates(Expression) to add an expectation that no duplicate messages are received; using an Expression to calculate a unique identifier for each message. This could be something like the JMSMessageID if using JMS, or some unique reference number within the message.

Here's another example

resultEndpoint.expectedBodiesReceived("firstMessageBody", "secondMessageBody", "thirdMessageBody");

Adding expectations to specific messages

In addition you can use the message(int messageIndex) method to add assertions about a specific message that is received.

For example to add expectations of the headers or body of the first message (using zero based indexing like java.util.List), you can use this code

resultEndpoint.message(0).header("foo").isEqualTo("bar");

There are some examples of the Mock endpoint in use in the camel-core processor tests.

See Also

Pojo Component

The pojo: component is now just an alias for the Bean component.

See Also

Quartz Component

The quartz: component provides a scheduled delivery of messages using the Quartz scheduler.
Each endpoint represents a different timer (in Quartz terms, a Trigger and JobDetail).

URI format

quartz://timerName?parameters
quartz://groupName/timerName?parameters
quartz://groupName/timerName/cronExpression

You can configure the Trigger and JobDetail using the parameters

Property Description
trigger.repeatCount How many times should the timer repeat for?
trigger.repeatInterval The amount of time in milliseconds between repeated triggers
job.name Sets the name of the job

For example the following routing rule will fire 2 timer events to the endpoint mock:results

from("quartz://myGroup/myTimerName?trigger.repeatInterval=2&trigger.repeatCount=1").to("mock:result");

Using Cron Triggers

Quartz supports Cron-like expressions for specifying timers in a handy format. You can use these expressions in the URI; though to preserve valid URI encoding we allow / to be used instead of spaces and $ to be used instead of ?.

For example the following will fire a message at 12pm (noon) every day

from("quartz://myGroup/myTimerName/0/0/12/*/*/$").to("activemq:Totally.Rocks");

which is equivalent to using the cron expression

0 0 12 * * ?

The following table shows the URI character encodings we use to preserve valid URI syntax

URI Character Cron character
'/' ' '
'$' '?'

See Also

Queue Component

Deprecated

To avoid confusion with JMS queues, this component is now deprecated in 1.1 onwards. Please use the SEDA component instead

The queue: component provides asynchronous SEDA behaviour so that messages are exchanged on a BlockingQueue and consumers are invoked in a seperate thread pool to the producer.

Note that queues are only visible within a single CamelContext. If you want to communicate across CamelContext instances such as to communicate across web applications, see the VM component.

Note also that this component has nothing to do with JMS, if you want a distributed SEA then try using either JMS or ActiveMQ or even MINA

URI format

queue:someName

Where someName can be any string to uniquely identify the endpoint within the current CamelContext

See Also

RMI Component

The rmi: component bind the PojoExchanges to the RMI protocol (JRMP).

Since this binding is just using RMI, normal RMI rules still apply in regards to what the methods can be used over it. This component only supports PojoExchanges that carry a method invocation that is part of an interface that extends the Remote interface. All parameters in the method should be either Serializable or Remote objects too.

URI format

rmi://rmi-regisitry-host:rmi-registry-port/registry-path

For example:

rmi://localhost:1099/path/to/service

Using

To call out to an existing RMI service registered in an RMI registry, create a Route similar to:

from("pojo:foo").to("rmi://localhost:1099/foo");

To bind an existing camel processor or service in an RMI registry, create a Route like:

RmiEndpoint endpoint= (RmiEndpoint) endpoint("rmi://localhost:1099/bar");
endpoint.setRemoteInterfaces(ISay.class);
from(endpoint).to("pojo:bar");

Notice that when binding an inbound RMI endpoint, the Remote interfaces exposed must be specified.

See Also

Timer Component

The timer: component provides timed events to Bean component. You can only consume events from this endpoint. It produces BeanExchanges that send a Runnable.run() method invocation.

URI format

timer:name?options

Where options is a query string that can specify any of the following parameters:

Name Default Value Description
time   The date/time that the (first) event should be generated.
period -1 If set to greater than 0, then generate periodic events every period milliseconds
delay -1 The number of milliseconds to wait before the first event is generated. Should not be used in conjunction with the time parameter.
fixedRate false Events take place at approximately regular intervals, separated by the specified period.
daemon true Should the thread associated with the timer endpoint be run as a daemon.

Using

To setup a route that generates an event every 500 seconds:

from("timer://foo?fixedRate=true&delay=0&period=500").to("pojo:bar");

Note that the "bar" pojo registered should implement Runnable.

See Also

XMPP Component

The xmpp: component implements an XMPP (Jabber) transport.

URI format

xmpp:hostname[:port][/room]

The component supports both room based and private person-person conversations

See Also

Graphic Design By Hiram