Nirbhay Mishra
Nirbhay Mishra

Reputation: 1648

How can I loop in Apache Camel

<setHeader headerName="smsRecivers"><simple>{{reciversList}}</simple></setHeader>

I have a list mobile numbers(in comma separated form reciversList=999999999,88888888,799999999 ) and I have to send each a sms, looping through reciversList list

some thing like

<loop on="reciversList">
   // so some work
</loop>

I looked in to loop function it have a constant number.

Upvotes: 4

Views: 17371

Answers (2)

AndyN
AndyN

Reputation: 2105

If you want to split on a header value rather than the body of a message, you can use the Camel Splitter EIP and write your own method to handle the split.

Your route will look something like this:

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="direct:start"/>
        <split>
            <method ref="splitterBean" method="split"/>
            Process each SMS here
        </split>
    </route>
</camelContext>

And you can then use the MySplitterBean example in the Apache Splitter page, and write a method like so:

 public List<Message> split(@Header(value = "smsReceivers") String header, @Body String body) {
    List<Message> answer = new ArrayList<Message>();
    // Perform header null checking here
    header = header.substring(header.indexOf("=")+1); // Remove var name
    String[] parts = header.split(",");
    for (String part : parts) {
        DefaultMessage message = new DefaultMessage();
        message.setHeader("smsReceiver", part);
        message.setBody(body);
        answer.add(message);
    }
    return answer;
} 

Within the loop, you can then simply access the SMS number through the "smsReceiver" header.

Upvotes: 4

Alexey Yakunin
Alexey Yakunin

Reputation: 1771

You can use loop : http://camel.apache.org/loop.html

<route>
  <setHeader headerName="smsRecivers">
     <simple>{{reciversList}}</simple>
  </setHeader>
  <loop>
    <simple>${in.header.smsRecivers.size}</simple>
    .....
  </loop>
</route>

Inside loop body you can get list's item by index, using excange property CamelLoopIndex or you can use custom increment index ( which can calculate in other header ).

Upvotes: 4

Related Questions