Camel meets Elvis

Last weekend, I was supposed to write on chapter 10 for the Camel in Action book, but I got side tracked with the prospect of Camel meeting Elvis.

A FUSE customer is in due time to upgrade to from Apache Camel 1.x to 2.x and they are currently using the Spring XML to define routes. They are using the Content Based Router EIP with predicates. As Camel 1.x is not as rich in its Spring XML they had to write those predicates in Java code. In Camel 2.x the Camel EL, known as the Simple language, can be used for most common use case for defining predicates.
However they are using predicates which accessing a header which is a Map value, which they then index. This is currently not possible to do with Apache Camel 2.2, as the simple language can only, retrieve the header value.

In this light we could easily add special support for using a syntax like this: header.name[key] to support their use case. This was easy to implement, in a matter of minutes, ah okay, lets say 1 hour at most.

However then it occurred to me as I have previously thought of adding a OGNL to the Camel Simple language. Its not a full blown OGNL like: Mvel, OGNL or the dynamic programming languages: Groovy, JuEL, JavaScript etc. But still a simple OGNL that will raise the bar that the Camel EL can solve out of the box, from 80% to 95% :).

So in the weekend, my wife had other plans, leaving me with plenty of time to give it a go. After having implemented a fair bit of the OGNL so you can invoke methods, access Map/List etc. it occurred to me that Camel must meet Elvis.

Its of course not the king himself, but the mr Elvis Operator. Which means you can do ?. in the OGNL notation.

Suppose you have a User object on a Message and want to test whether an address has a zip code in a certain range.

For example you can do:
  ${body?.address?.zip} between 5000..5999

Notice how we can use the elvis operator to avoid the NPE. If the User object do not have an address the predicate will return false.

I have updated the Camel Simple wiki page with a few more examples, if you want to learn more.
And btw the Bean language also supports this new OGNL.

I have though of adding it to the Bean component as well, so you can do in an endpoint

But currently it cannot do this. Any thoughts?
This new feature will be available in Apache Camel 2.3.

PS: I have started on chapter 10

1 comment:

Claus Ibsen said...

Been so long time since I last hacked with Groovy that I forgot that ?: is the tenary operator which is the evlis operator.

Obviously we want the NPE avoider so its the null-safe operator which has been added, and not mr Elivs.

Sorry for the mix up. But hey we got what we wanted which is to avoid the NPEs.