JAX-RS with GSON and Jersy



Following from the excellent tutorial from Vogella (http://www.vogella.com/articles/REST/article.html ), extending with some extra details.
 Using GSON in this as my  class had  a custom class wrapped in Java collection, GSON makes it very easy to marshall JSON, same also with JAXB using Jersy; But with GSON unmarshalling to Java is also pretty easy.  Also multiple parmeter support is shown
So let us start with the interface first. Kindly read Roy Thomas Fielding's 2000 Dissertation, where he described his architecture style for the web This is a must read for , especially 'architects'. Enough Talk, Let us show some code Yes read about JAX-RS annotations, otherwise it is a simple Java Class (packaged as a servlet - WAR, see Vogellas article first. Okay here goes the interface (in rest everything is HTTP,GET,SET, POST etc

package com.test.prog;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.google.gson.Gson;

@Path("/somerest")
public class RESTfulService
{
       //-- Using GSON way
 @GET 
 @Path("/get_some_list/{startId}/{count}")
 public String getSomelist( @PathParam("startId")  int startId, @PathParam("count") int count) {

  System.out.println("In getSomelistGenerate startId= "+startId+" count= "+count);
                DataList datalist= new DataList ();
  List mylist = new ArrayList();
  for (int i = startId; i < startId+count; i++) {
   // Parameter Constructor okay if using GSON, not okay for JAXB   //Data temp = new Data(i+1,"A long Text");
   DataList temp = new DataList ();
          temp.setId(i+1);
   temp.setText("A long Text");
   
   mylist.add(temp);

  }
  datalist.setList(mylist);
         return new Gson().toJson(datalist);

 }


        //-- Using JAXB way
 @GET 
 @Path("/get_some_list_jaxb/{startId}/{count}")
 public DataList getSomelist( @PathParam("startId")  int startId, @PathParam("count") int count) {

  System.out.println("In getSomelistGenerate startId= "+startId+" count= "+count);
                DataList datalist= new DataList ();
  List mylist = new ArrayList();
  for (int i = startId; i < startId+count; i++) {
   // Parameter Constructor okay if using GSON, not okay for JAXB   //Data temp = new Data(i+1,"A long Text");
   DataList temp = new DataList ();
          temp.setId(i+1);
   temp.setText("A long Text");
   
   mylist.add(temp);

  }
  datalist.setList(mylist);
         return datalist;

 }

Here goes the approximate Structure for Data and DataList class. Note the JAXB annotation is not needed if you are using Just GSON

package com.test.prog;

@XmlRootElement
public class DataList {
 protected List datalist;
       //--- Write getter and setter for this

@XmlRootElement
public class Data {
        private int id;
        private String text;
  
       //--- Write getter and setter for this
       // Data(int id, String text) No if you are using JAXB ctors with partmeters won't work, it expects 
      /Java Bean type class

-->Now create a WAR file and put this in Tomcat or some other Servlet container. Let us see how a client for this can be written using GSON

import java.io.ByteArrayInputStream;
import java.net.URI;
import java.util.Iterator;
import java.util.List;
//Below only needed if you are using JAB to unmarhsall
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.google.gson.Gson;

import com.sun.jersey.api.client.*;

//To test the GSON getting and demarshalling 
 public static void main(String[] args) throws JAXBException{

  ClientConfig config = new DefaultClientConfig();
  Client client = Client.create(config);
  WebResource service = client.resource(getBaseURI());

String datalist= service.path("rest").path("somerest/get_some_list/2432/77").
     accept(MediaType.APPLICATION_JSON).get(String.class);
   DataList mydatalist= new Gson().fromJson(datalist, DataList.class);
// To test JAX demarshalling ? - Not succeeded from the String, and weary to try :)


//TODO JAXB Part not working proerly
  datalist= service.path("rest").path("somerest/get_some_list_jaxb/4234/42").
    accept(MediaType.APPLICATION_JSON).get(String.class);
  JAXBContext jaxbContext = JAXBContext.newInstance(DataList.class);
   
  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  ByteArrayInputStream input = new ByteArrayInputStream (alarmlist.getBytes()); 
   mydatalist=  (AlarmDataList) jaxbUnmarshaller.unmarshal(input);

//Getting the URI, JAX-RS -JESRY automagically does create the URL up to your package, --Check the Web.xml configuration setting too
private static URI getBaseURI() {
  return UriBuilder.fromUri("http://localhost:8080/com.test.prog").build();
 
 }



Comments

Popular posts from this blog

Long running Java process resource consumption monitoring , leak detection and GC tuning

Best practises - Selenium WebDriver/ Java

Java Script Development Guidlines