Saturday, March 9, 2013

Quick headless JAX-RS servers with CXF


If one needs to vend out JSON data in a JAX-RS compatible way with minimal setup fuss, CXF + Spring provides good out-of-the-box solution for you.
The steps would be:
  1. Write your service class (interface and impl preferably)
  2. Annotate your service impl methods with
    1. @Path annotation indicating the URI on which it will serve the resource
    2. @Get/@Post indicating the HTTP method which it serves
    3. @Produces("application/json") indicating that the output format is JSON
  3. Define a jaxrs:server directive in your spring context file indicating the address and resource path on which the service is hosted
  4. Add maven dependencies of javax.ws.rs-api (for annotations), cxf-rt-core (for stubbing RS communication over a http conduit) and cxf-rt-transports-http-jetty (for embedded jetty)
and voila you are done.
Concretely:
public interface SpecialService {
    String getSomeText();
}
public class SpecialServiceImpl implements SpecialService {

    @GET
    @Produces("application/json")
    @Path("/someText/")
    @Override
    public String getSomeText() {
        return "kilo";
    }
}
    <bean id="specialService" class="com.kilo.SpecialServiceImpl"/>

    <bean id="inetAddress" class="java.net.InetAddress" factory-method="getLocalHost" />

    <jaxrs:server id="specialServiceRS"
        address="http://#{inetAddress.hostName}:${com.kilo.restful.port}/specialServiceRS">
        <jaxrs:serviceBeans>
            <ref bean="specialService" />
        </jaxrs:serviceBeans>
    </jaxrs:server>
And now hit http://yourhostname:yourportnum/specialServiceRS/someText to get the response as "kilo". If you examine the request via some developer tools, you will see that the content type is application/json.
CXF JAX-RS uses an embedded jetty as the http container, so we don't really need a tomcat for setting this up. This might bring up the question of Tomcat vs Jetty overall and here are my thoughts:
Tomcat
  • Lightweight
  • Servlet 3 style async threading in the works
  • Known beast in terms of configuration
Jetty
  • Even more lightweight
  • Implements servlet 3 style async thread allocation (like node) and hence more responsive and efficient
  • Easy to have an embedded server with cxf (embeddability is synonymous with jetty)
  • Ability to have multiple simple java processes that act as headless servers quickly
Overall, I believe we should give Jetty a chance and see how it performs. If it ever lets us down, it is easy to take the process and house it in a Tomcat container.

We will try to cover some more involved use cases of passing in inputs via JAX-RS, dealing with complex objects, CORS and GZIP in subsequent posts (the samples already have them explained).

References:

No comments:

Post a Comment