3. Loop
The Loop allows to process the a message a number of times and possibly process them in a different way.
Example
The following example shows how to take a request from the direct:x endpoint , then send the message repetitively to "mock:result". The number of times the message is sent is either passed as an argument to loop(), or determined at runtime by evaluating an _expression_. The _expression_ must evaluate to an int, otherwise a RuntimeCamelException is thrown.
Using the Fluent Builders
Pass loop count as an argument
from("direct:a").loop(8).to("mock:result");
Use _expression_ to determine loop count
from("direct:b").loop(header("loop")).to("mock:result");
Use _expression_ to determine loop count
from("direct:c").loop().xpath("/hello/@times").to("mock:result");
Using the Spring XML Extensions
Pass loop count as an argument
<route>
<from uri="direct:a"/>
<loop>
<constant>8</constant>
<to uri="mock:result"/>
</loop>
</route>
Use _expression_ to determine loop count
<route>
<from uri="direct:b"/>
<loop>
<header>loop</header>
<to uri="mock:result"/>
</loop>
</route>
<route>
<from uri="direct:c"/>
<loop>
<xpath>/hello/@times</xpath>
<to uri="mock:result"/>
</loop>
</route>
<route>
<from uri="direct:d"/>
<loop>
<constant>2</constant>
<to uri="mock:result"/>
</loop>
<to uri="mock:last"/>
</route>
<route>
<from uri="direct:e"/>
<loop>
<constant>10</constant>
<process ref="myProcessor"/>
<to uri="mock:result"/>
</loop>
</route>
</camelContext>
<bean id="myProcessor" class="org.apache.camel.processor.LoopTestProcessor">
<constructor-arg index="0" value="10"/>
</bean>
</beans>
Use _expression_ to determine loop count
<route>
<from uri="direct:c"/>
<loop>
<xpath>/hello/@times</xpath>
<to uri="mock:result"/>
</loop>
</route>
<route>
<from uri="direct:d"/>
<loop>
<constant>2</constant>
<to uri="mock:result"/>
</loop>
<to uri="mock:last"/>
</route>
<route>
<from uri="direct:e"/>
<loop>
<constant>10</constant>
<process ref="myProcessor"/>
<to uri="mock:result"/>
</loop>
</route>
</camelContext>
<bean id="myProcessor" class="org.apache.camel.processor.LoopTestProcessor">
<constructor-arg index="0" value="10"/>
</bean>
</beans>
For further examples of this pattern in use you could look at one of the junit test case![]()
Using This Pattern
If you would like to use this EIP Pattern then please read the Getting Started, you may also find the Architecture useful particularly the description of Endpoint and URIs. Then you could try out some of the Examples first before trying this pattern out.