Mediation Routing Using Apache Camel
The basic unit of work in Apache Camel is route. Route is simply a flow of EIPs, where an output of one EIP is an input of the other. So let's start with a simple example.
I would like to sort the xml files based on their content. When xml element denoting person’s city has value ‘London’ then file needs to be copied to messages/uk directory, in other case to messages/others directory. Additionally I want to log each copy operation. Here is EIPs flow implementing described above logic:
Below you can see the configuration of Apache Camel context:
1: <code style="color: black; word-wrap: normal;">1: <camelContext xmlns="http://camel.apache.org/schema/spring"> 2: <route> 3: <from uri="file:src/data?noop=true"/> 4: <choice> 5: <when> 6: <xpath>/person/city = 'London'</xpath> 7: <log message="UK message"/> 8: <to uri="file:target/messages/uk"/> 9: </when> 10: <otherwise> 11: <log message="Other message"/> 12: <to uri="file:target/messages/others"/> 13: </otherwise> 14: </choice> 15: </route> 16: </camelContext> </code><code style="color: black; word-wrap: normal;"> </code>
As the name suggests, from is a declaration of source endpoint that listens to events / polls events. In this example, endpoint is a file poller. On the website http://camel.apache.org/components.html you can find list of all available Apache Camel components, each one with detailed description of uri configuration.
The next element in the configuration is choice when otherwise, which is content based router. In our example when condition is an xpath expression /person/city = 'London'. Node otherwise is chosen when none of the when conditions are fulfilled. To log messages you can use log element. The last node is to which is target endpoint.
XML on the left is copied to messages/uk, and XML on the right is copied to messages/others.
<person user="james"> <firstName>James</firstName> <lastName>Strachan</lastName> <city>London</city> </person>
<person user="michal"> <firstName>Michał</firstName> <lastName>Warecki</lastName> <city>Warszawa</city> </person>
The next section will show how to run aforementioned example.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)