siliconsenthil.in

Apache Camel With Scala: Extending DSL

Let’s take a very simple use case of integrating with a http endpoint which has an authentication mechanism.

    from("someWhere")
      //Do some processing
      .setHeader("Authorization", _ => "OAuth anObfuscatedTokenString")
      .setHeader(Exchange.HTTP_METHOD, "GET")
      .to("http://someServer.com")
      .process(//Do something with response)

    from("someWhereElse")
      //Do some processing
      .setHeader("Authorization", _ => "OAuth anObfuscatedTokenString")
      .setHeader(Exchange.HTTP_METHOD, "POST")
      .to("http://someServer.com")
      .process(//Do something with response)

You can clearly see if have many routes like this, there will be a lot of duplication.

So we wanted to extend the DSL so that these kind of duplications are avoided and we could come up with more readable routes.

We created an implicit class and add method like toSomeServer which abstrats the details.

object DSLImplicits {
  implicit class RichDSL(val dsl: DSL) {
    def toSomeServer = {
      dsl.setHeader("Authorization", _ => "OAuth anObfuscatedTokenString")
          .to("http://someServer.com")
    }

    def get = dsl.setHeader(Exchange.HTTP_METHOD, _ => HttpMethods.GET.name)

    def post = dsl.setHeader(Exchange.HTTP_METHOD, _ => HttpMethods.POST.name)
  }
}

The above extention can be used like this.

import DSLImplicits.RichDSL
//----------------------------
from("someWhere")
  //Do some processing
  .get.toSomeServer
  .process(//Do something with response)

from("someWhereElse")
  //Do some processing
  .post.toSomeServer
  .process(//Do something with response)

You can clearly see this ends with more readable route.

This is is not possible with java dsl. As given here extending can be possible with Groovy based DSL too.

Comments