[[contentBasedRouter-eip]]
= Content Based Router

The
http://www.enterpriseintegrationpatterns.com/ContentBasedRouter.html[Content
Based Router] from the xref:enterprise-integration-patterns.adoc[EIP
patterns] allows you to route messages to the correct destination based
on the contents of the message exchanges.

image::eip/ContentBasedRouter.gif[image]

The following example shows how to route a request from an input
*seda:a* endpoint to either *seda:b*, *seda:c* or *seda:d* depending on
the evaluation of various xref:manual:ROOT:predicate.adoc[Predicate] expressions

[source,java]
----
RouteBuilder builder = new RouteBuilder() {
    public void configure() {
        errorHandler(deadLetterChannel("mock:error"));
 
        from("direct:a")
            .choice()
                .when(header("foo").isEqualTo("bar"))
                    .to("direct:b")
                .when(header("foo").isEqualTo("cheese"))
                    .to("direct:c")
                .otherwise()
                    .to("direct:d");
    }
};
----

[TIP]
====
See
xref:manual:faq:why-can-i-not-use-when-or-otherwise-in-a-java-camel-route.adoc[Why
can I not use when or otherwise in a Java Camel route] if you have
problems with the Java DSL, accepting using `when` or `otherwise`.
====

== Using the xref:manual:ROOT:spring-xml-extensions.adoc[Spring XML Extensions]

[source,java]
----
<camelContext errorHandlerRef="errorHandler" xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="direct:a"/>
        <choice>
            <when>
                <xpath>$foo = 'bar'</xpath>
                <to uri="direct:b"/>
            </when>
            <when>
                <xpath>$foo = 'cheese'</xpath>
                <to uri="direct:c"/>
            </when>
            <otherwise>
                <to uri="direct:d"/>
            </otherwise>
        </choice>
    </route>
</camelContext>
----

For further examples of this pattern in use you could look at the
https://github.com/apache/camel/blob/main/core/camel-core/src/test/java/org/apache/camel/processor/ChoiceTest.java[junit test case].

[[ContentBasedRouter-UsingThisPattern]]
== Using This Pattern

If you would like to use this EIP Pattern then please read the
xref:manual:ROOT:getting-started.adoc[Getting Started]. You may also find the
xref:manual:ROOT:architecture.adoc[Architecture] useful particularly the description
of xref:manual:ROOT:endpoint.adoc[Endpoint] and xref:manual:ROOT:uris.adoc[URIs]. Then you could
try out some of the xref:manual:ROOT:examples.adoc[Examples] first before trying
this pattern out.
