Apache Camel: can I put multiple statements in the when part of the conditional choice statement?

opstalj picture opstalj · Feb 10, 2012 · Viewed 20.6k times · Source

I would like to obtain the following kind of routing:

  1. HTTP POST message with XML body enters CAMEL
  2. I store some of the parameters of the XML body
  3. The message is routed to an external endpoint
  4. The external endpoint (external server) replies

-> at this moment, I would like to check whether the reply from the external endpoint is a HTTP 200 OK containing a XML parameter equal to SUCCESS. -> if so, then I would like to use some of the stored parameters to construct a new HTTP message (method = PUT this time) and send it out to an external endpoint

Problem that I am currently having, is the following:

.choice()
 .when(simple("${in.headers.CamelHttpResponseCode} == 200"))
   // now I want do a few things, eg: check also the XML body via xpath
   // and change the message to be sent out (change Method to PUT, ...)
    .to("http://myserver.com")
 .otherwise()
   // if no 200 OK, I want the route to be stopped ... not sure how ?
.end()

Question: any idea how to add those extra statements in case the HTTP response code was 200 OK ? It looks like the when does not allow me to add extra statements ... (I got an error in my Eclipse IDE).

Thanks in advance.

Note: could it be that I have to route the message in case the 200 OK matches to a 'new endpoint' and then create a new from route with this new endpoint ? Eg:

.choice()
     .when(simple("${in.headers.CamelHttpResponseCode} == 200"))
        .to("mynewendpoint")
     .otherwise()
       // if no 200 OK, I want the route to be stopped ... not sure how ?
    .end();

 from("mynewendpoint").
  .setHeader(etc etc)
  .to("http://myserver.com")

In this latter case, how exactly should I define this 'newendpoint' ?

Answer

Claus Ibsen picture Claus Ibsen · Feb 14, 2012

In the programming language DSLs such as Java, you can build predicates together. I posted a blog entry some years ago about this at: http://davsclaus.blogspot.com/2009/02/apache-camel-and-using-compound.html

For example having two predicates

Predicate p1 = header("hl7.msh.messageType").isEqualTo("ORM"):
Predicate p2 = header("hl7.msh.triggerEvent").isEqualTo("001");

You can chain them together, using and or or.

Predicate isOrm = PredicateBuilder.and(p1, p2);

And then you can use isOrm in the route

from("hl7listener")
    .unmarshal(hl7format)
    .choice()
        .when(isOrm).beanRef("hl7handler", "handleORM")
        .otherwise().beanRef("hl7handler", "badMessage")
    .end()
    .marshal(hl7format);