GSON as JAX-RS json provider in CXF

While there are many frameworks for parsing JSON structured data, I was looking for a framework which will provide a generic object. I was expecting a returned object to be more like a property holder (no Hashmaps, please). I came across GSON and found it is the perfect candidate for what I am looking for.
But my problem was not addressed completely, I was looking for embedding GSON inside CXF as JAX-RS provider. The default implementation which comes with CXF, was returning a concrete object which was impossible for me to build and make available to the provider. Hence, I needed a way to configure GSON as JAX-RS provider and capitalize the features which I was more interested in.
This led the way to build my own JAX-RS provider using GSON. Fortunately, it is much easier with CXF to create JAX-RS provider and plug it in the framework.
Step 1
Create a class “GSONJAXRSProvider” and implement

javax.ws.rs.ext.MessageBodyReader
javax.ws.rs.ext.MessageBodyWriter

Step 2
Override the method to parse incoming data.

public Object readFrom(Class object, Type arg1, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream inputStream) throws IOException, WebApplicationException

I have used following code to deserialize data

InputStreamReader streamReader = new InputStreamReader(inputStream);
JsonElement jsonObject = parser.parse(streamReader);
return (Object)jsonObject;

Step 3
Override the method to serialize outgoing data.

public void writeTo(Object object, Class arg1, Type arg2, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream responseStream) throws IOException, WebApplicationException

And here goes code for serializing JSONObject to string.

PrintWriter printWriter = new PrintWriter(responseStream);
JsonObject json = (JsonObject)object;
printWriter.write(json.toString());
printWriter.flush();

Step 4
Configure the newly created class as JAX-RS provider in CXF. Refer following configuration snippet.






That’s all!

CXF on IBM WebSphere 7 – Deployment Pitfalls

Just recently I deployed CXF enabled application on websphere 7 and came across many issues. The issues were not with respect to configuration problems but were mostly related to the classes used internally by CXF (version 2.1, I guess) framework. Surpizingly these issues dont pop-up on JBoss server (Its like saying, hey look my code works on my machine, I dont know what went wrong with yours, it simply doesn’t kick. Heard that a lot in college days 😉
Continue reading