Monday, 15 April 2013

REST web-service example using Jersey

REST web-service using jersey

JAX-RS: Java API for RESTful Web Services

It’s a Java programming language API that provides support in creating web services according to the REST architectural pattern.  It (JAX-RS) uses annotations, introduced in J2SDK1. 5 for simplifying the development and deployment of web service clients and endpoints.

Some of the implementations of JAX-RS are follows:

  • Jersey, an open source reference implementation for REST framework provided by Oracle.
  • Restlet, an open source REST frameworks for the Java platform.
  • Apache Wink, an open source framework which supports development as well as consumption of REST web-services. Apache Software Foundation is the provider and the server module of Apache Wink implements JAX-RS.
  • RESTeasy, A portable implementation of JAX-RS and it’s provider is JBoss which is a division of RedHat.
  • Apache CXF, an open source Web service framework. CXF helps us to build and develop services using frontend programming APIs, like JAX-WS and JAX-RS. These services can talk with a variety of protocols such as SOAP, XML/HTTP, HTTP, or CORBA and work over a variety of transports such as HTTP, JMS or JBI(Java Business Integration). CXF name is derived from combining the "Celtix" and "XFire" project names.
Note: -JBI (Java Business Integration) is a specification, developed under JCP (Java Community Process ) for an approach to implement SOA.



Jersey is Oracle's JSR 311: JAX-RS implementation for building RESTful Web services. Jersey implements support for the annotations defined in JSR-311, which is making it easy for developers to build RESTful web services with Java. Jersey also adds additional features not specified by the JSR. 

                                                                                                     Note:- ref - http://en.wikipedia.org

Annotations used in the demo Example is described below:-


@PATH(passed_path) : -  

 This annotation sets the path to application base URL  and includes the value, passed with @PATH annotation specified at the class or method level of a resource. The @Pathannotation’s value is a partial URI path template relative to the base URI of the server on which the resource is deployed, the context root of the application, and the URL pattern to which the JAX-RS runtime responds.

For example:- http://<hostname>:<server_portnumber>/application_name/url _pattern/ passed_path(path value passed with @PATH annotation for method or class). 

@Path("restwebservice") - In this way I used this annotation.

So, here for accessing the RestWebServicePublisher class the URL is like below:

http://localhost:7075/RestWebServiceUsingJersey/welcome/restwebservice

Note:- Application base URL is - http://localhost:7075/RestWebServiceUsingJersey

           URL pattern is - /welcome/

           and passed_path with @PATH annotation is - restwebservice



@GET: - This annotation indicates that the following method will be invoked for a HTTP GET request.
                The other related annotations corresponding to HTTP methods are @POST, @PUT,  
                @DELETE and @HEAD


@Produces: - This annotation is used to specify the MIME media types which a resource can produce
                         and send back to the client.


@Consumes: - This annotation is used to specify the MIME media types which a resource can consume
                          that were sent by the client.
 


 STEPS to create REST web-service sample example Using Jersey

         1) Download Jersey jars from this location :- http://jersey.java.net/nonav/documentation/latest
             /chapter_deps.html, the required library jars which I am using for this project development is as  
            below:-
            
            activation-1.1.jar
            asm-3.1.jar
            jaxb-api-2.1.jar
            jaxb-impl-2.1.10.jar
            jersey-bundle-1.4.jar
            jersey-client-1.1.2-ea.jar
            jersey-core-1.1.2-ea.jar
            jersey-json-1.1.2-ea.jar
            jersey-server-1.1.2-ea.jar
            jersey-test-framework-1.1.2-ea-SNAPSHOT.jar
            jettison-1.1.jar
            jsr311-api-1.1.jar
            stax-api-1.0-2.jar
            xpp3_min-1.1.4c.jar
            xstream-1.3.1.jar

         2) Create a dynamic web-project using Eclipse.
         
         3) Create a package name with com.gaurav.restwebservice.jersey in the src folder.
     
         4) Create a class name with RestWebServicePublisher.java and place the below code in the java file.


RestWebServicePublisher.java

package com.gaurav.restwebservice.jersey;

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

@Path("restwebservice")
public class RestWebServicePublisher {

    // This method is called if requested for TEXT_PLAIN.
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getPlainTextFormat() {
        return "Welcome by RESTWebService Using Jersey";
    }

    // This method is called if requested for XML
    @GET
    @Produces(MediaType.TEXT_XML)
    public String getXMLFormat() {
        return "<?xml version=\"1.0\"?>" + "<welcome> Welcome by RESTWebService Using Jersey" + "</welcome>";
    }

    // This method is called if requested for HTML
    @GET
    @Produces(MediaType.TEXT_HTML)
    public String getHtmlFormat() {
        return "<html> " + "<title>" + "Welcome REST WebService" + "</title>"
                + "<body><h1>" + "Welcome by RESTWebService Using Jersey" + "</body></h1>" + "</html> ";
    }
   
    // This method is called if requested for JSON
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getJSONFormat() {

        String json = "{" + "'name': 'Gaurav'," + "'id' : 1,"
                + "'designation' : 'System Analyst'," + "'groups' : [{"
                + "'name' : 'Kumar'," + "'id' : 2,"
                + "'designation' : 'Senior System Developer',"
                + "'groups' : [{" + "'name' : 'Aryan'," + "'id' : 3,"
                + "'desingation': 'Senior System Analyst'," + "'groups':[]"
                + "}]" + "}]" + "}";

        return json;
    }
}
 

      5) In the WEB-INF folder, in the web.xml file place the below code in order to configure Jersey servlet 
          container and servlet URL pattern. Here also we need to pass package name(where the resource is 
          available) as the initial parameter.

   web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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">
    <display-name>Rest-Web-Service-Using-Jersey</display-name>
    <servlet>
        <servlet-name>Jersey REST Web Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.gaurav.restwebservice.jersey</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Web Service</servlet-name>
        <url-pattern>/welcome/*</url-pattern>
    </servlet-mapping>
</web-app>

     6) Now, create a package name with com.gaurav.restwebservice.jersey.client in the src folder and 
         also create a java file name with RestWebServicePublisherClient(any name we can put here). Place  
         the below code in this java file

RestWebServicePublisherClient.java

package com.gaurav.restwebservice.jersey.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class RestWebServicePublisherClient {

    private static URI getApplicationBaseURI() {
        return UriBuilder.fromUri(
                "http://localhost:7075/RestWebServiceUsingJersey/welcome/")
                .build();
    }

    public static void main(String[] args) {
        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        WebResource service = client.resource(getApplicationBaseURI());

        // To Get the Plain text format
        System.out.println("\n*****This is the Plain Text format*****");
        System.out.println(service.path("restwebservice")
                .accept(MediaType.TEXT_PLAIN).get(String.class));

        // To Get the XML format
        System.out.println("\n*****This is the XML format*****");
        System.out.println(service.path("restwebservice")
                .accept(MediaType.TEXT_XML).get(String.class));

        // To get the HTML format
        System.out.println("\n*****This is the HTML format*****");
        System.out.println(service.path("restwebservice")
                .accept(MediaType.TEXT_HTML).get(String.class));

        // To get the JSON format
        System.out.println("\n*****This is the JSON format*****");
        System.out.println(service.path("restwebservice")
                .accept(MediaType.APPLICATION_JSON_TYPE).get(String.class));

    }

}
   7) Run the application on server, here I am using tomcat7.0 server. For deploying the application on 
       Tomcat7.0 server and start the server take the reference from location(http://javatechtipssharedbygaurav.blogspot.in/2013/04/rest-web-service-with-crud-operations.html) and go through the STEPS No -15
      
   8) After deploying the application and starting the tomcat server, Execute the 
       RestWebServicePublisherClient.java as a java application the result which we will get is available   
       below:-
    
     OUTPUT :-


Here, in the above example I have tested the deployed application using jersey client, but suppose if we want to test this application using soapUI, then we need WADL(Web Application Description Language) file.

After deploying the application in the server:- for getting the WADL file we can hit below URL.
      http://localhost:7075/RestWebServiceUsingJersey/welcome/application.wadl
This URL will provide us WADL file and we can save this in file system and import in soapUI for testing this application. we can get WADL file in this way only in the case if we are using jersey Reference implementation for building RESTful Web services.

Soon in the next web-service post I will describe how can we test this application with the help of soapUI.

No comments:

Post a Comment