Wednesday, July 29, 2015

enum in Java

Enum was introduced in java with jdk5 release. It is one of the most overlooked feautures by java developers. So lets try to understand what is an enum and what are the features and advantage of using enum.Enum in java is a set of named constants. Enum is declared with the keyword enum.

enum Days {
      SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;
}

The above enum is a set of named constants representing the days of  a week. Enums are internally represented as a class. So the above enum will roughly translated to below code:-

Class Days {
      public static final SUNDAY = new Days();
      public static final MONDAY = new Days();
      public static final TUESDAY = new Days();
public static final WEDNESDAY = new Days();
public static final THURSDAY = new Days();
public static final FRIDAY = new Days();
public static final SATURDAY = new Days();

}

So every named constant in an enum is an object of the same enum type and are implicitly public, static and final. Enum in java are more powerful as it can contain variable, methods and consturctors unlike the enum in other programming language. Some of the features of enum are as below:

1.All named constants in an enum are implictly public, static and final are represent an instance of same enum type.

2.enum in java can not extend any other class as every enum in java implicitly extends java.lang.Enum class.

3.enums can not be extended by any other class as enums in java are implicitly final and so can not be extened.

4.enums can implement any number of interfaces.

5.enum constants are final but it can also contain other variables apart from named constants.

6.enums can be used in swithch statement.

7.enum constructors are always private.

8. we cant create instance of enum using new operator.

9. We can declare abstract methods in java enum, then all the enum fields must implement the abstract method

Lets try to demonstrate all this through code example:

Lets declare an enum ThreadStatus:

public enum ThreadStatus {

      START, RUNNING, WAITING, DEAD;
}
Lets also add priority instance variable for the above enum and assign some value for each enum constant.lets also declare a constructor.

public enum ThreadStatus {

      START(1), RUNNING(2), WAITING(3), DEAD(4);
     
      private int priority;
     
      private ThreadStatus(int priority){
            this.priority = priority;
      }
}
Lets also add an abstract method called getDetail(). As the method is abstract all enum constants should implement this abstract method. Also add getters and setters for priority instance variable. The final enum code will look like this:-

public enum ThreadStatus {

      START(1) {
            @Override
            public String getDetail() {
                  return "Starting";
            }
      }, RUNNING(2) {
            @Override
            public String getDetail() {
                  return "Running";
            }
      }, WAITING(3) {
            @Override
            public String getDetail() {
                  return "Waiting";
            }
      }, DEAD(4) {
            @Override
            public String getDetail() {
                  return "Dead";
            }
      };
     
      private int priority;
     
      private ThreadStatus(int priority){
            this.priority = priority;
      }

      public int getPriority() {
            return priority;
      }

      public void setPriority(int priority) {
            this.priority = priority;
      }
     
      public abstract String getDetail();
}

Lets demonstrate the use of enum through example:

public class ThreadStatusEnumDemo {

      /**
       * @param args
       */
      public static void main(String[] args) {
            ThreadStatus[] status = ThreadStatus.values();
           
            for(ThreadStatus s : status){
                  System.out.println("Thread Priority:" +s.getPriority());
                  System.out.println("Thread Details:" +s.getDetail());
            }
            //change the priority of thread statuses
            ThreadStatus.STARTING.setPriority(5);
            ThreadStatus.RUNNING.setPriority(10);
            ThreadStatus.WAITING.setPriority(15);
            ThreadStatus.DEAD.setPriority(20);
           
            System.out.println("***New priority of threads****");
           
            for(ThreadStatus s : status){
                  System.out.println("Thread Priority:" +s.getPriority());
            }
           
            //demonstrate the use of switch
           
            System.out.println("****switch demo*****");
           
            for(ThreadStatus s : status){
                  switch(s){
                  case STARTING:
                        System.out.println("THREAD IS STARTING");
                        break;
                       
                  case RUNNING:
                        System.out.println("THREAD IS RUNNING");
                        break;
                       
                  case WAITING:
                        System.out.println("THREAD IS WAITING");
                        break;
                       
                  case DEAD:
                        System.out.println("THREAD IS DEAD");
                        break;
                         
                        default:
                              System.out.println("invalid thread status");
                       
                  }
            }
           
      }

}

Tuesday, July 28, 2015

GC Algorithms

Java Virtual Machine provides four different algorithms for performing GC

1.Serial Garbage Collector: The serial garbage collector is the simplest of the four. This is the default collector if the application is running on a client-class machine (32-bit JVMs on Windows or singleprocessor machines). The serial collector uses a single thread to process the heap. It will stop all application threads as the heap is processed (for either a minor or full GC). During a full GC, it will fully compact the old generation. The serial collector is enabled by using the -XX:+UseSerialGC flag (though usually it is the default in those cases where it might be used). Note that unlike with most JVM flags,the serial collector is not disabled by changing the plus sign to a minus sign (i.e., by specifying -XX:-UseSerialGC). On systems where the serial collector is the default, it is disabled by specifying a different GC algorithm.

2. The Throughput Collector: This is the default collector for server-class machines (multi-CPU Unix machines, and any 64-bit JVM). The throughput collector uses multiple threads to collect the young generation, which makes minor GCs much faster than when the serial collector is used. The throughput collector can use multiple threads to process the old generation as well. That is the default behavior in JDK 7u4 and later releases, and that behavior can be enabled in earlier JDK 7 JVMs by specifying the - XX:+UseParallelOldGC flag. Because it uses multiple threads, the throughput collector is often called the parallel collector. The throughput collector stops all application threads during both minor and full GCs, and it fully compacts the old generation during a full GC. Since it is the default in most situations where it would be used, it needn’t be explicitly enabled. To enable it where necessary, use the flags -XX:+UseParallelGC -XX:+UseParallelOldGC.

3.The CMS( Concurrent Mark and Sweep ) collector: The CMS collector is designed to eliminate the long pauses associated with the full GC cycles of the throughput and serial collectors. CMS stops all application threads during a minor GC, which it also performs with multiple threads. Notably, though, CMS uses a different algorithm to collect the young generation (-XX:+UseParNewGC) than the throughput collector uses (-XX:+UseParallelGC). Instead of stopping the application threads during a full GC, CMS uses one or more background threads to periodically scan through the old generation and discard unused objects. This makes CMS a low-pause collector: application threads are only paused during minor collections, and for some very short periods of time at certain points as the background threads scan the old generation. The overall amount of time that application threads are stopped is much less than with the throughput collector. The trade-off here comes with increased CPU usage: there must be adequate CPU available for the background GC thread(s) to scan the heap at the same time the application threads are running. In addition, the background threads do not perform any compaction, which means that the heap can become fragmented. If the CMS back‐ground threads don’t get enough CPU to complete their tasks, or if the heap becomes too fragmented to allocate an object, CMS reverts to the behavior of the serial collector: it stops all application threads in order to clean and compact the old generation using a single thread. Then it begins its concurrent, background processing again (until, possibly, the next time the heap becomes too fragmented). CMS is enabled by specifying the flags -XX:+UseConcMarkSweepGC -XX:+UseParNewGC (both of which are false by default).

4. The G1( Garbage First ) collector: The G1 collector is designed to process large heaps (greater than about 4 GB) with minimal pauses. It divides the heap into a number of regions, but it is still a generational collector. Some number of those regions comprise the young generation, and the young generation is still collected by stopping all application threads and moving all objects that are alive into the old generation or the survivor spaces. As in the other algorithms, this occurs using multiple threads. G1 is a concurrent collector: the old generation is processed by background threads that don’t need to stop the application threads to perform most of their work. Because the old generation is divided into regions, G1 can clean up objects from the old generation by copying from one region into another, which means that it (at least partially) compacts the heap during normal processing. Hence, a G1 heap is much less likely to be subject to fragmentation—though that is still possible. Like CMS, the trade-off for avoiding the full GC cycles is CPU time: the multiple background threads must have CPU cycles available at the same time the application threads are running. G1 is enabled by specifying the flag -XX:+UseG1GC (which by default is false).


Wednesday, July 22, 2015

Garbage Collector : An overview from JVM Perspective

Three basic operations performed by garbage collectors are - finding unused objects, making their memory available, and compacting the heap. Different collectors take different approaches to these operations, which is why they yield different performance characteristics.

It is simpler to perform these operations if no application threads are running while the garbage collector is running. Java programs are typically heavily multithreaded, and the garbage collector itself often runs multiple threads. So there are two logical groups of threads: those performing application logic, and those performing GC.

The pauses when all application threads are stopped are called stop-the-world pauses. These pauses generally have the greatest impact on the performance of an application, and minimizing those pauses is the key consideration when tuning GC.

With little bit of difference in their implementation almost all garbage collectors work by splitting the heap into different generations. They are broadly divided into two generations – old and young generation. The young generation is further divided into eden and the survivor spaces. Java garbage collector is designed to take advantage of the fact that most of the objects in the memory have very short life. This is where the generational design comes in. Objects are first created in the young generation which is some subset of the entire heap. When the young generation fills up, the garbage collector will stop the application threads and empty out the young generation by either discarding or moving the objects elsewhere. This operation of cleaning up the young generation is called minor GC.

There are two advantages of this design. First, as the young generation is only a portion of the entire heap, processing it is faster than processing the entire heap. This results in shorter pause of the application thread but the downside is that the application threads will be stopped more frequently. But it is always a big advantage to have shorter pauses even though they will be more frequent. The second advantage is that when the young generation is cleared during the GC all objects in eden are either moved or discarded; all live objects are moved to either one of the survivor spaces or to the old generation. Since all objects are moved, the young generation is automatically compacted when it is collected. All GC algorithms have stop the world pauses during the collection of young generation.

As objects are moved from young generation to old generation eventually it will also fill up and the JVM will need to find the objects that are no longer in use and discard them from the old generation. This is where the GC algorithms have their biggest differences. The simpler algorithms stop all application threads, find the unused objects and free their memory, and then compact the heap. This process is called a full GC, and it generally causes a long pause for the application threads.

It is also possible to find unused objects while application threads are running; CMS and G1 both take that approach. Because the phase where they scan for unused objects can occur without stopping application threads, CMS and G1 are called concurrent collectors. They are also called low-pause (and sometimesincorrectlypauseless) collectors, since they minimize the need to stop all the application threads. Concurrent collectors also take different approaches to compacting the old generation. With CMS or G1 collector, an application will typically experience fewer and much shorter pauses. The trade-off is that the application will use more CPU overall.

Different GCs suit for different application needs. There are trade-offs in every situation. In an application such as a Java EE server measuring the response time of individual requests, consider these points:

 The individual requests will be impacted by pause timesand more importantly by long pause times for full GCs. If minimizing the effect of pauses on response times is the goal, a concurrent collector will be more appropriate. If the average response time is more important than the outliers (i.e., the 90th% response time), the throughput collector will usually yield better results. The benefit of avoiding long pause times with a concurrent collector comes at the expense of extra CPU usage. Similarly, the choice of garbage collector in a batch application is guided by the following trade-off: If enough CPU is available, using the concurrent collector to avoid full GC pauses will allow the job to finish faster. If CPU is limited, then the extra CPU consumption of the concurrent collector will cause the batch job to take more time.

HotSpot JVM - Why its called HotSpot

Sun/Oracle version of JVM is known as HotSpot JVM. Let’s try to understand why it’s named HotSpot  JVM which will also help us to understand what a JIT compiler is and how the execution happens from .java file upto the execution of the code.

When we compile a .java file using the javac compiler the .java file gets converted to .class file which is the Bytecode representation of the .java file. The javac compiler doesn’t directly convert the java code into the machine language instead it converts it to the Bytecode that the JVM understands. Since java Bytecode has no platform dependent code, it is executable on any hardware where the JVM has been installed even with different CPU and OS from which the code was compiled. And this is what gives java platform independence. The .class file is a binary representation of the java code which can not be understood by human and which only the JVM undserstands. This .class file is loaded in the JVM memory via class loader and is executed by the execution engine. As the Bytecode is not the machine level representation of the code,therefore, the execution engine must change the bytecode to the language that can be executed by the machine in the JVM. The bytecode can be changed to the suitable language in one of two ways.

·       Interpreter: Reads, interprets and executes the bytecode instructions one by one. As it interprets and executes instructions one by one, it can quickly interpret one bytecode, but slowly executes the interpreted result. This is the disadvantage of the interpret language. The 'language' called Bytecode basically runs like an interpreter.

·  JIT (Just-In-Time) compiler: The JIT compiler has been introduced to compensate for the disadvantages of the interpreter. The execution engine runs as an interpreter first, and at the appropriate time, the JIT compiler compiles the entire bytecode to change it to native code. After that, the execution engine no longer interprets the method, but directly executes using native code. Execution in native code is much faster than interpreting instructions one by one. The compiled code can be executed quickly since the native code is stored in the cache. 

However, it takes more time for JIT compiler to compile the code than for the interpreter to interpret the code one by one. Therefore, if the code is to be executed just once, it is better to interpret it instead of compiling. Therefore, the JVMs that use the JIT compiler internally check how frequently the method is executed and compile the method only when the frequency is higher than a certain level. So the piece or spot of code that gets executed repeatedly becomes hotter with every execution and once the certain threshold value is reached the JIT compiler compiles that portion or spot of code and keeps it in cache from where it can be directly executed next time the same code is called for execution. If the spot is not the hotspot any more, the Hotspot VM removes the native code from the cache and runs in interpreter mode.  And hence it has been named as HotSpot JVM.

32-Bit vs 64-Bit JVM (Client-Server JVM)

When we download Java we must choose a version. The choice depends upon the platform that we are using. The JVM/Java is available in 32-bit/64-bit versions. However the 32-bit/64-bit JVM is also distinguished as client/server JVM based on the JIT compiler it uses. These names come from the command-line argument used to select the compiler (e.g., either -client or -server). When downloading Java for a given operating system, there are only two options: a 32-bit or a 64-bit binary. A 32-bit binary can be expected to have  two compilers (client and server), while the 64-bit binary will have only a single (server) compiler. (In fact, the 64-bit binary will have two compilers, since the client compiler is needed to support tiered compilation. But a 64-bit JVM cannot be run with only the client compiler.)

A 32-bit client version (-client)
A 32-bit server version (-server)
A 64-bit server version (-d64)

If we have a 32-bit operating system, then we must use a 32-bit version of the JVM. If we have a 64-bit operating system, then we can choose to use either the 32- or 64-bit version of Java. Don't assume that just because we have a 64-bit operating system, we must also use a 64-bit version of Java.

If the size of our heap will be less than about 3 GB, the 32-bit version of Java will be faster and have a smaller footprint. This is because the memory references within the JVM will be only 32 bits, and manipulating those memory references is less expensive than manipulating 64-bit references (even if we have a 64-bit CPU). The 32-bit references also use less memory. JVM can use 32-bit addresses even within the 64-bit JVM. However, even with that optimization, the 64-bit JVM will have a larger footprint because the native code it uses will still have 64-bit addresses.

The downside to the 32-bit JVM is that the total heap size must be less than 4 GB (3 GB on some versions of Windows, and 3.5 GB on some old versions of Linux). That includes the heap, permgen, and the native code and native memory the JVM uses. Programs that make extensive use of long or double variables will be slower on a 32-bit JVM because they cannot use the CPUs 64-bit registers, though that is a very exceptional case.Programs that fit within a 32-bit address space will run anywhere between 5% and 20% faster in a 32-bit JVM than a similarly configured 64-bit JVM. With 64-bit JVM there is no such limit of heap size. We can select as big a hip as we want to. Howerver the downside of 64-bit JVM with larger heap size is the pause it causes during the full garbage collection. The larger the size oh the heap the bigger the pause will be. If the application doesn’t need a heap size bigger than 4GB then its always better to go for 32-bit JVM.

To determine the default compiler for a particular installation of Java, run this command:
% java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

The last line indicates which of the three possible compilers will be used: client (32-bit), server (32-bit), or 64-bit server.


Monday, January 26, 2015

Java/J2EE Blog: Little Bit of REST

Java/J2EE Blog: Little Bit of REST: Before we write our first RESTful web service lets have a brief introduction of web service and how they are different from web applicati...

Little Bit of REST

Before we write our first RESTful web service lets have a brief introduction of web service and how they are different from web application. Both web application and web services are accessed over the web or the internet. So, what is the basic difference. Well a web application is supposed to be consumed by human over the web whereas a web service is supposed to be consumed by another application or software component over the web. So a web service is a piece of code exposed over the web to be consumed by another piece of software code over the web or the internet. This piece of code that is exposed over the web is called service which is consumed by the consumer or the client which again is an another software component.

When a web service client makes a request to a web service endpoint, they are usually messages transmitted from one machine to another. These messages need to be in a format, a language, that both the client and the server can understand. This language, or protocol, is standardized in some web service types. For example, SOAP web services is a type of web services, where the protocol always has to follow the standard called SOAP. All SOAP web services uses this protocol to communicate with clients. It used to stand for Simple Object Access Protocol. But that name is now discontinued and we are stuck with just the acronym. There is a specific format, which is XML, and there are specific rules which detail how that XML should be. The client and the server needs to talk to each other using this SOAP protocol only!


So, what is the protocol used by REST. Well the answer is none. A REST client can send and receive messages in any format like XML,JSON, HTML, Text etc. There are no rules as long as the client and server understand each other. REST or Representational state transfer is actually an architecture style. The term REST was coined by Roy Fielding who is one of the principal authors of HTTP specification. That is the reason the ideas behind REST makes good use of HTTP specification. REST web services exposes data using the HTTP methods like GET(to read the data),POST(to create the data),PUT(to update the data),DELETE(to delete the data) and any restful resource is exposed to the outside world via a URI on the web.


JAX-RS or Java API for Restful Web Services is a new API that aims to make development of RESTful web services in Java simple and intuitive. Ok, so enough of the background about web services. In this blog i will be using Jackson which is the implementation of JAX-RS API to write RESTful web services. I will also use Gson which is a google API to convert JSON to Java objects and vice versa. My sample appolication will use Hibernate as the ORM tool and Spring core just for dependency injection. This sample application will read/write data from the users table and expose methods perfrom CRUD operation on this table.

This is how my folder structure looks like:-




















And below are the JARs that will be required:-




















Inside the model package i have the User class, its a simple pojo with gettters/setters. Below is the code:-

package com.sanjiv.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.hibernate.annotations.FetchProfile;



@Entity
@Table(name="USERS")
//@JsonAutoDetect
//@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Users {
@Id
@Column(name="USER_ID")
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="userid_seq")
@SequenceGenerator(name="userid_seq",sequenceName="userid_sequence",allocationSize=1)

private int userID;

@Column(name="USER_NAME")

private String userName;

@Column(name="EMAIL_ID")
private String emailID;

public Users(){}

public Users(String userName, String emailID, int userID) {

this.userName = userName;
this.userID = userID;
this.emailID = emailID;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public int getUserID() {
return userID;
}

public void setUserID(int userID) {
this.userID = userID;
}

public String getEmailID() {
return emailID;
}

public void setEmailID(String emailID) {
this.emailID = emailID;
}

@Override
public String toString() {
    return new StringBuffer(" User Name : ").append(this.userName)
             .append(" Email Id : ").append(this.emailID)
             .append(" User ID : ")
             .append(this.userID).toString();
   }



}


Inside the dao package i have a UserDaoInterface and UserDao implementation class which is responsible for database related stuff using Hibernate as ORM. Below is the code for interface

package com.sanjiv.dao;

import java.util.List;

import com.sanjiv.model.Users;

public interface UserDaoInterface {

public List<Users> getUsers();
public Users getUserById(int userid);
public void deleteUsers();
public void deleteUserById(int userid);
public void addUser(Users user);

void updateUser(Users user);
}

Implementation class:-

package com.sanjiv.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.sanjiv.model.Users;

public class UserDao implements UserDaoInterface {

SessionFactory sessionFactory;

public UserDao(){

}

public SessionFactory getSessionFactory() {
return sessionFactory;
}

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

public UserDao(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;

}


public List<Users> getUsers() {

Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
List<Users> usersList = session.createQuery("from Users").list();
tx.commit();
return usersList;
}


public Users getUserById(int userid) {
Users user = null;

Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();

user = (Users) session.get(Users.class, userid);

tx.commit();

return user;
}

public void addUser(Users user) {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();

}

@Override
public void deleteUsers() {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("Delete from Users");
int result = query.executeUpdate();
tx.commit();

}

@Override
public void deleteUserById(int userid) {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("Delete from Users where userID= :ID");
query.setParameter("ID", userid);
int result = query.executeUpdate();
tx.commit();

}

@Override
public void updateUser(Users user) {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();

session.saveOrUpdate(user);
tx.commit();

}

}

Our REST resource does not call the methods directly on the dao, instead its users service class UserService which is inside the service package. Below is the complete code:-

package com.sanjiv.service;

import java.util.ArrayList;
import java.util.List;

import com.sanjiv.dao.UserDao;
import com.sanjiv.model.Users;

public class UserService {
UserDao userDao;
public UserService(){
}
public UserDao getUserDao() {
return userDao;
}

public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}

public UserService(UserDao userDao){
this.userDao = userDao;
}
public void addUser(Users user){
userDao.addUser(user);
}
public Users getUserById(int userid){
Users user = userDao.getUserById(userid);
return user;
}
public List<Users> getUsers(){
List<Users> userList = new ArrayList<Users>();
userList = userDao.getUsers();
return userList;
}
public void deleteUser(int userid){
userDao.deleteUserById(userid);
}
public void deleteUsers(){
userDao.deleteUsers();
}

public void updateUser(Users user){
userDao.updateUser(user);
}
}

Next is Hibernate.cfg.xml :-

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- session-factory name=""> -->
<session-factory>
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:devDB</property>
  
  <property name="hibernate.connection.username">system</property>
  <property name="hibernate.connection.password">admin123</property>
  
  <property name="hibernate.connection.pool_size">1</property>
  <property name="show_sql">true</property> 
  <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
  <property name="hibernate.current_session_context_class">thread</property>
  
  <!-- property name="mappingDirectoryLocations">classpath:WEB-INF/classes/hibernate</property-->
  
   <!-- Mapping classes -->
   <mapping class="com.sanjiv.model.Users"/> 
   
</session-factory>
</hibernate-configuration>

And spring.xml-

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <bean id="userDao" class="com.sanjiv.dao.UserDao">
        <property name="sessionFactory" ref="hibernate3SessionFactory" />
    </bean>
    
    <bean id="userService" class="com.sanjiv.service.UserService">
        <property name="userDao" ref="userDao" />
    </bean>
    
    <!-- Hibernate3 XML SessionFactory Bean definition-->
     <bean id="hibernate3SessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="configLocation">
    <value>hibernate.cfg.xml</value>
  </property>
    </bean> 
    
</beans>

Now its to write our first REST web service which in my case is a UserResource class:-

package com.sanjiv.restws;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import weblogic.application.ApplicationContext;

import com.sanjiv.dao.UserDao;
import com.sanjiv.model.Users;
import com.sanjiv.service.UserService;
import com.sanjiv.utility.ConnectionHelper;
import com.sanjiv.utility.HibernateUtility;
import com.sun.jersey.json.impl.provider.entity.JSONArrayProvider;

@Path("/v1")

public class UserResource implements UserResourceInterface{

/* UsersService userService = new UsersService(new UsersDao
(HibernateUtility.buildSessionFactory()));*/
@Context
private UriInfo uriInfo;
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
UserService userService = (UserService) context.getBean("userService");
@GET
@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
public List<Users> getUsers() {
List<Users> usersList = new ArrayList<Users>();
usersList = userService.getUsers();

return usersList;
}
@GET
@Path("/users/{userid}")
@Produces(MediaType.APPLICATION_JSON)
public Users getUser(@PathParam("userid") int userid) {
Users user = userService.getUserById(userid);
return user;
}
@DELETE
@Path("/users/delete/{userid}")
public Response deleteUser(@PathParam("userid")int userid){
userService.deleteUser(userid);
return Response.ok().build();
}
@DELETE
@Path("/users/delete")
public Response deleteUsers(){
userService.deleteUsers();
return Response.ok().build();
}
/*@POST
@Consumes("application/json")
@Path("/users/{username}-{emailid}")
public Response saveUser(@PathParam("username") String userName,@PathParam("emailid") String emailID){
Users user = new Users();
user.setEmailID(emailID);
user.setUserName(userName);
userService.addUser(user);
return Response.ok().build();
}*/
@POST
@Path("/users")
@Consumes(MediaType.APPLICATION_JSON)
public String saveUser(Users user){
userService.addUser(user);
return Response.ok().build().toString();
}
@PUT
public Response updateUser(Users user){
userService.updateUser(user);
return Response.ok().build();
}
}

Now we will write our client which will call the methods on if the weservice. The code for client is inside client package. Below is the complete code:-

package com.sanjiv.restclient;

import javax.ws.rs.core.MediaType;

import com.google.gson.Gson;
import com.sanjiv.model.Users;
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;
import com.sun.jersey.api.json.JSONConfiguration;

public class RestJersyClient {

/**
* @param args
*/
public static void main(String[] args) {
final String ENDPOINT_URL = "http://localhost:7001/UsersRestWS/rest/v1/users/";
httpPost(ENDPOINT_URL);
//httpGet(ENDPOINT_URL,5);
//httpGet(ENDPOINT_URL,);
//httpDelete(ENDPOINT_URL);
}
private static void httpDelete(String endpointURL, int userid) {
endpointURL = endpointURL + "delete/" +userid;
System.out.println(endpointURL);
httpDelete(endpointURL);
}


private static void httpGet(String endpointURL, int userid) {
endpointURL = endpointURL +userid;
System.out.println(endpointURL);
httpGet(endpointURL);
}


private static void httpGet(String endpointURL){
try {

ClientConfig clientConfig = new DefaultClientConfig();

clientConfig.getFeatures().put(
JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

Client client = Client.create(clientConfig);

WebResource webResource = client
.resource(endpointURL);
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).get(ClientResponse.class);

if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}

String output = response.getEntity(String.class);

System.out.println("Server response .... \n");
System.out.println(output);

} catch (Exception e) {

e.printStackTrace();

}
}
private static void httpPost(String endpointURL){
try {

Users user = new Users();
user.setUserName("Sanjiv Dutta");
user.setEmailID("duttamca@gmail.com");

ClientConfig clientConfig = new DefaultClientConfig();

clientConfig.getFeatures().put(
JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

Client client = Client.create(clientConfig);

WebResource webResource = client
.resource(endpointURL);
String request = new Gson().toJson(user);
System.out.println(request);

ClientResponse response = webResource.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, request);

if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}

String output = response.getEntity(String.class);

System.out.println("Server response .... \n");
System.out.println(output);

} catch (Exception e) {

e.printStackTrace();

}
}
private static void httpDelete(String endpointURL){
endpointURL = endpointURL + "delete/";
System.out.println(endpointURL);
try {

ClientConfig clientConfig = new DefaultClientConfig();

clientConfig.getFeatures().put(
JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

Client client = Client.create(clientConfig);

WebResource webResource = client
.resource(endpointURL);
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).delete(ClientResponse.class);

if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}

String output = response.getEntity(String.class);

System.out.println("Server response .... \n");
System.out.println(output);

} catch (Exception e) {

e.printStackTrace();

}
}

}

First invoce the httpPost() method to insert the data using the REST web service. All the methods are self explanatory and can be used to send,receive,update,delete using the RESTful webservice.

This was just the very basic of REST web service. Thank for reading.