Tuesday 7 May 2013

REST web-service example with parametrized methods using Jersey

Rest web-service having parametrized methods

In the earlier post I explained that how to create REST web-service examples Using Jersey. So for primary setup steps please follow the below given link.

In this post I am going to explain how to deal with  parametrized methods in REST web-service by using Jersey API.

System requirement for the application :-
Jersey Jars.
REST Client.
JDK1.6 and above
Eclipse Helios and above.
Tomcat 7.0 and above.

STEPS :-

To create RestWebServiceWithParametrizedMethods dynamic web project 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:-
             asm-3.1.jar
             jackson-core-asl-1.9.2.jar
             jackson-jaxrs-1.9.2.jar
             jackson-mapper-asl-1.9.2.jar
             jackson-xc-1.9.2.jar
             jersey-client-1.17.jar
             jersey-core-1.17.jar
             jersey-json-1.17.jar
             jersey-server-1.17.jar
             jersey-servlet-1.17.jar
            jettison-1.1.jar
            jsr311-api-1.1.1.jar 
           
         2) Create a dynamic web-project named RestWebServiceWithParametrizedMethods using 
             Eclipse.
         
         3) Create a package name with com.gaurav.jaxrs.services in the src folder.
     
         4) Create a class name with ParametrizedMethodServicesUsingREST.java and place the below code in the java file.


ParametrizedMethodServicesUsingREST.java

package com.gaurav.jaxrs.services;

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

@Path("basic")
public class ParametrizedMethodServicesUsingREST {

    // This method is called if TEXT_PLAIN is request
    @Path("name")
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    public String displayName(String name) {
        return "My Name is " + name;
    }

    public boolean isParsableToInteger(String strValue) {
        try {
            Integer.parseInt(strValue);
            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }
    }

    @Path("countVowels")
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    public String countVowels(String word) {

        int count = 0;
        String result = null;
        for (int i = 0; i < word.length(); i++) {
            if (word.charAt(i) == 'a' || word.charAt(i) == 'A') {
                count++;
            } else if (word.charAt(i) == 'e' || word.charAt(i) == 'E') {
                count++;
            } else if (word.charAt(i) == 'i' || word.charAt(i) == 'I') {
                count++;
            } else if (word.charAt(i) == 'o' || word.charAt(i) == 'O') {
                count++;
            } else if (word.charAt(i) == 'u' || word.charAt(i) == 'U') {
                count++;
            }
        }
        System.out
                .println("Number of vowels in the given string is : " + count);
        result = String.valueOf(count) +" vowels found in the given string "+word ;
        System.out.println(result);
        return result;
    }

    @Path("factorial")
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    public String getFactorial(String inputString) {

        String factorialResult = "Not a Valid Number";

        if (inputString == null || inputString.trim().length() == 0) {
            return "";
        }

        if (isParsableToInteger(inputString)) {

            Long number = Long.parseLong(inputString);

            if (number < 0) {

                return factorialResult = "Number must be positive";
            } else {

                Long factorial = number;

                for (Long i = (number - 1); i > 1; i--) {
                    factorial = factorial * i;
                }
                factorialResult = "Factorial of given number " + number
                        + " is " + String.valueOf(factorial);

            }

        }
        return factorialResult;

    }

}

  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.jaxrs.services</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Web Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>


6) 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://www.javatechtipssharedbygaurav.com/2013/04/rest-web-service-with-crud-operations.html) and go through the STEPS No -15

7)After deploying the application and starting the tomcat server, we can get the WADL file
    For getting the WADL file we can hit below URL.

      http://localhost:7075/RestWebServiceWithParametrizedMethods/rest/application.wadl

     This URL will provide us WADL file and we can test our REST based web-services using RESTClient 
     or SOA Client which is a Add-ons for Mozile Firefox. We can get WADL file in this way only if we
     are using jersey API for building RESTful Web services.

8) Open Mozila Firefox browser, Go to Tools menu, click on Add-ons, Search for REST Client or SOA
    Client and then click on install button to install the selected plugin. After installation restart the browser and
    again go to tools menu and select the installed plugin. I am proceeding with REST Client Add-ons.

After opening the REST Client
  • Select Http method as POST.
  • Pass the corresponding URL for calling a specific method.
  • Pass the required parameter in the Body.
  • Then in the Response body we can check the Result after click on send.
Result:-
  
  For calling the factorial method, the specified URL is like below:-
  http://localhost:7075/RestWebServiceWithParametrizedMethods/rest/basic/factorial



 For calling the countVowels method, the specified URL is like below:-
 http://localhost:7075/RestWebServiceWithParametrizedMethods/rest/basic/countVowels



 For calling the name method, the specified URL is like below:-
 http://localhost:7075/RestWebServiceWithParametrizedMethods/rest/basic/name



Description of the URL : - 

http://localhost:7075/RestWebServiceWithParametrizedMethods/rest/basic/factorial

http://hostname:<portnumber>/nameof the web project/URL pattern/class level path annotation/method level path annotation.   

WADL file contents are as follows:-

<application xmlns="http://wadl.dev.java.net/2009/02">
    <doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 1.17 01/17/2013 03:31 PM" />
    <grammars />
    <resources
        base="http://localhost:7075/RestWebServiceWithParametrizedMethods/rest/">
        <resource path="basic">
            <resource path="factorial">
                <method id="getFactorial" name="POST">
                    <request>
                        <representation mediaType="*/*" />
                    </request>
                    <response>
                        <representation mediaType="text/plain" />
                    </response>
                </method>
            </resource>
            <resource path="countVowels">
                <method id="countVowels" name="POST">
                    <request>
                        <representation mediaType="*/*" />
                    </request>
                    <response>
                        <representation mediaType="text/plain" />
                    </response>
                </method>
            </resource>
            <resource path="name">
                <method id="displayName" name="POST">
                    <request>
                        <representation mediaType="*/*" />
                    </request>
                    <response>
                        <representation mediaType="text/plain" />
                    </response>
                </method>
            </resource>
        </resource>
    </resources>
</application>

No comments:

Post a Comment