Understanding Apache Camel Interceptors Using Example | JavaInUse







Understanding Apache Camel Interceptors

The intercept feature in Camel supports intercepting Exchanges while they are en route. We have overhauled the Intercept in Camel 2.0 so the following information is based on Camel 2.0. Camel supports three kinds of interceptors:
  • intercept that intercepts each and every processing step while routing an Exchange in the route.
  • interceptFrom that intercepts incoming Exchange in the route.
  • interceptSendToEndpoint that intercepts when an Exchange is about to be sent to the given Endpoint.
For this tutorial we will be taking reference of the Apache Camel+ JMS tutorial we had implemented before.

Apache Camel - Table of Contents

File Transfer Using Java DSL Apache Camel Apache Camel Java DSL + Spring Integration Hello World Example Apache Camel Exception Handling Using Simple Example Apache Camel Redelivery policy using example Integrate Apache Camel and ActiveMQ EIP patterns using Apache Camel Apache Camel Tutorial- Integrate Spring Boot+ Apache Camel Apache Camel Tutorial- Integrate with MySQL DB using SQL query Apache Camel + Spring + ActiveMQ + JBoss Fuse Apache Camel EIP - Splitter and Aggregator pattern Apache Camel Unit Testing Apache Camel + Spring + Quartz Hello World Example Camel application deployment on JBoss Fuse Apache Camel + Apache CXF SOAP Webservices Apache Camel + JAX-RS REST Webservice Apache Camel + CXFRS REST Webservice Apache Camel Routing Slip EIP Pattern Apache Camel Dynamic Router Pattern Apache Camel Load Balancer EIP Pattern Apache Camel Interceptors Apache Camel + Kafka Hello World Example Apache Camel - Marshalling/Unmarshalling XML/JSON Data Example

Lets Begin

We will create Eclipse maven project as follows-

Apache Camel Interceptor Tutorial
Our pom file will be as follows-
<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-load-balancer</artifactId>
	<version>0.0.1-SNAPSHOT</version>

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

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

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

		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-client</artifactId>
			<version>5.10.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-pool</artifactId>
			<version>5.10.1</version>
		</dependency>
	</dependencies>
</project>
  • Intercept that intercepts each and every processing step while routing an Exchange in the route


    Apache Camel Interceptor Example
    Define the route.
    package com.javainuse;
    
    import org.apache.camel.Exchange;
    import org.apache.camel.Processor;
    import org.apache.camel.builder.RouteBuilder;
    
    public class SimpleRouteBuilder extends RouteBuilder {
    
    	int count;
    
    	@Override
    	public void configure() throws Exception {
    
    		intercept().process(new Processor() {
    			public void process(Exchange exchange) {
    				count++;
    				System.out.println("interceptor called " + count + " times " + exchange.getIn().getBody());
    
    			}
    		});
    		from("file:C:/inbox?noop=true").split().tokenize("\n").to("jms:queue:javainuse1").to("jms:queue:javainuse2");
    	}
    
    }
    
    When Camel is started, it creates a CamelContext object that contains the definition of the Route to be started. Below we create default camel context and load the routes created in SimpleRouteBuilder.
    package com.javainuse;
    
    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 MainApp {
    
        public static void main(String[] args) {
            SimpleRouteBuilder routeBuilder = new SimpleRouteBuilder();
            CamelContext ctx = new DefaultCamelContext();
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://0.0.0.0:61616");
            //define the jms component
            ctx.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
            try {
                ctx.addRoutes(routeBuilder);
                ctx.start();
                Thread.sleep(5 * 60 * 1000);
                ctx.stop();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }
    
    Next run the MainApp class as a java application. We can see the output as follows-
    Apache Camel Interceptor
  • InterceptFrom that intercepts incoming Exchange in the route


    Apache Camel Interceptor Incoming Request
    Define the route.
    package com.javainuse;
    
    import org.apache.camel.Exchange;
    import org.apache.camel.Processor;
    import org.apache.camel.builder.RouteBuilder;
    
    public class SimpleRouteBuilder 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:C:/inbox?noop=true").split().tokenize("\n").to("jms:queue:javainuse1");
    		from("jms:queue:javainuse1").to("jms:queue:javainuse2");
    		from("jms:queue:javainuse2").to("jms:queue:javainuse3");
    		
    	}
    
    }
    
    When Camel is started, it creates a CamelContext object that contains the definition of the Route to be started. Below we create default camel context and load the routes created in SimpleRouteBuilder.
    package com.javainuse;
    
    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 MainApp {
    
        public static void main(String[] args) {
            SimpleRouteBuilder routeBuilder = new SimpleRouteBuilder();
            CamelContext ctx = new DefaultCamelContext();
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://0.0.0.0:61616");
            //define the jms component
            ctx.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
            try {
                ctx.addRoutes(routeBuilder);
                ctx.start();
                Thread.sleep(5 * 60 * 1000);
                ctx.stop();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }
    
    Next run the MainApp class as a java application. We can see the output as follows-
    Apache Camel Interceptor Run
  • InterceptSendToEndpoint that intercepts when an Exchange is about to be sent to the given Endpoint


    Apache Camel Exchange
    Define the route.
    package com.javainuse;
    
    import org.apache.camel.Exchange;
    import org.apache.camel.Processor;
    import org.apache.camel.builder.RouteBuilder;
    
    public class SimpleRouteBuilder extends RouteBuilder {
    
    	int count;
    
    	@Override
    	public void configure() throws Exception {
    
    		interceptSendToEndpoint("jms:queue:javainuse2").process(new Processor() {
    			public void process(Exchange exchange) {
    				count++;
    				System.out.println("interceptor called "+ count +" times "+exchange.getIn().getBody());
    				
    			}
    		});
    		
    		from("file:C:/inbox?noop=true").split().tokenize("\n").to("jms:queue:javainuse1");
    		from("jms:queue:javainuse1").to("jms:queue:javainuse2");
    	}
    
    }
    
    When Camel is started, it creates a CamelContext object that contains the definition of the Route to be started. Below we create default camel context and load the routes created in SimpleRouteBuilder.
    package com.javainuse;
    
    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 MainApp {
    
        public static void main(String[] args) {
            SimpleRouteBuilder routeBuilder = new SimpleRouteBuilder();
            CamelContext ctx = new DefaultCamelContext();
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://0.0.0.0:61616");
            //define the jms component
            ctx.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
            try {
                ctx.addRoutes(routeBuilder);
                ctx.start();
                Thread.sleep(5 * 60 * 1000);
                ctx.stop();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }
    
    Next run the MainApp class as a java application. We can see the output as follows-
    Apache Camel Intercpetor Output

Download Source Code

Download it - Apache Camel Interceptor Example

See Also

Spring Boot Hello World Application- Create simple controller and jsp view using Maven Spring Boot Tutorial-Spring Data JPA Spring Boot + Simple Security Configuration Pagination using Spring Boot Simple Example Spring Boot + ActiveMQ Hello world Example Spring Boot + Swagger Example Hello World Example Spring Boot + Swagger- Understanding the various Swagger Annotations Spring Boot Main Menu Spring Boot Interview Questions