Introduction to Apache Camel

Apache Camel is a open source implementation of famous Enterprise Integration Patterns.   Camel is a Routing and Mediation Engine and facilitates the developers to create routes and mediation rules in variety of Domain Specific language(DSL) such as java, Spring/XML, scala etc.

Camel is versatile

Camel uses URIs to supports large number of transport and messaging models such as HTTP, JMS, JBI, Mina, SCA, CXF  it also  works well with external components and dataformats. To get a  feel of versatility of Camel you can browse the list of Components and URIs it supports in the link below. http://camel.apache.org/components.html

Camel is easy to use

Camel allows us to use same set of APIs to create routes and mediate messages between various components. This makes it extremely easy to use

Unit Testing camel is a breeze

Unit testing is essential to writing any quality code. Camel makes this facade of software development extremely easy. It provides bunch of ready make components like CamelContextSupport,  camel-guice, camel-test-blueprint for easily testing the code. More of this in a future post.

The Camel Terminologies/Classes/Interfaces

Endpoint

Endpoints are places where the exchange of messages takes place. It may refer to an address, a POJO, email address, webservice uri, queue uri, file etc. In camel an endpoint is implemented by implemented Endpoint interface. The endpoints are wrapped by something called routes.

CamelContext

CamelContext is at heart of all camel application and it represents Camel run time system.

  1. Create camelcontext.
  2. Add endpoints or components.
  3. Add Routes to connect the endpoints.
  4. Invoke camelcontext.start() – This starts all the camel-internal threads which are responsible for receiving, sending and processing messages in the endpoints.
  5. Lastly invoking camelcontext.stop() when all the messages are exchanged and processed. This will gracefully stop all the camel-internal threads and endpoints.

CamelTemplate

This is a thin wrapper around the CamelContext object and it is responsible to sending exchange or messages to an endpoint.

Component

Component is really an endpoint factory. As camel supports lots of different kind of resources, each of these resources have different kind of endpoints. In practical cases application don’t create endpoints directly using Components. Instead CamelContext decideds which component to instantiate and then uses that component instance to create endpoints. So in app we will have. CamelContext.getEndpoint(“pop3://john.smith@mailserv.example.com?password=myPassword”); Now pop3 in this case is name of the component. CamelContext maps all the component name with the component classes and using the name it instantiates the instance. Once it has handle to the component it instantiates the endpoint by calling. Component.createInstance() method.

Message

Mesaage represents a single concrete message ie request, reply or exception. All concrete message class impements a message interface for example JmsMessage class.

Exchange

Exchange is a container of message. It is created when a message is received by a consumer during routing process.

Processor

Processor interface represents a class that processes a message. It contains a single method public void process(Exchange exchange) throws exception Application developers can implement this interface to preform business logic on the message when message is received by the consumer.

Routes and RouteBuilder

Route is the step by step movement of message from a source, through arbitrary types of decision by filters or routers to a destination. They are configured by help of DSL (Domain Specific language). Java DSL is created by implementing routebuilder interface. It has single method called configure() which defines the entire route of message. Routes can also be configured via xml file using spring.

A Small Example of Camel code.

Lets follow this with a small example to get a taste of what Camel can do. In this example we will move group of files present in a folder to a different folder. In this process we will do following

  1. Checkout the dependencies for Camel.
  2. Create a simple RouterBuilder.
  3. Registering CamelContext in a spring file.
  4. Injecting the routerbuilder in a the CamelContext Bean
  5. Executing the class by starting the Camelcontext and finally stopping it once the execution is done.

1. Dependencies – Add following dependencies in your pom.xml

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

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

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

2. Create RouterBuilder - RouterBuilder can be created by extending org.apache.camel.builder.RouterBuilder class and overriding configure() method. Here is an example

import org.apache.camel.builder.RouteBuilder;

/**
 * Created by IntelliJ IDEA.
 * User: Niraj Singh
 * Date: 7/28/13
 * Time: 10:29 AM
 * To change this template use File | Settings | File Templates.
 */
public class MyFirstRouterBuilder extends RouteBuilder {
     @Override
    public void configure() throws Exception {
        try{
            from( "file:d:/vids").to("file:d:/temp");
        }catch(Exception e){

        }
     }
}
  1. From() is the source endpoint and contains uri of file or directory which camel will be polling.
  2. to() represents the target endpoint and contains name of target file or directory.
  3. The file component uri is of form “file://nameOfFileOrDirectory“.

3. Registering CamelContext in spring and injecting RouterBuilder in spring.

<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="sqsContext" xmlns="http://camel.apache.org/schema/spring">
         <routeBuilder ref="myFirstRouter" />
    </camelContext>

    <bean id="myFirstRouter" class="com.aranin.aws.sqs.MyFirstRouterBuilder"/>

</beans>

4. Starting the camel context and executing the code and stopping the camel context.

import org.apache.camel.CamelContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * Created by IntelliJ IDEA.
 * User: Niraj Singh
 * Date: 4/16/13
 * Time: 11:21 AM
 * To change this template use File | Settings | File Templates.
 */
public class CamelHello {
    public static void main(String args[]) throws Exception {
        try {
                ApplicationContext springcontext = new FileSystemXmlApplicationContext("D:/samayik/awsdemo/src/main/resources/hellocamel.xml");
                CamelContext context = springcontext.getBean("firstCamelContext", CamelContext.class);
                context.start();
                Thread.sleep(10000);
                context.stop();

            } catch ( Exception e ) {
                System.out.println(e);
            }

    }
}

If you run this class then first we load the camelcontext from the spring config file. Inject the router builder in it. After the context starts then all the file from source directory is copied to the target directory. Once all the file are copied then try copying a new file to the source directory, it will be copied to target as well until the context is running 10000 ms in this case.

I have few more advanced tutorials on camel. Perhaps you will find them useful. There links are listed in the reference sections.

References

  1. http://camel.apache.org/
  2. http://camel.apache.org/enterprise-integration-patterns.html
  3. http://architects.dzone.com/articles/enterprise-integration
  4. http://weblog4j.com/2013/05/14/amazon-sqs-listening-to-sqs-using-apache-camel-the-spring-dsl-way/
  5. http://weblog4j.com/2013/04/17/amazon-sqs-listening-to-amazon-sqs-queue-using-apache-camel/

That is all folks. Though no one will write comments, but I like to persevere, and still request folks to drop in a line or two if you like this tutorial.

Warm Regards

Niraj

 

Reference: Introduction to Apache Camel from our JCG partner Niraj Singh at the Weblog4j blog.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

5 Responses to "Introduction to Apache Camel"

  1. sree says:

    very nice tutorial about Apache Camel

  2. Thanks Guys,

    I am glad you like it.

    Regards
    Niraj

  3. Raghav says:

    Hi Niraj,

    Thanks for sharing this very good introduction about Camel.

    The example was fantastic for beginners.

    Cheers,
    Raghav

  4. Geo says:

    Great introduction.Thanks man

Leave a Reply


six − = 2



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books