Friday, February 28, 2014

RestFul Web Service Tutorial

 

 JAX-RS Web Service Tutorial 

In this tutorial,  will demonstrates how RESTful services are created using JAX-RS, Tomcat will be primary application server. Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.

 

What are RESTful Web Services?
RESTful web services are built to work best on the Web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web. In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.


The following principles encourage RESTful applications to be simple, lightweight, and fast:

  • Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for resource and service discovery. See The @Path Annotation and URI Path Templates for more information.
  • Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE. PUT creates a new resource, which can be then deleted by using DELETE. GET retrieves the current state of a resource in some representation. POST transfers a new state onto a resource. See Responding to HTTP Methods and Requests for more information.
  • Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. Metadata about the resource is available and used, for example, to control caching, detect transmission errors, negotiate the appropriate representation format, and perform authentication or access control. See Responding to HTTP Methods and Requests and Using Entity Providers to Map HTTP Response and Request Entity Bodies for more information.
  • Stateful interactions through hyperlinks: Every interaction with a resource is stateless; that is, request messages are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several techniques exist to exchange state, such as URI rewriting, cookies, and hidden form fields. State can be embedded in response messages to point to valid future states of the interaction. See Using Entity Providers to Map HTTP Response and Request Entity Bodies and “Building URIs” in the JAX-RS Overview document for more information.

 

RESTful web API HTTP methods
Resource GET PUT POST DELETE
Collection URI, such as http://example.com/resources/ List the URIs and perhaps other details of the collection's members. Replace the entire collection with another collection. Create a new entry in the collection. The new entry's URI is assigned automatically and is usually returned by the operation. Delete the entire collection.
Element URI, such as http://example.com/resources/item17 Retrieve a representation of the addressed member of the collection, expressed in an appropriate Internet media type. Replace the addressed member of the collection, or if it doesn't exist, create it. Not generally used. Treat the addressed member as a collection in its own right and create a new entry in it. Delete the addressed member of the collection.

 

Creating a RESTful Root Resource Class
Root resource classes are POJOs that are either annotated with @Path or have at least one method annotated with @Path or a request method designator, such as @GET, @PUT, @POST, or @DELETE. Resource methods are methods of a resource class annotated with a request method designator. This section explains how to use JAX-RS to annotate Java classes to create RESTful web services. 


Developing RESTful Web Services with JAX-RS
JAX-RS is a Java programming language API designed to make it easy to develop applications that use the REST architecture.

The JAX-RS API uses Java programming language annotations to simplify the development of RESTful web services. Developers decorate Java programming language class files with JAX-RS annotations to define resources and the actions that can be performed on those resources. JAX-RS annotations are runtime annotations; therefore, runtime reflection will generate the helper classes and artifacts for the resource. A Java EE application archive containing JAX-RS resource classes will have the resources configured, the helper classes and artifacts generated, and the resource exposed to clients by deploying the archive to a Java EE server.

 
Annotation Description
@Path The @Path annotation’s value is a relative URI
path indicating where the Java class will be hosted: for example, /helloworld.
You can also embed variables in the URIs to make a URI
path template. For example, you could ask for the name of a user
and pass it to the application as a variable in the URI:
/helloworld/{username}.
@GET The @GET annotation is a request method designator and corresponds to the similarly
named HTTP method. The Java method annotated with this request method designator will
process HTTP GET requests. The behavior of a resource is determined by the
HTTP method to which the resource is responding.
@POST The @POST annotation is a
request method designator and corresponds to the similarly named HTTP method. The Java
method annotated with this request method designator will process HTTP POST requests. The
behavior of a resource is determined by the HTTP method to which the
resource is responding.
@PUT The @PUT annotation is a request method designator and corresponds to
the similarly named HTTP method. The Java method annotated with this request method
designator will process HTTP PUT requests. The behavior of a resource is determined
by the HTTP method to which the resource is responding.
@DELETE The @DELETE annotation
is a request method designator and corresponds to the similarly named HTTP method.
The Java method annotated with this request method designator will process HTTP DELETE

requests. The behavior of a resource is determined by the HTTP method to
which the resource is responding.
@HEAD The @HEAD annotation is a request method designator and corresponds
to the similarly named HTTP method. The Java method annotated with this request
method designator will process HTTP HEAD requests. The behavior of a resource is
determined by the HTTP method to which the resource is responding.
@PathParam The @PathParam
annotation is a type of parameter that you can extract for use in
your resource class. URI path parameters are extracted from the request URI, and
the parameter names correspond to the URI path template variable names specified in
the @Path class-level annotation.
@QueryParam The @QueryParam annotation is a type of parameter that you can
extract for use in your resource class. Query parameters are extracted from the
request URI query parameters.
@Consumes The @Consumes annotation is used to specify the MIME media
types of representations a resource can consume that were sent by the client.
@Produces The @Produces annotation is used to specify the MIME media types of representations a
resource can produce and send back to the client: for example, "text/plain".
@Provider The @Provider
annotation is used for anything that is of interest to the JAX-RS runtime,
such as MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is
used to map an HTTP request entity body to method parameters. On the
response side, a return value is mapped to an HTTP response entity body
by using a MessageBodyWriter. If the application needs to supply additional metadata, such
as HTTP headers or a different status code, a method can return a
Response that wraps the entity and that can be built using Response.ResponseBuilder.

 

Wednesday, November 20, 2013



RESTWebservices and GUI Framework PinPoints:


1. Based on my experience with GWT/Vaadin and REST Webservice dont ever treat JAXB Beans as a Model in the UI layer.


2. Create a separate model objects in the UI Layer and have 'Has-A' relationship with the JAXB Model.

3. Having separate model objects in UI Layer separates the logic from the JAXB Beans and the UML Model generated.

4. If the UML Model generated beans implemented default version of equals()/hashcode() methods this will have impact on the UI layer as well.

5. Maintaining/Versioning of the UML will impact the JAXB beans which will break the UI layer.


Conclusion:

In the UI layer, have a separate model which will allow to have greater flexibility in terms of UI handling with respect to data formats, rendering, etc...

Saturday, November 9, 2013

REST Webservice example





Steps to create REST Webservice with Jersey example:

1. Create Dynamic Web Project in Eclipse


2. Below is the project structure.






3. Download and copy Jersey [jersey-bundle-1.17.1.jar] and asm [asm-3.3.1.jar] to /RESTfulExample/WebContent/WEB-INF/lib


4. Create a REST Servlet service in the below folder structure.

5. Jersey high-level definition of some of the overview:








Below is the HelloWorldService.java content copy


@Path  ->  Defines the Servlet name through the "Path" annotation
@GET   ->  Defines the HTTP Method
@Path("/{param}") - Defines the Path Param in the URI
@Produces(MediaType.TEXT_PLAIN) - In simple terms output type


package main.java.com.rest;

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


@Path("/hello")
public class HelloWorldService {

    @GET
    @Path("/{param}")
    @Produces(MediaType.TEXT_PLAIN)
    public Response getMsg(@PathParam("param") String msg) {
         String output = "Jersey say : " + msg;
         System.out.println("Welcome to Jersey Apache tomcat---->"+output);
         return Response.status(200).entity(output).build();
     }
   
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Response getMsg() {
         String output = "Jersey say : " + "Hanuman";
         System.out.println("Welcome to Jersey Apache tomcat---->");
         return Response.status(200).entity(output).build();
     }

    @POST
    public void postMsg(@FormParam("name") String name) {
        System.out.println("At post method---> " + name);
    }
   
}


6. Build the project from Eclipse through Project -> Build Project options


7. Right click on Project Name and select "Export".

8. Click on 'Next' button


9. Select 'Web Project' and specify the 'Destination' where the WAR file to be saved.

For simplicity, I have copied to tomcat/webapps location


10. Test the REST webservice through chrome browser - POSTMAN plugin and click on SEND button.

Method: GET 




11. To test the URI through Jersey REST client or programmatically below are steps :

a) Copy the libs to jar files below project structure and add to java build





b) Below is the Java file for testing the URI

package com.rest.junit;
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 JTest {
   
  public static void main(String[] args) {
  
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    // Get plain text
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));
    // Get XML
    System.out.println( service.path("rest").path("hello").path("RamaSita_Hanuman").accept(MediaType.TEXT_PLAIN).get(String.class));

  }

  private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:8080/RESTfulExample").build();
  }

}



12.Select the Java file and click on 'Run As' and select 'Java Application.


Sunday, March 27, 2011

Creational Patterns:

Creational Patterns are the design patterns which are used for constructing the objects. Below are the different types of Creational Patterns:

1. Singleton Pattern.
2. Prototype Pattern.
3. Builder Pattern.
4. Factory Pattern.
5. Factory Method Pattern
6. Abstract Factory Pattern.
7. ObjectPool Pattern.

Singleton Pattern:

The name of the pattern represents the instance of the class should be one only instance and it should be instantiable. For example, in a system there should be only one Calendar instance. Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves. Below are few points to be considered.
- Should have private constructor.
- Should be self instantiable.
- Should be one instance.
- Should have a utility method which returns the same instance of the Singleton object.

It involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance at the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.


eg:
class Calendar {

private Calendar calendar;

private Calendar() {

}

public Calendar getInstance() {
if(calendar ==null) {
calendar = new Calendar();
}

return calendar;
}
...........
}

Typically whenever we access Calendar, we will get the same object.

Difference between FactoryMethod/Builder Patterns:
The Factory Method is also a Creational Pattern, but is classified as a Class Creational pattern, where the Builder Pattern is an Object Creational pattern. The difference in classification is that "Class" Creational patterns deal with the relationships between the parent class and subclasses.Inheritance plays a big role in these patterns. Object Creational patterns deal with the relationship between objects and is usually created during runtime.

The Builder pattern is the creation of objects step by step. The Factory Method pattern defines an interface and let the subclasses decide which object to instantiate.

Friday, March 25, 2011

Design Patters for OOPs

Why we need perfect design?

Designing OOPs software is hard and designing resuable software is even harder. We need to figure out realtime objects factor them into the classes at right granularity, define classes, interface and inheritance relationships among these objects. Our design should be specific to the be problem we are trying to solve but also general enough to solve the future problems because of the future changing requirements. Irrespective of programming language every OOP programmer require the design skills.

Software Design Principles:
Software design principles represents a set of guidelines that helps us to avoid having a bad design. Below are the software design principles:

Open Closed Principle:

Software entities like classes, interfaces are open for extension but should be closed for modification. Meaning if any existing classes/interfaces can be extend/inherited for modifications by overriding (Polymorphically). But the existing classes/interfaces should be closed for modificaiton. eg: Any frameworks released in major/minor versions eg: Spring/Struts/Hibernate etc..

Dependency Injection/Inversion Principle:
Consider class/modules depends on some other module, it initializes and holds a direct reference to it. This will make the 2 modules tight coupled. Typically in software engineering pratices "Lossely coupled, tightly cohesion" between the Objects. In order to decouple them the first module will get the reference from a property/XML file, basically the same was called IOC in Spring which is core package of Spring framework and an external module controlling the dependencies will inject the reference to the second one.

Interface Segregation Principle:
Interface should define the methods which are required specific to that module. Eg: Vehicle is a interface :

interface Vehicle {
Model getModel();
SpeakerSystem getSpeakerSystem();
Engine getEngine();

}

class Bicycle implements Vehicle {

// Bicycle might have Model , Engine but not SpeakerSystem.
public Model getModel(){
.....
return model;
}
public SpeakerSystem getSpeakerSystem() {
return null;
//Here speaker system is null which means speaker system not applicable
}
public Engine getEngine() {
//Most of the advanced Models of Bicycle have some kind of engine/motors.
return engine;
}

}

Interfaces containing methods that are not specific to it are called polluted or fat interfaces. Such interfaces definition should be avoided.


Click here to know the list of the Category Patterns.