Templates by BIGtheme NET

How to Use message filters in Camel Routers

Need of Message filters
1) Suppose QA department has expressed the need to be able to send test orders into the live
web front end of the order system.
2) In this case we required some message filter, that stop the QA messages so that they are not to be processed.
3) Incoming messages only pass through the filter if a certain condition is met.

15
A Message Filter allows you to filter out uninteresting messages based on some condition.
In this case, test messages are filtered out.

Example:
We have two orders one is Order_xml.xml valid order and another one Test_Order_xml.xml test order.
Order_xml.xml

Test_Order_xml.xml

We are providing the filter in java code as given, If in order element not fount test attribute, then only do process other wise ignore.
In Test_Order_xml.xml order, test is there then, this xml will be ignored. Other one Order_xml.xml not having test in order attribute. Then this will be processed.

from("file:/venkatjavasource/camel/from?noop=false").filter(xpath("/order[not(@test)]"))
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("Received XML order: " + exchange.getIn().getHeader("CamelFileName"));
} }).to("file:/venkatjavasource/camel/to/success");

Before running these java app, from directory is having two files.
16

UseMessageFiltersInCamelRouters.java

package com.venkatjavasource.camel;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class UseMessageFiltersInCamelRouters {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		CamelContext context = new DefaultCamelContext();
		context.addRoutes(new RouteBuilder() {
			public void configure() {
				from("file:/venkatjavasource/camel/from?noop=false").filter(xpath("/order[not(@test)]")).
				process(new Processor() {
					public void process(Exchange exchange) throws Exception {
							System.out.println("Received XML order: " + exchange.getIn().getHeader("CamelFileName"));
						}
					}).to("file:/venkatjavasource/camel/to/success");						
			}
		});

		context.start();
		Thread.sleep(10000);
		context.stop();
	}
}

Demo :
Right click select “Run As” -> “Java Application”.

Check in from and success folders.
17

But back has taken for both the files, as both are processed, but test order is filtered.
18

Now we check the success folder, this should have only one file.
19
Out Put
Received XML order: Order_xml.xml

Here only one file is processed, the test file is ignored.

*** Venkat – Happy leaning ****