Apache Camel

Apache Camel Interceptor Example

1. Introduction

This is an in-depth article related to the Apache Camel Interceptor. Apache Camel is open source java package to process data and integrate with other applications. You can use an interceptor to intercept the data during an exchange in the route. The exchange can be incoming or en route.

2. Apache Camel Interceptor

2.1 Prerequisites

Java 7 or 8 is required on the Linux, windows, or Mac operating system. Maven 3.6.1 is required. Apache MQ 5.16.1 and Camel 2.25.2 are used in this example.

2.2 Download

You can download Java 8 can be downloaded from the Oracle website. Apache Maven 3.6.1 can be downloaded from the Apache site. Apache MQ 5.16.1 can be downloaded from the Apache MQ Website.

2.3 Setup

You can set the environment variables for JAVA_HOME and PATH. They can be set as shown below:

Setup

JAVA_HOME="/desktop/jdk1.8.0_73"
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH

The environment variables for maven are set as below:

Maven Environment

JAVA_HOME=”/jboss/jdk1.8.0_73″
export M2_HOME=/users/bhagvan.kommadi/Desktop/apache-maven-3.6.1
export M2=$M2_HOME/bin
export PATH=$M2:$PATH

2.4 How to download and install ActiveMQ

You can extract the archive downloaded from the Apache ActiveMQ site to a folder.

2.5 Apache Camel

Apache Camel can be used to integrate with web services and other applications like SalesForce, Twitter, and Facebook. Apache Camel has around 320 open source components. Apache Camel is based on pipes pattern. The Camel toolkit has a set of adapters to integrate different systems and applications. Different use cases relevant to apache camel integration are sending invoices to Accounts Department, reading data and uploading them to web folders, receiving messages from the message queues and processing them, and calling a web service to get user details from the data source.

2.6 Apache Camel Interceptor Example

Now let us look at the Camel interceptor. To start with, Routes are used to move data from source to destination. It is based on a pipes pattern. The source and destination are endpoints. Routes are written in Java. Below is the sample route in Java :

ExampleRoute

package org.javacodegeeks;

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

public class ExampleRouteBuilder extends RouteBuilder {

	int count;

	@Override
	public void configure() throws Exception {

		interceptFrom("*").process(new Processor() {
			public void process(Exchange exchange) {
				count++;
				System.out.println("interceptor called " + count + " times " + exchange.getIn().getBody());

			}
		});

		from("file:mailbox?noop=true").split().tokenize("\n").to("jms:queue:javacodegeeks1");
		from("jms:queue:javacodegeeks1").to("jms:queue:javacodegeeks2");
		from("jms:queue:javacodegeeks2").to("jms:queue:javacodegeeks3");
	}

}

In the above code, endpoints are written at the bottom of the configure method for different routes. Endpoints are defined in URI-like syntax. The configure method has the information for processing routes. Now let us look at the example app where camel context is created and ExampleRouteBuilder routes are created. The sample code is shown below:

ExampleApplication

package org.javacodegeeks;

import javax.jms.ConnectionFactory;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.CamelContext;
import org.apache.camel.component.jms.JmsComponent;
import org.apache.camel.impl.DefaultCamelContext;

public class ExampleApplication {

	public static void main(String[] args) {
		ExampleRouteBuilder routeBuilder = new ExampleRouteBuilder();
		CamelContext context = new DefaultCamelContext();
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://0.0.0.0:61616");
		context.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
		try {
			context.addRoutes(routeBuilder);
			context.start();
			Thread.sleep(5 * 60 * 1000);
			context.stop();
		} catch (Exception exception) {
			exception.printStackTrace();
		}

	}
}

You can start the Active MQ server by using the command below:

ActiveMQ start

./activemq start

You can use the maven pom.xml attached below for building the camel code.

Maven POM

<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.javainuse</groupId>
	<artifactId>camel-dynamic-router</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-core</artifactId>
			<version>2.25.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-jms</artifactId>
			<version>2.25.2</version>
		</dependency>

		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-camel</artifactId>
			<version>5.16.1</version>
		</dependency>

		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-broker</artifactId>
			<version>5.16.1</version>
		</dependency>

		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-client</artifactId>
			<version>5.16.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-pool</artifactId>
			<version>5.16.1</version>
		</dependency>
	</dependencies>
</project>

You can start building the project by using the maven command

Maven Compile

mvn package

The output of the above command when executed is shown below:

Maven Output

apples-MacBook-Air:apachecamel bhagvan.kommadi$ mvn package
[INFO] Scanning for projects...
[INFO] 
[INFO] ----------------------------------
[INFO] Building camel-dynamic-router 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ camel-dynamic-router ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ camel-dynamic-router ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 2 source files to /Users/bhagvan.kommadi/OldDesk/JavacodeGeeks/Code/apachecamel/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ camel-dynamic-router ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ camel-dynamic-router ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ camel-dynamic-router ---
[INFO] 
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ camel-dynamic-router ---
[INFO] Building jar: /Users/bhagvan.kommadi/OldDesk/JavacodeGeeks/Code/apachecamel/target/camel-dynamic-router-0.0.1-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.658 s
[INFO] Finished at: 2022-01-17T01:28:47+05:30
[INFO] ------------------------------------------------------------------------

Now you can run the code using the command below:

Apache Camel Maven Command

java -cp  /Users/bhagvan.kommadi/olddesk/javacodegeeks/code/apachecamel/target/camel-dynamic-router-0.0.1-SNAPSHOT.jar:/Users/bhagvan.kommadi/olddesk/apache-activemq-5.16.1/activemq-all-5.16.1.jar org.javacodegeeks.ExampleApplication

The output of the command above when executed is shown below:

Apache Camel Execution

apples-MacBook-Air:apachecamel bhagvan.kommadi$ java -cp  /Users/bhagvan.kommadi/olddesk/javacodegeeks/code/apachecamel/target/camel-dynamic-router-0.0.1-SNAPSHOT.jar:/Users/bhagvan.kommadi/olddesk/apache-activemq-5.16.1/activemq-all-5.16.1.jar org.javacodegeeks.ExampleApplication
 INFO | Apache Camel 2.25.2 (CamelContext: camel-1) is starting
 INFO | JMX is enabled
 INFO | Type converters loaded (core: 195, classpath: 3)
 INFO | StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
 INFO | Endpoint is configured with noop=true so forcing endpoint to be idempotent as well
 INFO | Using default memory based idempotent repository with cache max size: 1000
 INFO | Route: route1 started and consuming from: file://mailbox?noop=true
 INFO | Route: route2 started and consuming from: jms://queue:javacodegeeks1
 INFO | Route: route3 started and consuming from: jms://queue:javacodegeeks2
 INFO | Total 3 routes, of which 3 are started
 INFO | Apache Camel 2.25.2 (CamelContext: camel-1) started in 1.107 seconds

3. Download the Source Code

Download
You can download the full source code of this example here: Apache Camel Interceptor Example

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button