Filter

The Message Filter from the EIP patterns allows you to filter messages.

The message filter implemented in Camel is similar to if (predicate) { block } in Java. The filter will include the message if the predicate evaluated to true.
image

EIP options

The Filter eip has no options.

Example

The Camel Simple language is great to use with the Filter EIP when routing is based on the content of the message, such as checking message headers.

from("direct:a")
    .filter(simple("${header.foo} == 'bar'"))
        .to("direct:bar")
    .end()
    .to("direct:b")

And in XML:

<route>
    <from uri="direct:a"/>
    <filter>
        <simple>${header.foo} == 'bar'</simple>
        <to uri="direct:bar"/>
    </filter>
    <to uri="direct:b"/>
</route>

You can use many languages as the predicate, such as XPath:

from("direct:start").
        filter().xpath("/person[@name='James']").
        to("mock:result");

And in XML:

<route>
    <from uri="direct:start"/>
    <filter>
        <xpath>/person[@name='James']</xpath>
        <to uri="mock:result"/>
    </filter>
</route>

Here is another example of calling a method on a bean to define the filter behavior:

from("direct:start")
    .filter().method(MyBean.class, "isGoldCustomer")
      .to("mock:gold")
    .end()
    .to("mock:all");
}

And then bean can have a method that returns a boolean as the predicate:

public static class MyBean {

    public boolean isGoldCustomer(@Header("level") String level) {
        return level.equals("gold");
    }

}

And in XML we can call the bean in `<method> where we can specify the FQN classname of the bean as shown:

<route>
    <from uri="direct:start"/>
    <filter>
        <method type="com.foo.MyBean" method="isGoldCustomer"/>
        <to uri="mock:gold"/>
    </filter>
    <to uri="mock:all"/>
</route>

Filtering and stopping

When using the Message Filter EIP, then it only applies to its children.

For example in the previous example:

<route>
    <from uri="direct:start"/>
    <filter>
        <method type="com.foo.MyBean" method="isGoldCustomer"/>
        <to uri="mock:gold"/>
    </filter>
    <to uri="mock:all"/>
</route>

Then for a message that is a gold customer will be routed to both mock:gold and mock:all (predicate is true). However, for a non-gold message (predicate is false) then the message will not be routed in the filter block, but will be routed to mock:all.

Sometimes you may want to stop continue routing for messages that was filtered. To do this, you can use the Stop EIP as shown:

<route>
    <from uri="direct:start"/>
    <filter>
        <method type="com.foo.MyBean" method="isGoldCustomer"/>
        <to uri="mock:gold"/>
        <stop/>
    </filter>
    <to uri="mock:all"/>
</route>