Message Filter

If there is a requirement to avoid unnecessary or undesired messages (like a spam filter), then there is a special type of message router called a Message Filter. This integration pattern will eliminate messages from a channel based on a defined set of criteria.

This type of pattern only utilizes a single output channel. If the message content matches the criteria specified by the Message Filter, then the message will be routed to the designated output channel. However, if the contents of the message don’t meet the criteria for inclusion, then the message is discarded.

Message Filter pattern

 

For example, assume that the enterprise publicizes price changes and promotions to their best customers. Thus, whenever an item’s price changes, a message will be created and sent to all customers. But, there may be some customers that have disabled this type of notification and therefore these messages would need to be eliminated.

Message Filter using XML DSL

In this example, we are interpreting contents in the message header:

<route> <from uri="direct:in"/> <filter> <simple>${header.myValue} == 'hello'</simple> <to uri="direct:hello"/> </filter> <to uri="direct:out"/> </route>

 

Message Filter using Beans

Here is an example of using a bean to define the filter behavior:

from("direct:start") .filter().method(MyBean.class, "isGoldCustomer").to("mock:result").end() .to("mock:end"); public static class MyBean { public boolean isGoldCustomer(@Header("level") String level) { return level.equals("gold"); } }