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.