Choice

The Content Based Router from the EIP patterns allows you to route messages to the correct destination based on the contents of the message exchanges.

image

Choice options

The Choice EIP supports 2 options which are listed below:

Name Description Default Type

whenClauses

Sets the when clauses

List

otherwise

Sets the otherwise node

OtherwiseDefinition

Examples

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 Predicate expressions

RouteBuilder builder = new RouteBuilder() {
    public void configure() {
        from("direct:a")
            .choice()
                .when(simple("${header.foo} == 'bar'"))
                    .to("direct:b")
                .when(simple("${header.foo} == 'cheese'"))
                    .to("direct:c")
                .otherwise()
                    .to("direct:d");
    }
};

And the same example using XML:

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="direct:a"/>
        <choice>
            <when>
                <simple>${header.foo} == 'bar'</simple>
                <to uri="direct:b"/>
            </when>
            <when>
                <simple>${header.foo} == 'cheese'</simple>
                <to uri="direct:c"/>
            </when>
            <otherwise>
                <to uri="direct:d"/>
            </otherwise>
        </choice>
    </route>
</camelContext>

Usage of endChoice and end

Usage of endChoice is not mandatory. However, It should be used whenever you want to return back control to choice() dsl so that you can add subsequent when and otherwise to the choice dsl. If you want to end entire choice() block use end().

Example

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .choice()
                        .when(body().contains("Camel"))
                        .multicast()
                            .to("mock:foo")
                            .to("mock:bar")
                        .endChoice() //we need to use endChoice to tell Java DSL to return scope back to the choice DSL.
                        .otherwise()
                            .to("mock:result");
            }
        };
    }

Another example is explained in the TIP below.

See 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.