
Filtering out unwanted messages
When you need to perform a sequence of steps only when a message matches a certain condition (Predicate), then a Filter is a good option.

Content Based Routing and Filtering are very similar. Filtering processes a message only if it matches the single predicate provided (much like a single if
statement).
A Content Based Router routes a message based on the first of the multiple predicates, or the optional otherwise
statement if none of the provided predicates matched (similar to an if () {..} else if () {..} else {..}
statement in Java).
This recipe will show you how to perform message processing steps only on those messages that match a specified predicate.
Getting ready
The Java code for this recipe is located in the org.camelcookbook.routing.filtering
package. The Spring XML files are located under src/main/resources/META-INF/spring
and prefixed with filtering
.
How to do it...
Create a filter
statement followed by a predicate using any of the Camel Expression Languages. After the predicate, specify one or more processor steps (multiple processor steps are executed in sequence, by default).
In the XML DSL, this routing logic is written as follows:
<filter> <simple>${body} regex '^C.*'</simple> <to uri="mock:C"/> </filter>
In the Java DSL, the same thing is written as:
.filter() .simple("${body} regex '^C.*'") .to("mock:C") .end()
How it works...
Camel's Filtering depends on Camel's Predicate capabilities. The preceding example uses Camel's Simple Expression Language. The Simple Expression Language provides a robust set of operators that can work on all of the data contained within the Camel exchange (message, headers, and properties). Each filter
element requires one predicate, which can be any one of the many built-in Camel Expression Languages, including any one of the POJO (Plain Old Java Object) methods that returns a boolean
value. The message will be routed to the one or more processor steps specified after the predicate expression of when
, by default executing multiple steps as a Pipeline , that is, in sequence.
There's more...
Camel will set a boolean
property on the exchange named CamelFilterMatched
(defined as a constant, Exchange.FILTER_MATCHED
). It will be set to true
if the message matched the previous Filter's predicate. Be careful if you have multiple Filter statements, as the FilterMatched
property will be set to true
or false
by each Filter's predicate, meaning it will represent the value of the last Filter's predicate that processed the message.