Search code examples
regexapache-camel

Only first when expression works in apache camel choice?


I have this route which check if body begins with "01" or "02" and calls different beans based on that. the problem is that only first one works. for example if I send a message beginning with "01" it works fine but if my message begins with "02" the otherwise part gets executed and i get the error message with an empty body.

<route id="genericService">
        <from uri="servlet:///genericService"/>
        <choice>
            <when>
                <simple>${body} regex "^01.*$"</simple>
                <bean ref="cardFacade" method="getBalance" />
            </when>
            <when>
                <simple>${body} regex "^02.*$"</simple>
                <bean ref="depositFacade" method="getBalance" />
            </when>
            <otherwise>
                <transform>
                    <simple>error:  ${body}</simple>
                </transform>
            </otherwise>
        </choice>
        <marshal>
            <json />
        </marshal>
        <transform>
            <simple>${body}</simple>
        </transform>
    </route>

Solution

  • The problem is the servlet component provides the body as a stream that is only readable once. So you need to either enable stream caching, or convert the message body to a non stream type such as String or byte[].

    You can find more details here

    And also see the 1st box on this page