Calling Java methods from Camel Routes (processor and bean,class components)

In this tutorial, we are going to learn how to call custom java methods from Camel routes.

Example Scenario:

Case 1: Call method using bean component

We have to call our custom created method from Camel Route using bean component.

Case 2: Using processor

We have to use processor in the middle of a route to redirect camel flow to process method.

Case 3: Using bean DSL

We have to call our custom created method from Camel Route using bean DSL.

Case 4: Using class component

We have to call a custom created method from Camel Route using class component.

Project Artifacts:

1. Technologies used –

a. Eclipse IDE for Java EE developer 4.5.0.20150621-1200 (Mars)
b. Preinstalled Maven with Eclipse Mars
c. Camel 2.16.0
d. Java 1.8

2. Eclipse project folder structure:

CustomMethodInvocationProjStruc

3. Jars Used

If you are not using Maven, here is the list of jars you would need for this project:

camel-core-2.16.0.jar
slf4j-api-1.6.6.jar
jaxb-core-2.2.11.jar
jaxb-impl-2.2.11.jar
camel-spring-2.16.0.jar
spring-context-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
commons-logging-1.2.jar
spring-expression-4.1.6.RELEASE.jar
spring-aop-4.1.6.RELEASE.jar
aopalliance-1.0.jar
spring-tx-4.1.6.RELEASE.jar

4. Maven Dependencies

file:pom.xml . Paste the below content to pom.xml. It can pass two arguments – “java” for running camel in Java DSL route and “xml” for running as Spring routes.

 

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javanbeyond</groupId>
	<artifactId>CamelFileOperations</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-core</artifactId>
			<version>2.16.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-spring</artifactId>
			<version>2.16.0</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<version>1.1.1</version>
				<executions>
					<execution>
						<phase>test</phase>
						<goals>
							<goal>java</goal>
						</goals>
						<configuration>
							<mainClass>com.javanbeyond.MainClass</mainClass>
							<arguments>
								<!--<argument>java</argument> -->
								<argument>xml</argument> 
							</arguments>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

5. Main Class

file: MainClass.java . Main class is our starting point and is called by maven. It can run Java DSL or Spring DSL based on argument passed. Also, we have to comment the case we don’t want to run.

 

package com.javanbeyond;

import org.apache.camel.CamelContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainClass {

  public static void main(String[] argsthrows Exception {
    if(args.length < ){
      System.err.println("Please pass java or xml as argument");
      System.exit(1);
    }
    
    if (args[0].equalsIgnoreCase("java")) {
      executeJavaDSL("usingBeanComponent");
      //executeJavaDSL("usingProcessor");
      //executeJavaDSL("usingBeanInvocation");
      //executeJavaDSL("usingClassComponent");
    else if (args[0].equalsIgnoreCase("xml")) {
      // Pass route id to execute the particular route
      executeSpringDSL("usingBeanComponent");
      //executeSpringDSL("usingProcessor");
      //executeSpringDSL("usingBeanInvocation");
      //executeSpringDSL("usingClassComponent");
    else {
      System.out.println("Argument not supported.");
      System.exit(1);
    }
    while (true) {

    }

  }

  @SuppressWarnings("resource")
  public static void executeSpringDSL(String routeIdthrows Exception {
    new ClassPathXmlApplicationContext("camel-context.xml")
        .getBean("camel", CamelContext.class).startRoute(routeId);
  }

  public static void executeJavaDSL(String routeIdthrows Exception {
    new CamelJavaDSL().getCamelContext().startRoute(routeId);
  }

}

6. Custom bean class.

file:MyBean.java . Class of method to be called.

 

package com.javanbeyond;

import org.apache.camel.Exchange;
import org.apache.camel.ExchangeProperty;
import org.apache.camel.Processor;

public class MyBean implements Processor {
  public void logMyMessage(String body,
      @ExchangeProperty(Exchange.TIMER_COUNTERString timerCount) {
    System.out.println("I am called with body : " + body);
    System.out.println("Timer Counter : " + timerCount);
  }

  public void process(Exchange exchangethrows Exception {
    System.out.print("Route Id: "+exchange.getFromRouteId());
    System.out.print("; Timer Counter : "
        + exchange.getProperty(Exchange.TIMER_COUNTER));
    System.out.println(
        "; Timer Name : " + exchange.getProperty(Exchange.TIMER_NAME));
  }
}

 

7a. Java DSL class

file: CamelJavaDSL.java . This class contains four routes for four different cases of calling java methods.

Case 1 : “usingBeanComponent”

In this method, bean method is called by bean component in the URI. The body of the bean method contains two parameters. The first parameter of type String is mapped to the body of the message and the other parameter which is annotated with  @ExchangeProperty injects the value of TIMER_COUNTER exchange property to “timerCount”. For a full list of annotations, please visit here.

Case 2 : “usingProcessor”

This case uses a processor to pass Exchange object to the process method of bean.

Case 3 : “usingBeanInvocation”

This case uses bean processor to call the same bean method of Case 1.

Case 4 : “usingClassComponent”

This case uses class component to call the same bean method of Case 1.

 

package com.javanbeyond;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.util.jndi.JndiContext;

public class CamelJavaDSL extends RouteBuilder {
  private static CamelContext context;

  public CamelJavaDSL() throws Exception {
    JndiContext jndiContext = new JndiContext();
    // The name which will be used to refer to this bean in route
    jndiContext.bind("IBean"new MyBean());
    context = new DefaultCamelContext(jndiContext);
    context.addRoutes(this);
    context.start();
  }

  @Override
  public void configure() throws Exception {
    // Timer repeats every 10 seconds
    // using bean component
    from("timer://javanbeyond?delay=2000&fixedRate=true&period=10000").autoStartup(false).routeId("usingBeanComponent")
     .setBody(simple("${routeId} - Hello bean."))
     .to("bean:IBean?method=logMyMessage");
    // using Processor
    from("timer://javanbeyond?delay=2000&fixedRate=true&period=10000").autoStartup(false).routeId("usingProcessor")
     .process(new MyBean());
    // using bean DSL
    from("timer://javanbeyond?delay=2000&fixedRate=true&period=10000").autoStartup(false).routeId("usingBeanInvocation")
     .setBody(simple("${routeId} - Hello bean."))
     .bean(MyBean.class, "logMyMessage");
    // using class component
    from("timer://javanbeyond?delay=2000&fixedRate=true&period=10000").autoStartup(false).routeId("usingClassComponent")
     .setBody(simple("${routeId} - Hello bean."))
     .to("class:com.javanbeyond.MyBean?method=logMyMessage");
  }

  public CamelContext getCamelContext() {
    return context;
  }

}

 

7b. Camel Spring XML DSL

file:camel-context.xml. Spring XML equivalent to Java 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">

	<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
		<route id="usingBeanComponent" autoStartup="false">
			<from
				uri="timer://javanbeyond?delay=2000&amp;fixedRate=true&amp;period=10000" />
			<setBody>
				<!-- Using simple expression to append string in message body -->
				<simple>${routeId} - Hello bean.</simple>
			</setBody>
			<to uri="bean:IBean?method=logMyMessage" />
		</route>
		<!-- Using processor to call process method of bean -->
		<route id="usingProcessor" autoStartup="false">
			<from
				uri="timer://javanbeyond?delay=2000&amp;fixedRate=true&amp;period=10000" />
			<process ref="IBean" />
		</route>
		<route id="usingBeanInvocation" autoStartup="false">
			<from
				uri="timer://javanbeyond?delay=2000&amp;fixedRate=true&amp;period=10000" />
			<setBody>
				<!-- Using simple expression to append string in message body -->
				<simple>${routeId} - Hello bean.</simple>
			</setBody>
			<bean ref="IBean" method="logMyMessage" />
		</route>
		<route id="usingClassComponent" autoStartup="false">
			<from
				uri="timer://javanbeyond?delay=2000&amp;fixedRate=true&amp;period=10000" />
			<setBody>
				<!-- Using simple expression to append string in message body -->
				<simple>${routeId} - Hello bean.</simple>
			</setBody>
			<to uri="class:com.javanbeyond.MyBean?method=logMyMessage" />
		</route>
	</camelContext>
	<bean id="IBean" class="com.javanbeyond.MyBean" />
</beans>

Example Execution:

Case 1:

  1. Make changes to Main class by calling either executeJavaDSL or executeSpringDSL with “usingBeanComponent” as argument and commenting other methods.
  2. Run the example by calling maven clean and install and passing either “xml” or “java” to the Main Class.
  3. You should see the following entry on eclipse console every 10 seconds.
I am called with body : usingBeanComponent - Hello bean.
Timer Counter : 1
I am called with body : usingBeanComponent - Hello bean.
Timer Counter : 2

Case 2:

  1. Make changes to Main class by calling either executeJavaDSL or executeSpringDSL with “usingProcessor” as argument and commenting other methods.
  2. Run the example by calling maven clean and install and passing either “xml” or “java” to the Main Class.
  3. You should see the following entry on eclipse console every 10 seconds.
Route Id: usingProcessor; Timer Counter : 1; Timer Name : javanbeyond
Route Id: usingProcessor; Timer Counter : 2; Timer Name : javanbeyond

Case 3: 

  1. Make changes to Main class by calling either executeJavaDSL or executeSpringDSL with “usingBeanInvocation” as argument and commenting other methods.
  2. Run the example by calling maven clean and install and passing either “xml” or “java” to the Main Class.
  3. You should see the following entry on eclipse console every 10 seconds.
I am called with body : usingBeanInvocation - Hello bean.
Timer Counter : 1
I am called with body : usingBeanInvocation - Hello bean.
Timer Counter : 2

Case 4:

  1. Make changes to Main class by calling either executeJavaDSL or executeSpringDSL with “usingClassComponent” as argument and commenting other methods.
  2. Run the example by calling maven clean and install and passing either “xml” or “java” to the Main Class.
  3. You should see the following entry on eclipse console every 10 seconds.
I am called with body : usingClassComponent - Hello bean.
Timer Counter : 1
I am called with body : usingClassComponent - Hello bean.
Timer Counter : 2

 

 

Leave a Reply

Back to Top
%d bloggers like this: