LibraryLink ToToggle FramesPrintFeedback

Stage 2: Examining the Sample Code

In this stage, you examine the sample code in ProjectRoot/simple-router/src/main/java/tutorial/ This sample implements a typical EIP pattern, a content-based router, and illustrates how easily — and concisely — you can solve integration problems using Apache Camel.

The following code shows how the sample route is implemented:

package tutorial; 1

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.spring.Main;

import static org.apache.camel.builder.xml.XPathBuilder.xpath;

* A Camel Router
* @version $
public class MyRouteBuilder extends RouteBuilder {

     * A main() so we can easily run these routing rules in our IDE
     public static void main(String... args) throws Exception {
          Main.main(args);  2
     * Lets configure the Camel routing rules using Java code...
     public void configure() {
  // TODO create Camel routes here.
  // here is a sample which processes the input files
  // (leaving them in place - see the 'noop' flag)
  // then performs content based routing on the message
  // using XPath
  from("file:src/data?noop=true"). 3
         when(xpath("/person/city = 'London'")). 4

This sample has several notable features. First, observe how the Java DSL uses a series of method calls to create an English-like expression. This technique makes the intent of the code clear: the sample reads input messages from a directory, applies an XPath predicate to each message's XML content, and, based on the result, chooses a different route for the output messages.

Note also the following:


Maven automatically creates a package name based on the value of the -DgroupId argument to the mvn archetype:create command.


Apache Camel defines a convenient wrapper class for the Spring container. To instantiate a Spring container instance, all that you need to do is write a short main() method that delegates creation of the container to the wrapper class.


The from() method call takes a file URL as its argument. This URL provides information that Apache Camel uses to interpret and execute the route. The file: prefix in the URL indicates that a file endpoint is required, which means the file component is responsible for creating the endpoint. (The file component, like other Apache Camel components, serves as an endpoint factory.) The option in the URL, ?noop=true, indicates that the files in src/data should be left in place after they are consumed. (This option is one of many available. Like other components, the file component provides numerous options.)


The when() method call specifies an XPath predicate, which is applied to each input. If the predicate evaluates to true, output is routed to the uk subdirectory; if false, to the others subdirectory.