Skip to main content

RESTful service with JAX-RS is so easy, a caveman could do it

A recent project requires me to build a RESTful service that supports supports stream input, output and JAXB binding. After a quick research, I was amazed when I found how easy it is to build RESTful service using JAX-WS(JSR-311) and Apache CXF. Cut the chase, let the code talk.
import javax.xml.ws.rs.*;
@Path( "/hello" )
public interface Greeter {
 @GET
 @Path( "/{user}")
 @Produces( "text/plain" )
 public String sayHelloTo( @PathParam( "user" )String userName );
}
It seems the annotations in the interface above provides everything client needs to know, and that's exactly right. Following CXF class returns an implementation of Greeter that knows to send HTTP request to http://helloworld.com/hello/jiaqi and return the HTML response as a String. There's zero coding work involved to create fully functional client.
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
...
Greeter greeter = JAXRSClientFactory.create( "http://helloworld.com",
       Greeter.class );
String result = greeter.sayHelloTo( "jiaqi" );
The server side code is even more amazing. Once interface is implemented, CXF provides library that seamlessly integrates arbitrary implementation with Servlet using Springframework. All you need to do is:

  • Making sure cxf-rt-frontend-jaxrs jar file and dependencies are in classpath. Which is simple in Maven:

...
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>2.2.4</version>
<scope>runtime</scope>
</dependency>
...

  • CXF servlet and spring context listener is in web.xml
...
<listener>
 <listener-class>
   org.springframework.web.context.ContextLoaderListener
 </listener-class>
</listener>
<servlet>
 <servlet-name>game</servlet-name>
 <servlet-class>
   org.apache.cxf.transport.servlet.CXFServlet
 </servlet-class>
</servlet>
...
  • And tell Servlet to call my implementation in spring configuration
<beans xmlns:jaxrs="http://cxf.apache.org/jaxrs" ... >
...
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxrs:server id="restfulService" address="/">
 <jaxrs:serviceBeans>
   <ref bean="greeter" />
 </jaxrs:serviceBeans>
</jaxrs:server>
<bean name="greeter"
   class="sample.GreeterImpl" ... >
... 
CXF project has a document with super detailed examples, which talked about more flexible use cases such as arbitrary MIME type, HTTP headers, cookies and stream based API. RESTful Java with JAX-RS is a book that worth reading for JAX-RS loving people. Anyway, now it's time for me to rewrite all my services.

A caveman could do it

Comments

Popular posts from this blog

Publish Maven site with Amazon S3 and CloudFront

Amazon S3 now supports static website hosting . As a 10 years Maven user, I wonder how easy it is to deploy Maven generated site to Amazon S3 and let the rock-solid storage provider to host my project websites. There are several existing s3 wagon providers , which all seem to have the same problem, not supporting directory copy. This is understandable since before S3 new website hosting feature, I guess people mostly expect to deploy artifacts rather than website to S3. So my first task is to write an AWS S3 wagon that supports directory copy. With AWS Java SDK , task becomes as simple as one single class . I made my S3 wagon available in Maven central repository at org.cyclopsgroup:awss3-maven-wagon:0.1 . The source code is hosted in github:jiaqi/cym2/awss3 . The next thing is to create an S3 bucket in console . To avoid trouble, bucket name is set to the future website domain name according to this discussion . Website feature needs to be explicitly enabled. I also created an...

4-states state machine for CSV parsing

Parsing CSV file is easy, it's nothing but splitting string with comma delimiter, which can be easily done in Java... The first thing came to my mind when I'm about to parse CSV file in Java is just like that. Now, reality is that following examples are all possible valid lines in a CSV file 1,Bender 2,"Bender" 3,"Bender, Bending" 4,"Ben""d""er" 5, Ben"der 6, Ben""der Line 7 might be arguable but anyway, two basic rules are If there's comma in field, use double quot to wrap field, otherwise double quot wrapper isn't required. Inside double quot, double quot is used to escape double quot. Suddenly the problem is complicated to something more than string splitting, however it can be simplified into a finite state machine with 4 states. States: 1. Ready for new field (initial state) 2. Field without double quot 3. Field with double quot 4. Escaping or end of double quot Transitions *Direction*|*Condition*|*Ac...

1300ms to 160ms, tune Spring/Hibernate on slow MySQL

I write this article to remember the different behaviour various JDBC connection pool displays when they work with slow JDBC connection(to MySQL database, in this case). It starts with a typical Java application on Spring, Hibernate, Jetty, ApacheCXF and MySQL like following code. Version 1: without correct pooling //... service code @Transactional(isolation=Isolation.READ_COMMITTED) public void foo() { //... do something with database } //... connection pool configuration ... class = "com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource"; url = "jdbc:mysql://mysql.far-far-away.com/mysystem"; user = ... //... transaction management configuration in spring ... <tx:annotation-driven transaction-manager="transactionManager" order="100" /> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="mySessionFact...