Showing posts with label Web Services. Show all posts
Showing posts with label Web Services. Show all posts

Friday, November 8, 2013

RESTful Web Services with Java

REST stands for REpresentational State Transfer, was first introduced by Roy Fielding in his thesis "Architectural Styles and the Design of Network-based Software Architectures" in year 2000.

REST is an architectural style. HTTP is a protocol which contains the set of REST architectural constraints.

REST fundamentals
  • Everything in REST is considered as a resource.
  • Every resource is identified by an URI.
  • Uses uniform interfaces. Resources are handled using POST, GET, PUT, DELETE operations which are similar to Create, Read, update and Delete(CRUD) operations.
  • Be stateless. Every request is an independent request. Each request from client to server must contain all the information necessary to understand the request.
  • Communications are done via representations. E.g. XML, JSON

RESTful Web Services

RESTful Web Services have embraced by large service providers across the web as an alternative to SOAP based Web Services due to its simplicity. This post will demonstrate how to create a RESTful Web Service and client using Jersey framework which extends JAX-RS API. Examples are done using Eclipse IDE and Java SE 6.

Creating RESTful Web Service
  • In Eclipse, create a new dynamic web project called "RESTfulWS"
  • Download Jersey zip bundle from here. Jersey version used in these examples is 1.17.1. Once you unzip it you'll have a directory called "jersey-archive-1.17.1". Inside it find the lib directory. Copy following jars from there and paste them inside WEB-INF -> lib folder in your project. Once you've done that, add those jars to your project build path as well.
    1. asm-3.1.jar
    2. jersey-client-1.17.1.jar
    3. jersey-core-1.17.1.jar
    4. jersey-server-1.17.1.jar
    5. jersey-servlet-1.17.1.jar
    6. jsr311-api-1.1.1.jar
  • In your project, inside Java Resources -> src create a new package called "com.eviac.blog.restws". Inside it create a new java class called "UserInfo". Also include the given web.xml file inside WEB-INF folder.
  • UserInfo.java
     
    package com.eviac.blog.restws;
    
    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;
    
    /**
     * 
     * @author pavithra
     * 
     */
    
    // @Path here defines class level path. Identifies the URI path that 
    // a resource class will serve requests for.
    @Path("UserInfoService")
    public class UserInfo {
    
     // @GET here defines, this method will method will process HTTP GET
     // requests.
     @GET
     // @Path here defines method level path. Identifies the URI path that a
     // resource class method will serve requests for.
     @Path("/name/{i}")
     // @Produces here defines the media type(s) that the methods
     // of a resource class can produce.
     @Produces(MediaType.TEXT_XML)
     // @PathParam injects the value of URI parameter that defined in @Path
     // expression, into the method.
     public String userName(@PathParam("i") String i) {
    
      String name = i;
      return "<User>" + "<Name>" + name + "</Name>" + "</User>";
     }
     
     @GET 
     @Path("/age/{j}") 
     @Produces(MediaType.TEXT_XML)
     public String userAge(@PathParam("j") int j) {
    
      int age = j;
      return "<User>" + "<Age>" + age + "</Age>" + "</User>";
     }
    }
    
    web.xml
    <?xml version="1.0" encoding="UTF-8"?>  
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
      <display-name>RESTfulWS</display-name>  
      <servlet>  
        <servlet-name>Jersey REST 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.eviac.blog.restws</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
      </servlet>  
      <servlet-mapping>  
        <servlet-name>Jersey REST Service</servlet-name>  
        <url-pattern>/rest/*</url-pattern>  
      </servlet-mapping>  
    </web-app>
    
  • To run the project, right click on it and click on run as ->run on server.
  • Execute the following URL in your browser and you'll see the output.
    http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra
    
  • output
Creating Client
  • Create a package called "com.eviac.blog.restclient". Inside it create a java class called "UserInfoClient".
  • UserInfoClient.java
    package com.eviac.blog.restclient;
    
    import javax.ws.rs.core.MediaType;
    
    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    import com.sun.jersey.api.client.WebResource;
    import com.sun.jersey.api.client.config.ClientConfig;
    import com.sun.jersey.api.client.config.DefaultClientConfig;
    
    /**
     * 
     * @author pavithra
     * 
     */
    public class UserInfoClient {
    
     public static final String BASE_URI = "http://localhost:8080/RESTfulWS";
     public static final String PATH_NAME = "/UserInfoService/name/";
     public static final String PATH_AGE = "/UserInfoService/age/";
    
     public static void main(String[] args) {
    
      String name = "Pavithra";
      int age = 25;
    
      ClientConfig config = new DefaultClientConfig();
      Client client = Client.create(config);
      WebResource resource = client.resource(BASE_URI);
    
      WebResource nameResource = resource.path("rest").path(PATH_NAME + name);
      System.out.println("Client Response \n"
        + getClientResponse(nameResource));
      System.out.println("Response \n" + getResponse(nameResource) + "\n\n");
    
      WebResource ageResource = resource.path("rest").path(PATH_AGE + age);
      System.out.println("Client Response \n"
        + getClientResponse(ageResource));
      System.out.println("Response \n" + getResponse(ageResource));
     }
    
     /**
      * Returns client response.
      * e.g : 
      * GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra 
      * returned a response status of 200 OK
      *
      * @param service
      * @return
      */
     private static String getClientResponse(WebResource resource) {
      return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class)
        .toString();
     }
    
     /**
      * Returns the response as XML
      * e.g : <User><Name>Pavithra</Name></User> 
      * 
      * @param service
      * @return
      */
     private static String getResponse(WebResource resource) {
      return resource.accept(MediaType.TEXT_XML).get(String.class);
     }
    }
    
  • Once you run the client program, you'll get following output.
  • Client Response 
    GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra returned a response status of 200 OK
    Response 
    <User><Name>Pavithra</Name></User>
    
    
    Client Response 
    GET http://localhost:8080/RESTfulWS/rest/UserInfoService/age/25 returned a response status of 200 OK
    Response 
    <User><Age>25</Age></User>
    
Enjoy!

Monday, August 20, 2012

Getting started with JAX-WS

JAX-WS stands for Java API for XML Web Services. It is a Java programming language API for creating web services and clients that communicate using XML. This post is a quick start for JAX-WS.

Prerequisites
GlassFish integrated with Eclipse.

Creating the JAX-WS Web Service
  1. In Eclipse create a Dynamic Web Project called "com.eviac.blog.jaxwsproj". Make GlassFish as the Target Runtime.
  2. Create a new class called "SampleWS" in the created project. This will be the implementation class of the web service.
    SampleWS.java
    package com.eviac.blog.jaxws.service;
    
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    
    @WebService
    public class SampleWS {
    
     @WebMethod
     public int sum(int a, int b) {
      return a + b;
     }
    
     @WebMethod
     public int multiply(int a, int b) {
      return a * b;
     }
    
    }
    
    
  3. Open a terminal and navigate to the root of the project directory. Create a directory called wsdl inside WebContent/WEB-INF/. Use the following command to create web service artifacts. Make sure your JAVA_ HOME is set properly or this command will not work. Also make sure to build the project before running this command or it will complain class not found.
    wsgen -classpath build/classes/ -wsdl -r WebContent/WEB-INF/wsdl -s src -d build/classes/ com.eviac.blog.jaxws.service.SampleWS
    
  4. Refresh the project to discover created artifacts. Open the created WSDL-file inside wsdl folder. Search for REPLACE_WITH_ACTUAL_URL and replace it with the web service URL: http://localhost:8080/com.eviac.blog.jaxwsproj/SampleWSService, and save the file.
  5. Deploy the project in Glassfish by right-clicking the project, click Run As -> Run on Server and select the Glassfish server.
Creating the JAX-WS client
  1. Create a Java project in eclipse called "com.eviac.blog.jaxwsclientproj". Open up a new terminal and go to the project root. Use the following command to generate the classes you need to access the web service. Here you will need to use the URL of the WSDL file.
    wsimport -s src -d bin http://localhost:8080/com.eviac.blog.jaxwsproj/SampleWSService?wsdl
    
  2. Create a new class called "SampleWSClient" in the project.
    SampleWSClient.java
    package com.eviac.blog.jaxws.client;
    
    import javax.xml.ws.WebServiceRef;
    
    import com.eviac.blog.jaxws.service.SampleWS;
    import com.eviac.blog.jaxws.service.SampleWSService;
    
    public class SampleWSClient {
    
     @WebServiceRef(wsdlLocation = "http://localhost:8080/com.eviac.blog.jaxwsproj/SampleWSService?wsdl")
     private static SampleWSService Samplews;
    
     public static void main(String[] args) {
      SampleWSClient wsClient = new SampleWSClient();
      wsClient.run();
     }
    
     public void run() {
      Samplews = new SampleWSService();
      SampleWS port = Samplews.getSampleWSPort();
      System.out.println("multiplication Result= "+ port.multiply(10, 20));
      System.out.println("Addition Result= "+port.sum(10, 20));
     }
    
    }
    
  3. Right click on the project and click on Run As -> Java Application. This will result following.
    multiplication Result= 200
    Addition Result= 30