0

I am trying to produce JSON output using Rest service. I am using Jersey implementation for Rest. Project executing on Tomcat 7.0. I am not using Maven. Below is rest service code

package com.ibm.rest;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

@Path("/customers")
public class CustomerResource {


    private static Map<Integer, Customer> customerDB = 
            new ConcurrentHashMap<Integer, Customer>();

    private AtomicInteger idCounter = new AtomicInteger();


    public CustomerResource() {

    }

    @POST
    @Consumes("application/xml")
    public Response createCustomer(Customer customer)
    {
        customer.setId(idCounter.incrementAndGet());
        customerDB.put(customer.getId(), customer);
        System.out.println("Created Customer" + customer.getId());
        return Response.created(URI.create("/RestProject/rest/customers/"+ customer.getId())).build();

    }

    @GET
    @Path("{id}")
    @Produces("application/xml")
    public Customer getCustomer(@PathParam("id") int id)
    {
        Customer customer = customerDB.get(id);
        if(customer == null)
        {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        return customer;
    }

    //Create Json object
    @GET
    @Path("{id}")
    @Produces("application/json")
    public Customer getCustomerJson(@PathParam("id") int id)
    {
        Customer customer = customerDB.get(id);
        if(customer == null)
        {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        return customer;
    }

    @PUT
    @Path("{id}")
    @Consumes("application/xml")
    public void updateCustomer(@PathParam("id") int id,Customer update){
        Customer customer = customerDB.get(id);
        if(customer == null)
        {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        customer.setFirstName(update.getFirstName());
        customer.setLastNAme(update.getLastNAme());
        customer.setStreet(update.getStreet());
        customer.setCity(update.getCity());
        customer.setZip(update.getZip());
        customer.setState(update.getState());
        customer.setCountry(update.getCountry());
    }

}

Customer domain object used in project

    package com.ibm.rest;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="customer")
public class Customer {
    private int id;
    private String firstName,lastNAme,street,city,state,zip,country;

    @XmlAttribute
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @XmlElement(name="first-name")
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @XmlElement(name="last-name")
    public String getLastNAme() {
        return lastNAme;
    }
    public void setLastNAme(String lastNAme) {
        this.lastNAme = lastNAme;
    }

    @XmlElement
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }

    @XmlElement
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }

    @XmlElement
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }

    @XmlElement
    public String getZip() {
        return zip;
    }
    public void setZip(String zip) {
        this.zip = zip;
    }

    @XmlElement
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }


}

Web.xml used in project

    <web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <servlet>
        <servlet-name>jersey-servlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.ibm.rest;org.codehaus.jackson.jaxrs</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

Finally this is client java program

    package com.ibm.rest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

public class CustomerClientJSONApplication {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println("======Create a new Customer=======");

        String newCustomer = "<customer>"
                + "<first-name>Vishwanath</first-name>"
                + "<last-name>Rao</last-name>"
                + "<street>tc palya</street>"
                + "<city>Bangalore</city>"
                + "<state>Karnataka</state>"
                + "<zip>560036</zip>"
                + "<country>India</country>"
                +"</customer>";
        try
        {

                URL postUrl = 
                new URL("http://localhost:8080/RestProject/rest/customers");

                HttpURLConnection connection =(HttpURLConnection)postUrl.openConnection();
                connection.setDoOutput(true);
                connection.setInstanceFollowRedirects(false);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-type", "application/xml");
                OutputStream os =   connection.getOutputStream();
                os.write(newCustomer.getBytes());
                os.flush();

                System.out.println(connection.getResponseCode());
                System.out.println(" Location--->" + connection.getHeaderField("Location"));
                connection.disconnect();



                System.out.println("======Get Created Customer=======");

                URL getUrl = 
                        new URL("http://localhost:8080/RestProject/rest/customers/1");
                HttpURLConnection connection1 =(HttpURLConnection)getUrl.openConnection();

                connection1 =(HttpURLConnection)getUrl.openConnection();
                connection1.setRequestMethod("GET");
                connection1.setRequestProperty("Accept", "application/json");
                System.out.println("Content-Type" + connection1.getContentType());


                BufferedReader reader = new BufferedReader( 
                        new InputStreamReader(connection1.getInputStream()));

                String line= reader.readLine();
                while(line!=null)
                {
                    System.out.println(line);
                    line = reader.readLine();
                }
                connection1.disconnect();   

                /*System.out.println("======Update exising Customer=======");

                String updateCustomer = "<customer>"
                        + "<first-name>Prasanna</first-name>"
                        + "<last-name>Hinge</last-name>"
                        + "<street>M G Road</street>"
                        + "<city>Bangalore</city>"
                        + "<state>Karnataka</state>"
                        + "<zip>560036</zip>"
                        + "<country>India</country>"
                        +"</customer>";

                URL updateUrl = 
                        new URL("http://localhost:9080/RestProject/rest/customers/1");

                connection =(HttpURLConnection)updateUrl.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("PUT");
                connection.setRequestProperty("Content-type", "application/xml");
                OutputStream os1 =   connection.getOutputStream();
                os1.write(updateCustomer.getBytes());
                os1.flush();

                System.out.println(connection.getResponseCode());
                //System.out.println(" Location" + connection.getHeaderField("Location"));
                connection.disconnect();

                System.out.println("======Get updated Customer=======");

                URL getUpdateUrl = 
                        new URL("http://localhost:9080/RestProject/rest/customers/1");

                connection =(HttpURLConnection)getUpdateUrl.openConnection();
                connection.setRequestMethod("GET");
                System.out.println("Content-Type" + connection.getContentType());


                BufferedReader reader1 = new BufferedReader( 
                        new InputStreamReader(connection.getInputStream()));

                String line1= reader1.readLine();
                while(line1!=null)
                {
                    System.out.println(line1);
                    line1 = reader1.readLine();
                }
                connection.disconnect();*/  

        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }

}

After deploying Rest service on Tomcat & executing client java program getting below errors on Tomcat Console

Created Customer1 Jul 08, 2015 6:51:29 AM org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo SEVERE: MessageBodyWriter not found for media type=application/json, type=class com.ibm.rest.Customer, genericType=class com.ibm.rest.Customer.

But on Java console getting error as below

**======Create a new Customer=======
201
 Location--->http://localhost:8080/RestProject/rest/customers/1
======Get Created Customer=======
Content-Typetext/html;charset=utf-8
java.io.IOException: Server returned HTTP response code: 500 for URL: http://localhost:8080/RestProject/rest/customers/1**

Tried all possible solutions on web for Jersey -Jackson integration api but not getting out put

please tell me what else is missing.

Below are jars used in project

-aopalliance-repackaged-2.3.0-b10.jar
-asm-debug-all-5.0.2.jar
-hk2-api-2.3.0-b10.jar
-hk2-locator-2.3.0-b10.jar
-hk2-utils-2.3.0-b10.jar
-jackson-all-1.9.0.jar
-javassist-3.18.1-GA.jar
-javax.annotation-api-1.2.jar
-javax.inject-2.3.0-b10.jar
-javax.servlet-api-3.0.1.jar
-javax.ws.rs-api-2.0.1.jar
-jaxb-api-2.2.7.jar
-jersey-client.jar
-jersey-common.jar
-jersey-container-servlet-core.jar
-jersey-container-servlet.jar
-jersey-guava-2.13.jar
-jersey-server.jar
-json-simple.jar
-org.osgi.core-4.2.0.jar
-osgi-resource-locator-1.0.1.jar
-persistence-api-1.0.jar
-validation-api-1.1.0.Final.jar
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
PDH
  • 39
  • 2
  • 9
  • Can you show all you dependencies (or jars). – Paul Samsotha Jul 08 '15 at 06:17
  • Below are the list of jar used in myproject – PDH Jul 09 '15 at 13:49
  • You can edit your question, rather than putting it in comments – Paul Samsotha Jul 09 '15 at 13:50
  • aopalliance-repackaged-2.3.0-b10.jar, asm-debug-all-5.0.2.jar,hk2-api-2.3.0-b10.jar,hk2-locator-2.3.0-b10.jar,hk2-utils-2.3.0-b10.jar,jackson-all-1.9.0.jar,javassist-3.18.1-GA.jar,javax.annotation-api-1.2.jar,javax.inject-2.3.0-b10.jar,javax.servlet-api-3.0.1.jar,javax.ws.rs-api-2.0.1.jar,jaxb-api-2.2.7.jar,jersey-client.jar,jersey-common.jar,jersey-container-servlet-core.jar, jersey-container-servlet.jar,jersey-guava-2.13.jar,jersey-server.jar,json-simple.jar, org.osgi.core-4.2.0.jar,osgi-resource-locator-1.0.1.jar,persistence-api-1.0.jar,validation-api-1.1.0.Final.jar, – PDH Jul 09 '15 at 13:54
  • Please edit your question with this information, so it is more readable. – Paul Samsotha Jul 09 '15 at 13:55
  • See [this post](http://stackoverflow.com/a/30424031/2587435) for all the jars you need. Note that the Jersey jars are all 2.17. You will want to go to the link provided in that post, to grab your 2.13 version. The Jackson versions should be fine – Paul Samsotha Jul 09 '15 at 14:01
  • Do you mean Jersey Jar I used are of version 2.17 & i should use version 2.13 – PDH Jul 09 '15 at 14:34
  • No I mean the jersey jars in the link are 2.17. The linked jars are direct downloads. There's a link further in the post, that links the actual source where you can search for your 2.13 (since that's the Jersey version you are using - you shouldn't mix versions). There's only two Jersey jars that you need. The others are Jackson jars, for which the linked versions are fine – Paul Samsotha Jul 09 '15 at 14:36

0 Answers0