Thursday, June 21, 2018

Upgrade: Jersey 1.x to 2.x


In order to be on the latest stable versions of the middleware technology stack, I upgraded by webapplication from Jersey1.x to Jersey2.x. Here are the details of the migration that might be helpful for those who are facing any issues while performing Jersey upgrade.

Name Old New
Java Java 8 Java 8
Spring 4.2.1 4.2.1
Hibernate 5.3.1 5.3.1
mysql-jdbc-connector 5.1.6 5.1.6
Jersey 1.8 2.27
JSON-B Provider Genson 1.4 Jackson 2.27
Jersey-Spring Jersey-spring 1.8 Jersey-spring4  2.27
Tomcat7.x.x8.0.23

As part of upgrade, it is not sufficient to update maven dependencies from Jersey 1.8 to 2.27 but also modifying web.xml configuration too to complete the task.

Dependency Entries: Following table lists the old and updated entries to be part of pom.xml file of the project


Update to the web.xml: Because of huge code refactoring from Jersey 1 to Jersey 2, the  core class itself it being changed and more. Following is the git sample showing the config changes in web.xml



Note: Dont get mislead by name of the core Jersey2 servelt which is ending with Container. It shoud be treated as a regular dispatcher-servlet and not to be confused with other containers such as SpringIOC or Tomcat 

Friday, June 15, 2018

Timezone best practice

In any webapplication, the timestamps and zones play an important role. Any discrepancies to fetch and save time details normally occur in terms of zones result in deep confusion to the user. This requires us to strategise the way we handle this sort of information. 

It is a good practice to maintain the single timezone at application level to avoid any such issues.

How to configure Uniform Timezone:
There are 3 stages Timezone information might change - Middleware, Frontend and Database. As long as it is controlled at middleware layer, the frontend is free to convert and render the data according to user's locale. Since the database server has its own timezone configuration, we have to force it to ignore those details and save what the middleware sends.

Config at middleware: 
1. Since any java based application or web servers work as per JVM's timezone. Pass timezone information as the jvm arguments.
2. If using Hibernate 5.3 or higher with Spring, following parameter need to be updated in spring-bean configuration file
UTC
3. Forcing database to ignore its own configuration:
Eg: MySQL: Put the following parameters in the connection string

Friday, June 8, 2018

Java Reflections in Spring & J2EE

Java Reflection: This API one of the critical APIs of Java SDK helps in manipulating various components of Class entity at run time.
To explain in detail, everyone knows one way to create an object of a class as shown in below code sample:

**********START*******
public class Sample{
void show(){
System.out.println("Reflections demo...");
}
}

public class SampleDemo{

public static void main(String[] args){
Sample s = new Sample();
s.show();
}
}
************END*******

The above code will be compiled by JVM and get executed at run time.

But there is another way to do the same by using Java Reflection Package. The package offers various constructs - Modifier, Method, Class and Constructor etc - to manipulate classes and execute tasks such as - Creating objects and calling methods on the classes with/without params.

Reflections are used in developing SDKs, IDEs and Frameworks(Spring, Hibernate etc). Here is a sample reflection-example of how a custom annotation works in Java.
----------------------
Spring MVC or J2EE inner workings:
In early days of J2EE web application development, there is a lot of boilerplate-code and object-creations apart from business logic do exist had to be written by developer. Though the boilerplate code and object-creation are necessary but it is inefficient to write in all applications everytime since it eats up developer's time of coding business-logic.

What if there is some intelligent code that handles the above tasks automatically so that developers just write the business?

Consider the following piece of code with the highlighted boilerplate/object-creation code.
************START*********
public class MainServlet{
/*This can be a Dispatcher servlet*/

public init(){

}

public processGET(){

   if(URL.getPath == "/sample"){
     Controller controller = new Controller(); ---->OBJECT CREATION
     controller.sendResponse();
}

}

public processPOST(){
        if(URL.getPath == "/sample"){
      Controller controller = new Controller(); ---->OBJECT CREATION
      controller.sendResponse();
                }

    public destroy(){}
}

public class Controller{
    private Service serviceObj;

    Controller(Service service){
    this.serviceObj = service       ---->OBJECT CREATION
    }

    /*Business logic*/
    public String sendResponse(){

    return seviceObj.getResponse();

    }
}

public class Service{
private DataDAO dataObj;

Service(DataDAO data){
this.dataObj = data;      ---->OBJECT CREATION
}

public String getResponse(){
dataObj.fetchRespFromDB();
}
}


 public class DataDAO{
  SessionFactory sf;

  DataDAO(){
  this.sf = new SessionFactory();  ---->OBJECT CREATION
  }

  /*******CRUD operations**************/

  public create(){

  try{
   
   conn.setAutoCommit(false);      ---->BOILER PLATE
   Statement stmt = conn.createStatement();    ---->OBJECT CREATION
   String SQL = "INSERT INTO Employees  " +
                "VALUES (106, 20, 'Rita', 'Tez')";
   stmt.executeUpdate(SQL);        ---->BOILER PLATE
   String SQL = "INSERTED IN Employees  " +
                "VALUES (107, 22, 'Sita', 'Singh')";
   ResultSet rs = stmt.executeUpdate(SQL);  ---->BOILER PLATE
   
   conn.commit();        ---->BOILER PLATE
   rs.close(); ---->BOILER PLATE
   stmt.close(); ---->BOILER PLATE
   conn.close(); ---->BOILER PLATE
}

catch(SQLException se){   
   conn.rollback(); ---->BOILER PLATE
}

  }

public read(){
  //Database logic
  }

  public update(){
  //Database logic
  }

  public delete(){
  //Database logic
  }


 }
 ************END***********

The combined Boilerplate and Object-Creation code is called Gluing Logic. Gluing is called so because it looks like a thread that knits all the coupled business components together and acts as request-workflow.

 Request-workflow:
 -> Http request received at webserver
 -> Request is handed over to Servlet
 -> Servlet invokes the corrsponding controller based on the URL path
 -> Controller process the request using appropriate method and various business components - Service layer, DAO layter classes.
 -> Finally the respone is built and sent back to client by servlet/webserver.

From the above sample and following description, we can say that the developer's task of coding the gluing-logic need to be handled by, as mentioned before, some intelligent entity.

Intelligent Entity:
Lets strip all the gluing code from the above sample and replace with a human readable text.


************START*********
public class MainServlet{
/*This can be a Dispatcher servlet*/

public init(){

}

public processGET(){

//Create Controller object
//Call appropriate method on controller to handle the request based on url path
}


}

public processPOST(){

//Create Controller object
//Call appropriate method on controller to handle the request based on url path

}

public destroy(){

}
}

public class Controller{

    private Service serviceObj;    //Create Service object and inject here

    /*Business logic*/
    public String sendResponse(){

    return seviceObj.getResponse();

    }
}

public class Service{
     private DataDAO dataObj;    //Create DAO object and inject here

     public String getResponse(){
     dataObj.fetchRespFromDB();
}
}


public class DataDAO{

   SessionFactory sf; //Create SessionFactory object and inject here. 

   /*******CRUD operations**************/

public create(){
 try{

   //Create Connection object, Set autoCommit false, Begin             Transaction   
   
   String SQL = "INSERT INTO Employees  " +
                "VALUES (106, 20, 'Rita', 'Tez')";
   stmt.executeUpdate(SQL);        ---->BOILER PLATE
   String SQL = "INSERTED IN Employees  " +
                "VALUES (107, 22, 'Sita', 'Singh')";

   //Close and destroy Connections or return it back to pool. Commit Transaction
}
catch(SQLException se){   
   //Close and destroy Connections or return it back to pool. Rollback Transaction
}

  }

public read(){
  //Database logic
}

public update(){
  //Database logic
}

public delete(){
  //Database logic
}


 }
 ************END***********

From the above modified code-sample, it will be way efficient if all the human readable text(BoilerPlate/ObjectCreation/injection or Gluing logic) is taken care by the so called Intelligent code.

How to achieve the Intelligence:
Supply the Object-Creation/Injection of various business components(Controllers/ Service layter /DAO Layer objects) part of glueing in a configuration file such as XML or via Annotations.

Let a Java-Reflection read the above information and run the whole request-workflow. 
Note: Reflections are chosen to handle these kind of intelligence dynamically at runtime because they are meant for this.

Who provides this Gluing/Intelligence:
Eg 1: Spring Framework in case SpringMVC based webapps: All the information supplied via spring-beans.xml or @Service, @Repository, @Controller or @Path is processed by a Reflection. Spring heavily uses reflections to (life-cycle)manage its beans and aop proxies.

 Eg 2: J2EE Application-Server in case of standard J2EE applications: Information supplied in web.xml or @Transaction, @EJB, @Stateless, @Bean is processed by a Reflection.
 TomCat or any servlet-cotainer reads web.xml to find the information about defined servlet and cretes a servlet instace then eventually invokes various methods with the help of reflections.

In fact, all component-containers are built using reflection - Servlet container, EJB container, Spring IoC container and Struts. Basically, whenever we encounter a Java object configured in XML (or any external mechanism or annotation) and try to set any properties on it from config itself, reflection is acting behind the scene. Though it is hidden, is implemented in the container itself.

To summarize, Developer writes business components and supply the configuration information(annotations or XML file). Spring or J2EE handles the gluing logic with Reflections internally.

Spring in action:
Consider a spring MVC based webapplication running on Apache Tomcat.

1. Client makes a request to the url
2. request lands up at Apache Http server
3. Apache hands the request to Tomcat
4. Tomcat(a servlet container- contains reflection code) reads web.xml, instantiates servlet and invokes service method on it
5. Servlet's methods invoke Spring IOC container code
6. IOC container(contains reflections) code goes like this:
Note: IOC Container in Spring is an interface - ApplicationContext.java. This is implemented by ClassPathXmlApplicationContext, FileSystemXmlApplicationContext and WebApplicationContext.

  a) scan packages mentioned in spring-dispatcher-beans.xml
  b) find the class annotated with @Controller with matching url pattern
  c) create object of the Controller class with necessary dependencies:- this step creates    not just controller object but also Service and DAO objects
  d) invoke appropriate method on the controller object based on the url pattern
  e) handover response back to dispatcher servlet
7. Dispatcher servlet handsover the reponse back to Tomcat 
8. Tomcat gets the response back to Apache
9. Apache sends response to Client

What processes various annotations in Spring:
All the annotations across Controllers, Service, Repository classes are processed by respective frameworks. Each framework has its own reflection code to process annotations. 

Hibernate: @Entity, @Table, @Id, @Column, @Generated
Spring: @Controller, @Repository, @Service, @Model, @ViewModel, @Autowire, @Qualifier
Jersey: @Path, @GET, @PUT, @POST, @DELETE, @Produces, @Consumes
Spring-Transaction: @Transactional(supports both javax.transaction.transactional and spring's own @Transactional)

Spring does not implement for many of the annotations belonging to various J2EE APIs but only provides integration code to invoke the core classes of respective frameworks and leaves rest of the processing to them to handle.

What about J2EE application servers:
IBM Websphere and Oracle's Weblogic have the fully supported J2EE implementations meaning that the integration logic is inbuilt.

How J2EE components work together in any Container - Spring or Application Server

In a Spring+Jersey+Hibernate RESTful webapplication, we can spot various J2EE components - JTA, JPA, Java Bean Validation, JSON-B API for B...