With Groovy you can say a closure implements an interface. This allows us to embed Groovy code inline as a Processor in a Camel route.
from("jetty:http://localhost:8080/hello") .process({Exchange exchange -> exchange.out.setBody "Hello World" } as Processor)
We can go one step futher by taking advantage of Groovy's dynamic metaClass to create our own method which takes a closure directly. The following adds a new method 'x' to the RouteDefinition class.
RouteDefinition.metaClass.x = {Closure c -> ((RouteDefinition)delegate).process(c as Processor)}
Our route definition now becomes much more elegant
from("jetty:http://localhost:8080/hello") .x {Exchange ex -> ex.out.setBody "Hello"} .x {Exchange ex -> ex.out.body = ex.in.body + " World"}
Add in some Grab annotations from Groovy's Grape extension to automatically download the Camel libraries and the whole thing becomes a single, small, self-contained script.
#!/usr/bin/env groovy @Grab(group="org.apache.camel", module="camel-core", version="2.5.0") @Grab(group="org.apache.camel", module="camel-jetty", version="2.5.0") import org.apache.camel.CamelContext import org.apache.camel.impl.DefaultCamelContext import org.apache.camel.builder.RouteBuilder import org.apache.camel.Processor import org.apache.camel.Exchange import org.apache.camel.model.RouteDefinition RouteDefinition.metaClass.x = {Closure c -> ((RouteDefinition)delegate).process(c as Processor)} CamelContext cxt = new DefaultCamelContext() cxt.addRoutes(new RouteBuilder(){ void configure(){ from("jetty:http://localhost:8080/hello") .x {Exchange ex -> ex.out.setBody "Hello"} .x {Exchange ex -> ex.out.body = ex.in.body + " World"} } }) cxt.start()
Cool stuff, would be nice to have a full-blown Groovy DSL ESB once!
ReplyDelete