Showing posts with label Groovy. Show all posts
Showing posts with label Groovy. Show all posts

Sunday, August 21, 2011

Quick RESTful web services with the Camel cxfbean component

Trying to create a REST web service using the old Camel cxfrs component was somewhat a pain and not very intuitive in my opinion. It was such a pain I didn't even want to write an example post for it. I really wanted something more automated like Jersey.

Luckly the Apache Camel cxfbean component makes putting together a REST web service much easier. Just annotate your service class and use it as the resource for the cxfbean component.

#!/usr/bin/env groovy

@Grab(group="org.apache.camel", module="camel-core", version="2.8.0")
@Grab(group="org.apache.camel", module="camel-jetty", version="2.8.0")
@Grab(group="org.apache.camel", module="camel-cxf", version="2.8.0")
@Grab(group='ch.qos.logback', module='logback-classic', version='0.9.29')
import org.apache.camel.CamelContext
import org.apache.camel.impl.DefaultCamelContext
import org.apache.camel.impl.SimpleRegistry
import org.apache.camel.builder.RouteBuilder

import javax.ws.rs.*


@Path("/example")
class MyExampleResource{

  @GET
  @Produces("text/plain")
  @Path("hello")
  public String hello(){
    "Hello World!"
  }
}

CamelContext cxt = new DefaultCamelContext()
cxt.registry = new SimpleRegistry()
cxt.registry.registry.put("myResources", [new MyExampleResource()])

cxt.addRoutes(new RouteBuilder(){
  void configure(){
    from("jetty:http://localhost:8080?matchOnUriPrefix=true")
    .to("cxfbean:myResources")
  }
})

cxt.start()

If you want to produce and consume a data format like JSON, you simply pass the necessary processor to the list of cxfbean processors. The CXF libaries include a JSON processor that you can quickly hook up - but I ran into a couple of issues. First you have to annotate your data classes with JAXB annotations (which you may not be able to do depending on your situation.) Second the processor tried to marshal all bean properties (methods that start with get.)

Since I was using Groovy I ran into an issue where Groovy automatically adds a getMetaClass method that returns an Interface and the CXF JSON processor didn't like that. Without an obvious way to tell the processor not to do that I decided to write my own quick processor using the GSON library. Here is a complete example which marshals data in and out from JSON format.

#!/usr/bin/env groovy

@Grab(group="org.apache.camel", module="camel-core", version="2.8.0")
@Grab(group="org.apache.camel", module="camel-jetty", version="2.8.0")
@Grab(group="org.apache.camel", module="camel-cxf", version="2.8.0")
@Grab(group='ch.qos.logback', module='logback-classic', version='0.9.29')
@Grab(group='com.google.code.gson', module='gson', version='1.7.1')
import org.apache.camel.CamelContext
import org.apache.camel.impl.DefaultCamelContext
import org.apache.camel.impl.SimpleRegistry
import org.apache.camel.builder.RouteBuilder

import javax.ws.rs.*

import javax.ws.rs.ext.MessageBodyWriter
import javax.ws.rs.ext.MessageBodyReader
import java.lang.reflect.Type
import java.lang.annotation.Annotation
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.MultivaluedMap
import com.google.gson.Gson


class Person {
  Integer id
  String name

  public String toString(){
      return "$id $name"
  }
}

@Path("/example")
class MyExampleResource{

  @GET
  @Produces("text/plain")
  @Path("hello")
  public String hello(){
    "Hello World!"
  }

  @GET
  @Produces("application/json")
  @Path("person/{id}")
  public Person getPerson(@PathParam("id") Integer id){
    Person p = new Person()
    p.id = id
    p.name = "Bob"
    return p
  }

  @PUT
  @Consumes("application/json")
  @Produces("application/json")
  @Path("person")
  public Person addPerson(Person p){
    println "Received ${p.toString()}"
    p.id = 123
    return p
  }
}

class GsonProvider implements
    MessageBodyWriter<Object>,
    MessageBodyReader<Object>{

    Gson gson = new Gson()

    boolean isWriteable(Class<?> aClass, Type type,
        Annotation[] annotations, MediaType mediaType){
        mediaType.subtype == 'json'
    }

    long getSize(Object t, Class<?> aClass, Type type,
        Annotation[] annotations, MediaType mediaType){
        0
    }

    void writeTo(Object t, Class<?> aClass, Type type,
        Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> stringObjectMultivaluedMap,
        OutputStream outputStream)
        throws java.io.IOException, javax.ws.rs.WebApplicationException{
        outputStream.write(gson.toJson(t).bytes)
    }

    Object readFrom(Class<Object> tClass, Type type,
        Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> stringStringMultivaluedMap,
        InputStream inputStream) {
        gson.fromJson(inputStream.text, tClass)
    }

    boolean isReadable(Class<?> aClass, Type type,
        Annotation[] annotations, MediaType mediaType) {
        mediaType.subtype == 'json'
    }
}


CamelContext cxt = new DefaultCamelContext()
cxt.registry = new SimpleRegistry()
cxt.registry.registry.put("myResources", [new MyExampleResource()])
cxt.registry.registry.put("jsonProvider", new GsonProvider())

cxt.addRoutes(new RouteBuilder(){
  void configure(){
    from("jetty:http://localhost:8080?matchOnUriPrefix=true")
    .to("cxfbean:myResources?providers=#jsonProvider")
  }
})

cxt.start()

Since originally writing this I discovered how to get the JSON parson that comes with CXF to work with Groovy classes. Include the XmlAccessorType annotation telling it to use FIELD.

...
import javax.xml.bind.annotation.XmlRootElement
import javax.xml.bind.annotation.XmlAccessType
import javax.xml.bind.annotation.XmlAccessorType
import org.apache.cxf.jaxrs.provider.JSONProvider
...
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Person {
  Integer id
  String name

  public String toString(){
      return "$id $name"
  }
}
...
cxt.registry.registry.put("jsonProvider", new JSONProvider())
...

Sunday, November 21, 2010

Simple ESB with Camel and Groovy

I'm not sure if writing an ESB service can be considered fun - but when using Groovy and Camel together it comes pretty close. Camel provedes a nice Java based DSL which makes the routing very clean and easy to follow. When you mix in the power of Groovy you get a very elegant solution.

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()

Sunday, January 31, 2010

Simple Groovy POJO Builder

While using Groovy the other day I wanted to use the builder notation on some simple classes I had created.  The Groovy builder classes are very powerful and allow you to create some very nice custom builders - but that was a little more complex than I was wanting.

Given these simple classes:

class Company{
 public def name = ""
 public def deptList = []

 public add(Department d){
  deptList.add(d)
 }
}

class Department{
 public String name = "default"
 public def Employee = []
}

class Employee{
 public String name = "default"
}

I wanted to be able to write something like the following and have the builder dynamically match up all of the methods and properties without me doing anything.

def c = PojoBuilder.build(Company.class){
  name = "Acme"
  Department{
   name = "HR"
   Employee{
    name = "John"
   }
   Employee{
    name = "Jack"
   }
  }
  Department{
   name = "IT"
   Employee{
    name = "Jimmy"
   }
   Employee{
    name = "James"
   }
  }
 }

As it turns out, the code to achieve this is rather short thanks to the powerful features of Groovy. A method similar to the following is a good start for the build method and allows us to call a closure on an instance of our class. From this closure we have direct access to all of the objects properties and methods - so calling name = "Acme" just works.

class PojoBuilder{

 public static Object build(Class cls, Closure c){
  Object o = cls.newInstance()
  c.delegate = o
  c.resolveStrategy = Closure.DELEGATE_FIRST
  c.call()
  return o
 }


An interesting feature of this is that the Department {...} syntax looks like a method call with a closure as a single parameter. If our Company class had a method
Department(Closure c)
that method would get called... but we don't want to have to add methods like that to our simple classes.

Luckily Groovy has a missingMethod functionality on the MetaClass which gets called when any method is missing. We can use that to add in our own method which can find a class matching the name, check for any method called "add" that accepts our found class, and optionally any properties with the same name that are an ArrayList. If found, dynamically add that method to our class and call it.

The complete example can be found here. It also includes a nice feature where you pass in the classes you want to use and the names you want to use in your builder syntax.