Java Reflection Tutorial

Hi all, this is my second post in 2015. Here in this tutorial i am going to focus little bit on Java’s one of the powerful concept called “Reflection”.

What is reflection?


“Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.” This concept is often mixed with introspection. Now let us see the definitions of “Reflection” & “Introspection”.

Introspection is the ability of a program to examine the type or properties of an object at runtime.
Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.

Reflection

Let us see simple code snippets about the two concepts as below.
Introspection Example: The instanceof operator determines whether an object belongs to a particular class.

if(obj instanceof CoffeeBean){
   CoffeeBean cb = (CoffeeBean)obj;
   cb.startMakingCoffee();
}

Reflection Example: The Class.forName() method returns the Class object associated with the class/interface with the given name(a string and full qualified name). The forName method causes the class with the name to be initialized.

// with reflection
Class<?> c = Class.forName("com.spark.beverages.CoffeeBean");
Object cb = c.newInstance();
Method m = c.getDeclaredMethod("startMakingCoffee", new Class<?>[0]);
m.invoke(cb);

Most of the web frameworks make use of reflection to make changes to objects using “Reflection”, some of the practical examples are as follows.

For example, Spring makes use of bean configuration such as:

<bean id="beanID" class="com.spark.beverages.CoffeeBean>
    <property name="someField" value="someValue" />
</bean>

When the Spring context processes this element, it will use Class.forName(String) with the argument “com.spark.beverages.CoffeeBean” to instantiate that Class. It will then again use reflection to get the appropriate setter for the element and set its value to the specified value.

let us consider the Servlet web applications, the same explanation applies to servlet configuration files also

<servlet>
    <servlet-name>someServlet</servlet-name>
    <servlet-class>com.spark.beverages.CoffeeBeanServlet</servlet-class>
<servlet>

Now let us see some examples on how to make use of Reflection API in java. Please go through the code carefully and its very easy to understand. The below code explains how to call different methods with different parameters and different return types.

/**
 * 
 */
package com.spark.java8.reflection;

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

/**
 * @author Sony
 *
 */
public class CoffeeBean {

	public void startMakingCoffee() {
		System.out.println("Coffee Making Started ...");
	}

	public void startMakingCoffee(String coffeeName) {
		System.out.println("Making of " + coffeeName + " Started ...");
	}

	public List<String> getBevarages() {
		List<String> list = new ArrayList<>(); // Using Java 7 feature
		list.add("Moka");
		list.add("caffuccino");
		list.add("Espressino");
		list.add("Black eye");
		list.add("Iced coffee");
		return list;
	}

	public int getTimeToMakeCoffee(String coffeeName) {
		if ("caffuccino".equalsIgnoreCase(coffeeName)) {
			return 15;
		} else {
			return 5;
		}
	}

}
/**
 * 
 */
package com.spark.java8.reflection.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author Sony
 *
 */
public class ReflectionTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Class<?> clazz = Class
					.forName("com.spark.java8.reflection.CoffeeBean");
			Object object = clazz.newInstance();
			Method method = clazz.getDeclaredMethod("startMakingCoffee", null);
			method.setAccessible(true);
			method.invoke(object, null);
			
			System.out.println("-----------------------------------------------");
			Method method2 = clazz.getDeclaredMethod("startMakingCoffee",
					new Class[] { String.class });
			method2.setAccessible(true);
			method2.invoke(object, "caffuccino");
			
			System.out.println("-----------------------------------------------");
			Method method3 = clazz.getDeclaredMethod("getBevarages", null);
			method3.setAccessible(true);
			List<?> name = (List<?>) method3.invoke(object, null);
			for (Object object2 : name) {
				System.out.println(object2);
			}
			
			System.out.println("-----------------------------------------------");
			Method method4 = clazz.getDeclaredMethod("getTimeToMakeCoffee", new Class[]{String.class});
			method4.setAccessible(true);
			String beverageName = "Cold coffee";
			int time = (int) method4.invoke(object, beverageName);
			System.out.println("time to make "+beverageName+" is "+time+" mins");
			
		}
		//Using Java 7 feature of Multiple Catch.
		catch (ClassNotFoundException | NoSuchMethodException
				| SecurityException | IllegalAccessException
				| IllegalArgumentException | InvocationTargetException
				| InstantiationException e) {
			e.printStackTrace();
		}
	}

}

Happy Reflections 🙂 Happy Coding 🙂

Primefaces 5 example

Here is an example on how to use jsf framework to develop a fully blown JavaEE application. when it comes to jsf all should know its a specification from sun and has been implemented by lot many vendors, some of them are “PrimeFaces”, “RichFaces”, “IceFaces”. The advantage of using JSF is the UI components are directly binded to Managed bean properties(value injection). In this example i want to show how to push data to database and retrieve from database to front end. This example is implemented in “Primefaces5.1”, “Maven”, “MySql”.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spark.jsf.primefaces</groupId>
	<artifactId>PrimeFacesTutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>PrimeFacesTutorial</name>
	<description>PrimeFacesTutorial</description>

	<repositories>
		<repository>
			<id>prime-repo</id>
			<name>PrimeFaces Maven Repository</name>
			<url>http://repository.primefaces.org</url>
			<layout>default</layout>
		</repository>
	</repositories>

	<properties>
		<java.version>1.6</java.version>
		<servlet.version>3.0.1</servlet.version>
		<jsf.version>2.2.4</jsf.version>
		<primefaces.version>5.1</primefaces.version>
	</properties>

	<dependencies>
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet.version}</version>
		</dependency>
		<!-- Faces Implementation -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>${jsf.version}</version>
		</dependency>
		<!-- Faces Library -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>${jsf.version}</version>
		</dependency>
		<!-- Primefaces Version 5 -->
		<dependency>
			<groupId>org.primefaces</groupId>
			<artifactId>primefaces</artifactId>
			<version>${primefaces.version}</version>
		</dependency>
		<!-- JSP Library -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
		</dependency>
		<!-- JSTL Library -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.1.2</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency>
	</dependencies>

	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warSourceDirectory>webapp</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
		<finalName>primefaces-tutorial</finalName>
	</build>
</project>

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"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>PrimeFaces Web Application</display-name>

	<!-- Change to "Production" when you are ready to deploy -->
	<context-param>
		<param-name>javax.faces.PROJECT_STAGE</param-name>
		<param-value>Development</param-value>
	</context-param>

	<context-param>
		<description>State saving method: 'client' or 'server' (=default). See
			JSF Specification 2.5.2</description>
		<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
		<param-value>client</param-value>
	</context-param>

	<context-param>
		<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
		<param-value>resources.application</param-value>
	</context-param>

	<!-- Welcome page -->
	<welcome-file-list>
		<welcome-file>login.xhtml</welcome-file>
	</welcome-file-list>

	<!-- JSF mapping -->
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map these files with JSF -->
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.jsf</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.faces</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>

</web-app>

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">
	

</faces-config>

Once done with our configuration files let us write the page from which the operations are done.
login.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:p="http://primefaces.org/ui">

<h:head>
	<h:outputStylesheet name="css/custom-styles.css" />
</h:head>
<body>
	<h:form>
		<p:panelGrid columns="2">
			<p:outputLabel value="FirstName"></p:outputLabel>
			<p:inputText value="#{loginBean.firstName}"></p:inputText>

			<p:outputLabel value="LastName"></p:outputLabel>
			<p:inputText value="#{loginBean.lastName}"></p:inputText>

			<p:outputLabel value="Email"></p:outputLabel>
			<p:inputText value="#{loginBean.emailText}"></p:inputText>

			<p:outputLabel value="Password"></p:outputLabel>
			<p:password value="#{loginBean.password}"></p:password>

			<p:commandButton action="#{loginBean.saveValues()}" value="Submit"></p:commandButton>
		</p:panelGrid>

		<p:dataTable var="loginBean" value="#{loginBean.loginBeans}">
			<p:column headerText="First Name">
				<h:outputText value="#{loginBean.firstName}" />
			</p:column>

			<p:column headerText="Last Name">
				<h:outputText value="#{loginBean.lastName}" />
			</p:column>

			<p:column headerText="Email Id">
				<h:outputText value="#{loginBean.emailText}" />
			</p:column>

			<p:column headerText="Password">
				<h:outputText value="#{loginBean.password}" />
			</p:column>
		</p:dataTable>
	</h:form>

</body>
</html>

let us write a DTO in which we hold the data.

/**
 * 
 */
package com.spark.jsf.vo;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;

/**
 * @author Sony
 *
 */
@ManagedBean(name="loginVO")
@SessionScoped
public class LoginBeanVO {

	private String firstName;
	private String lastName;
	private String emailText;
	private String password;
	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}
	/**
	 * @param firstName the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}
	/**
	 * @param lastName the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	/**
	 * @return the emailText
	 */
	public String getEmailText() {
		return emailText;
	}
	/**
	 * @param emailText the emailText to set
	 */
	public void setEmailText(String emailText) {
		this.emailText = emailText;
	}
	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}
	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((emailText == null) ? 0 : emailText.hashCode());
		result = prime * result
				+ ((firstName == null) ? 0 : firstName.hashCode());
		result = prime * result
				+ ((lastName == null) ? 0 : lastName.hashCode());
		result = prime * result
				+ ((password == null) ? 0 : password.hashCode());
		return result;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		LoginBeanVO other = (LoginBeanVO) obj;
		if (emailText == null) {
			if (other.emailText != null)
				return false;
		} else if (!emailText.equals(other.emailText))
			return false;
		if (firstName == null) {
			if (other.firstName != null)
				return false;
		} else if (!firstName.equals(other.firstName))
			return false;
		if (lastName == null) {
			if (other.lastName != null)
				return false;
		} else if (!lastName.equals(other.lastName))
			return false;
		if (password == null) {
			if (other.password != null)
				return false;
		} else if (!password.equals(other.password))
			return false;
		return true;
	}
	
	
}

Here comes the major part of our code, its our backing bean which controls our jsf page. There are lot many concepts involved in the below code, we achieve dependency injection using @ManagedProperty annotation in the below code we have injected the dao and dto objects to backing bean using @ManagedProperty annotation , also we used ExternalContext object to redirect to the jsf page from managed bean.

/**
 * 
 */
package com.spark.jsf.managed.beans;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.context.RequestContext;

import com.spark.jsf.dao.impl.LoginSaveDAOImpl;
import com.spark.jsf.vo.LoginBeanVO;
import com.spark.security.EncryptPassword;

/**
 * @author Sony
 *
 */
@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean {

	private String firstName;
	private String lastName;
	private String emailText;
	private String password;
	private List<LoginBeanVO> loginBeans = new ArrayList<LoginBeanVO>();

	@ManagedProperty(value = "#{loginVO}")
	private LoginBeanVO loginBeanVO;

	@ManagedProperty(value = "#{loginSaveDao}")
	private LoginSaveDAOImpl loginSaveDAOImpl;

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the emailText
	 */
	public String getEmailText() {
		return emailText;
	}

	/**
	 * @param emailText the emailText to set
	 */
	public void setEmailText(String emailText) {
		this.emailText = emailText;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the loginSaveDAOImpl
	 */
	public LoginSaveDAOImpl getLoginSaveDAOImpl() {
		return loginSaveDAOImpl;
	}

	/**
	 * @param loginSaveDAOImpl
	 *            the loginSaveDAOImpl to set
	 */
	public void setLoginSaveDAOImpl(LoginSaveDAOImpl loginSaveDAOImpl) {
		this.loginSaveDAOImpl = loginSaveDAOImpl;
	}

	/**
	 * @return the loginBeanVO
	 */
	public LoginBeanVO getLoginBeanVO() {
		return loginBeanVO;
	}

	/**
	 * @param loginBeanVO
	 *            the loginBeanVO to set
	 */
	public void setLoginBeanVO(LoginBeanVO loginBeanVO) {
		this.loginBeanVO = loginBeanVO;
	}

	/**
	 * @return the loginBeans
	 */
	public List<LoginBeanVO> getLoginBeans() {
		return loginBeans;
	}

	/**
	 * @param loginBeans the loginBeans to set
	 */
	public void setLoginBeans(List<LoginBeanVO> loginBeans) {
		this.loginBeans = loginBeans;
	}
	
	@PostConstruct
	public void getLoginDetails(){
		
		loginBeans = loginSaveDAOImpl.getLoginBeans();
	}

	public void saveValues() {

		loginBeanVO.setFirstName(firstName);
		loginBeanVO.setLastName(lastName);
		loginBeanVO.setEmailText(emailText);
		EncryptPassword encryptPassword = new EncryptPassword("");
		String encryptedPassword = encryptPassword.encrypt(password);

		loginBeanVO.setPassword(encryptedPassword);
		boolean status = loginSaveDAOImpl.saveCredentialsToDatabase(loginBeanVO);
		
		if(status){
			FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "User details saved successfully !");
			RequestContext.getCurrentInstance().showMessageInDialog(facesMessage);
			populateLoginBeanList();
			ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
		    try {
				ec.redirect(((HttpServletRequest) ec.getRequest()).getRequestURI());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Failed to Save user, might be user with same email id already exist !");
			RequestContext.getCurrentInstance().showMessageInDialog(facesMessage);
		}
		
	}
	
	public void populateLoginBeanList(){
		loginBeans = loginSaveDAOImpl.getLoginBeans();
	}

}

here our dao layer logic.

/**
 * 
 */
package com.spark.jsf.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;

import com.spark.jsf.db.DBUtil;
import com.spark.jsf.vo.LoginBeanVO;

/**
 * @author Sony
 *
 */
@ManagedBean(name= "loginSaveDao")
@SessionScoped
public class LoginSaveDAOImpl {

	List<LoginBeanVO> loginBeanVOs;
	
	public boolean saveCredentialsToDatabase(LoginBeanVO loginBeanVO) {
		boolean status = false;
		System.out.println(loginBeanVO.getFirstName() + "  "
				+ loginBeanVO.getLastName() + "  " + loginBeanVO.getPassword());
		Connection connection = DBUtil.getDBConnection();
		System.out.println("Got the connection object: " + connection);
		String sql = "insert into login(first_name,last_name,email_id,password) values(?,?,?,?)";
		if (!checkUserWithEmailExist(connection, loginBeanVO.getEmailText())) {
			try {
				PreparedStatement preparedStatement = connection
						.prepareStatement(sql);
				preparedStatement.setString(1, loginBeanVO.getFirstName());
				preparedStatement.setString(2, loginBeanVO.getLastName());
				preparedStatement.setString(3, loginBeanVO.getEmailText());
				preparedStatement.setString(4, loginBeanVO.getPassword());
				preparedStatement.execute();
				System.out.println("--------------- Values Saved to Database ---------------");
				status = true;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else {
			System.out
					.println("------------ user already exist with the same email id ---------------");
			status = false;
		}
		return status;
	}

	private boolean checkUserWithEmailExist(Connection connection,
			String emailText) {
		String sql = "select * from login where email_id = ?";
		boolean userExist = false;
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement(sql);
			preparedStatement.setString(1, emailText);
			ResultSet resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				userExist = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return userExist;
	}
	
	public List<LoginBeanVO> getLoginBeans(){
		loginBeanVOs = new ArrayList<LoginBeanVO>();
		String sql = "select * from login";
		Connection connection = DBUtil.getDBConnection();
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement(sql);
			ResultSet resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				LoginBeanVO beanVO = new LoginBeanVO();
				beanVO.setFirstName(resultSet.getString("first_name"));
				beanVO.setLastName((resultSet.getString("last_name")));
				beanVO.setEmailText((resultSet.getString("email_id")));
				beanVO.setPassword((resultSet.getString("password")));
				loginBeanVOs.add(beanVO);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return loginBeanVOs;
	}
}

The speciality of this example is that i have implemented the PBEWithMD5AndDES algorith for encrypting and decrypting the passwords for security purpose.
SecurityUtils.java

/**
 * 
 */
package com.spark.security;

import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

/**
 * @author Sony
 *
 */
public class SecurityUtils {

	public static Cipher dCipher, eCipher;
	public SecurityUtils(String helperString) {
		//b-bit salt
		byte[] salt = {(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
                (byte) 0x56, (byte) 0x34, (byte) 0xE3, (byte) 0x03};
		
		// iteration count
		int iterationCount = 19;
		try {
			// generating a temporary key, Encryptinng with DES using a pass key
			
			KeySpec keySpec = new PBEKeySpec(helperString.toCharArray(), salt, iterationCount);
			SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
			
			eCipher = Cipher.getInstance(secretKey.getAlgorithm());
			dCipher = Cipher.getInstance(secretKey.getAlgorithm());
			
			AlgorithmParameterSpec algorithmParameterSpec = new PBEParameterSpec(salt, iterationCount);
			
			eCipher.init(Cipher.ENCRYPT_MODE, secretKey, algorithmParameterSpec);
			dCipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameterSpec);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

EncryptPassword.java

/**
 * 
 */
package com.spark.security;

import java.io.UnsupportedEncodingException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;

/**
 * @author Sony
 *
 */
public class EncryptPassword extends SecurityUtils{

	public EncryptPassword(String helperString) {
		super(helperString);
	}
	
	public String encrypt(String password){
		 try {
             // Encode the string into bytes using utf-8
             byte[] utf8 = password.getBytes("UTF8");
             // Encrypt
             byte[] enc = eCipher.doFinal(utf8);
             // Encode bytes to base64 to get a string
             return new sun.misc.BASE64Encoder().encode(enc);

      } catch (BadPaddingException e) {
    	  e.printStackTrace();
      } catch (IllegalBlockSizeException e) {
    	  e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
    	  e.printStackTrace();
      }
      return null;
	}
}

DecryptPassword.java

/**
 * 
 */
package com.spark.security;

/**
 * @author Sony
 *
 */
public class DecryptPassword extends SecurityUtils {

	public DecryptPassword(String helperString) {
		super(helperString);
	}

	public String decrypt(String encryptedPassword) {
		try {
			// Decode base64 to get bytes
			byte[] dec = new sun.misc.BASE64Decoder()
					.decodeBuffer(encryptedPassword);
			// Decrypt
			byte[] utf8 = dCipher.doFinal(dec);
			// Decode using utf-8
			return new String(utf8, "UTF8");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

}

Let us have a helper class which will create a connection object and return DAO layer.

/**
 * 
 */
package com.spark.jsf.db;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @author Sony
 *
 */
public class DBUtil {

	private static Connection connection = null;
	
	private DBUtil(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getDBConnection(){
		if(connection == null){
			return new DBUtil().getConnection();
		}else{
			return connection;
		}
	}

	/**
	 * @return the connection
	 */
	public Connection getConnection() {
		return connection;
	}

	/**
	 * @param connection the connection to set
	 */
	public  void setConnection(Connection connection) {
		this.connection = connection;
	}
	
}

finally the output is as below.

ui

ExtJS With Spring MVC

Hi all its been long days i put a post on my blog. most of my colleagues were requesting me to put a write up on EXTJS and integrating it with Spring3.x MVC so here is my write for all those who were waiting for it. Basically EXTJS is Extended java script and every widget that you see on the page are coded as components and lot of features included in it. ExtJS comes in two flavors licensed and Open source. you can download ExtJS Lib from Sencha site.

the below is the java project struct for your reference
proj_struct

and here is the web project structure(Webcontent)
proj_struct2

Now lets start creating the UI. the main container which holds most of the components in the extjs page is called ViewPost and here is the code for that

Ext.require([ '*' ]);

Ext.onReady(function() {

	Ext.QuickTips.init();

	//Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider'));
	var panel;
	var viewport = Ext.create('Ext.Viewport', {
		id : 'border-example',
		layout : 'border',
		items : [

		Ext.create('Ext.Component', {
			region : 'north',
			height : 0

		}),

		{
			xtype : 'tabpanel',
			region : 'east',
			title : 'Help Menu',
			dockedItems : [ {
				dock : 'top',
				xtype : 'toolbar',
				items : [ '->', {
					xtype : 'button',
					text : 'test',
					tooltip : 'Test Button'
				} ]
			} ],
			animCollapse : true,
			collapsible : true,
			split : true,
			width : 225,
			minSize : 175,
			maxSize : 400,
			margins : '0 5 0 0',
			activeTab : 1,
			tabPosition : 'bottom',
			items : []
		}, {
			region : 'west',
			stateId : 'navigation-panel',
			id : 'west-panel',
			title : 'Navigation Menu',
			split : true,
			width : 200,
			minWidth : 175,
			maxWidth : 400,
			collapsible : true,
			animCollapse : true,
			margins : '0 0 0 5',
			layout : 'accordion',
			items : [ {
				contentEl : 'west',
				title : '<b>Inventory</b>',
				iconCls : 'nav'
			}, {
				title : 'Purchase Order',
				iconCls : 'settings'
			}, {
				title : 'Patient Management',
				iconCls : 'info'
			} ]
		},

		panel = Ext.create('Ext.tab.Panel', {
			region : 'center',
			deferredRender : false,
			activeTab : 0
		}) ]
	});
	Ext.select("a.newProduct").on('click', function() {
		var tabExists = false;
		var items = panel.items.items;
		for ( var i = 0; i < items.length; i++) {
			if (items[i].id === 'NewProduct') {
				panel.setActiveTab(i);
				tabExists = true;
				panel.setActiveTab(i);
			}
		}
		if (!tabExists) {
			panel.insert(1, NewProduct);
			panel.setActiveTab(0);
		}
	});
	
	Ext.select("a.newFrame").on('click', function() {
		var tabExists = false;
		var items = panel.items.items;
		for ( var i = 0; i < items.length; i++) {
			if (items[i].id === 'NewFrame') {
				panel.setActiveTab(i);
				tabExists = true;
				panel.setActiveTab(i);
			}
		}
		if (!tabExists) {
			panel.insert(1, NewFrame);
			panel.setActiveTab(0);
		}
	});
	
	Ext.select("a.searchProd").on('click', function() {
		var tabExists = false;
		var items = panel.items.items;
		for ( var i = 0; i < items.length; i++) {
			if (items[i].id === 'searchFrame') {
				panel.setActiveTab(i);
				tabExists = true;
				panel.setActiveTab(i);
			}
		}
		if (!tabExists) {
			panel.insert(1, SearchFrame);
			panel.setActiveTab(0);
		}
	});
	
	Ext.select("a.newContactLens").on('click', function() {
		var tabExists = false;
		var items = panel.items.items;
		if(items.length > 0){
			for(var i = 0 ; i < items.length; i++){
				if(items[i].id === 'newContactLens'){
					panel.setActiveTab(i);
					tabExists = true;
					panel.setActiveTab(i);
				}
			}
		}
		if(!tabExists){
			panel.insert(1,newContactLens);
			panel.setActiveTab(0);
		}
	});
});

below is the code for creating a tabbed panel which is inside the ViewPort and all the form components are in the TabbedPanel. this can be done as below.

var item_type_store = Ext.create('Ext.data.Store', {
	fields : [ 'text' ],
	data : [ {
		text : 'type_1'
	}, {
		text : 'type_2'
	}, {
		text : 'type_3'
	}, {
		text : 'type_4'
	}, {
		text : 'type_5'
	}, {
		text : 'type_6'
	} ]
});

var item_type = Ext.create('Ext.form.field.ComboBox', {
	store : item_type_store,
	fieldLabel : 'ItemType',
	name : 'itemtype',
	xtype: 'tbfill'
});

var item_location_store = Ext.create('Ext.data.Store', {
	fields : [ 'text' ],
	data : [ {
		text : 'location_1'
	}, {
		text : 'location_2'
	}, {
		text : 'location_3'
	}, {
		text : 'location_4'
	}, {
		text : 'location_5'
	}, {
		text : 'location_6'
	}, {
		text : 'location_7'
	} ]
});

var item_location = Ext.create('Ext.form.field.ComboBox', {
	store : item_location_store,
	fieldLabel : 'ItemLocation',
	name : 'itemLocation'
});

var supplier_name_store = Ext.create('Ext.data.Store', {
	fields : [ 'text' ],
	data : [ {
		text : 'supplier_1'
	}, {
		text : 'supplier_2'
	}, {
		text : 'supplier_3'
	}, {
		text : 'supplier_4'
	}, {
		text : 'supplier_5'
	}, {
		text : 'supplier_6'
	}, {
		text : 'supplier_7'
	} ]
});

var supplier_name = Ext.create('Ext.form.field.ComboBox', {
	store : supplier_name_store,
	fieldLabel : 'SupplierName',
	name : 'supplierName'
});

var brand_collection_store = Ext.create('Ext.data.Store', {
	fields : [ 'text' ],
	data : [ {
		text : 'Brand_1'
	}, {
		text : 'Brand_2'
	}, {
		text : 'Brand_3'
	}, {
		text : 'Brand_4'
	}, {
		text : 'Brand_5'
	}, {
		text : 'Brand_6'
	}, {
		text : 'Brand_7'
	}, {
		text : 'Brand_8'
	} ]
});

var brand_collection = Ext.create('Ext.form.field.ComboBox', {
	store : brand_collection_store,
	fieldLabel : 'Brand/Collection',
	name : 'brandCollection'
});

var NewProduct = Ext.create('Ext.form.Panel', {
	layout : 'vbox',
	contentEl : 'center2',
	title : 'New Product',
	id : 'NewProduct',
	defaults : {
		bodyPadding : 10

	},
	items : [ {
		xtype : 'panel',
		width : 900,
		collapsible: true,
		title : 'Product Details',
		defaults : {
			width : 230,
			cls : 'form-field'
		},
		defaultType : 'textfield',
		items : [ {
			fieldLabel : 'SrNo',
			name : 'srNo',
			value : '',
			validator : function(event) {
				if (!(/[0-9]/.test(this.getValue()))) {
					return "This Field should be in Numbers only";
				}
				return true;
			}
		}, {
			fieldLabel : 'ItemNumber',
			name : 'iteNumber',
			value : ''
		
		}, {
			fieldLabel : 'Description',
			name : 'desc',
			value : ''
		
		}, {
			fieldLabel : 'Item Code',
			name : 'itemCode',
			value : ''
		
		}, {
			xtype : item_type,
			labelClsExtra : 'form-field'
		}, {
			xtype : item_location,
			labelClsExtra : 'form-field'
		}, {
			xtype : supplier_name,
			labelClsExtra : 'form-field'
		}, {
			xtype : brand_collection,
			labelClsExtra : 'form-field'
		}, {
			fieldLabel : 'Tax(%)',
			name : 'itemTax',
			value : ''
		
		}]
	}, {
		xtype : 'panel',
		title : 'Product Attributes',
		width : 900,
		flex : 2,
		collapsible: true,
		defaults : {
			cls : 'form-field'
		},
		items : [ {
			xtype : 'checkbox',
			fieldLabel : 'Active',
			name : 'active',
			checked : false,
		}, {
			xtype : 'checkbox',
			fieldLabel : 'Discounted',
			name : 'discounted',
			checked : false,
		}, {
			xtype : 'checkbox',
			fieldLabel : 'Dispensable',
			name : 'dispensable',
			checked : false,
		}, {
			xtype : 'checkbox',
			fieldLabel : 'Taxable',
			name : 'taxable',
			checked : false,
		} ]
	},{
		xtype : 'panel',
		title : 'Product Cost Details',
		width : 900,
		flex : 2,
		collapsible: true,
		autoScroll: true,
		defaults : {
			cls : 'form-field'
		},
		items : [ {
			xtype : 'textfield',
			fieldLabel : 'SupplierCost',
			name : 'supplierCost',
			value : ''
		
		}, {
			xtype : 'textfield',
			fieldLabel : 'LandingCost',
			name : 'landingCost',
			value : ''
		
		}, {
			xtype : 'textfield',
			fieldLabel : 'LastOrdered',
			name : 'lastOrdered',
			value : ''
		}, {
			xtype : 'textfield',
			fieldLabel : 'LastReceived',
			name : 'lastReceived',
			value : ''
		},  {
			xtype : 'textfield',
			fieldLabel : 'QuantityOrdered',
			name : 'quantityOnOrder',
			value : ''
		
		}, {
			xtype : 'textfield',
			fieldLabel : 'QuantityReceived',
			name : 'quantityReceived',
			value : ''
		
		}]
	} ],
	buttons : [
			{
				text : 'Save',
				handler : function() {
					var productForm = this.up('form').getForm();
					if (!productForm.isValid()) {
						alert("Please enter proper details!");
					} else {
						console.log(productForm.getValues());
						Ext.Ajax.request({
							url : 'spring/product/newproduct',
							method : 'POST',
							params : {
								productDetails : Ext
										.encode(productForm.getValues())
							},
							scope : this,
							success : function(response) {
								// Received response from the server
								msg = Ext.decode(response.responseText);
								if (msg.success) {
									Ext.MessageBox.alert('',
											msg.message);
								} else {
									Ext.MessageBox.alert('',
											msg.message);
								}
							},
							failure : function(response) {
								Ext.MessageBox.alert(msg.message);
							}
						});
					}

				}
			}, {
				text : 'Cancel',
				handler : function() {
					this.up('form').getForm().reset();
				}
			} ]

});

the above code has lot many things to understand. There are data stores that got created, components such textfields, comboboxt etc , buttons and their handlers. inside the handlers we have Ajax calls that will submit the form data to our spring controller.

the main moto of ExtJs is one HTML and many JavaScript files now to launch our application we need one initial page that launches and renders the extjs components and here it goes

<html>
<head>
<title>Vision One</title>

<link rel="stylesheet" type="text/css"
	href="resources/extjs/resources/css/ext-all.css">
<link rel="stylesheet" type="text/css"
	href="resources/extjs/resources/css/vision-one-custom.css">
<script type="text/javascript" src="resources/extjs/ext-all-debug.js"></script>
<script type="text/javascript" src="view/newProduct.js"></script>
<script type="text/javascript" src="view/newContactLens.js"></script>
<script type="text/javascript" src="view/newFrame.js"></script>
<script type="text/javascript" src="view/searchProduct.js"></script>
<script type="text/javascript" src="view/vision_ui.js"></script>

</head>
<body>
	<!-- use class="x-hide-display" to prevent a brief flicker of the content -->
	<div id="west" class="x-hide-display">
		<ul>
			<li><a href="#" class="newProduct">New Product(others)</a></li>
			<li><a href="#" class="newFrame">New Frames</a></li>
			<li><a href="#" class="newContactLens">New Contact Lens</a></li>
			<li><a href="#" class="searchProd">Search Products</a></li>
			<li><a href="#" class="searchFrame">Search Frames</a></li>
			<li><a href="#" class="searchLense">Search Lenses</a></li>
		</ul>
	</div>
	<div id="center2" class="x-hide-display"></div>
	<div id="center1" class="x-hide-display"></div>
	<div id="props-panel" class="x-hide-display"
		style="width: 200px; height: 200px; overflow: hidden;"></div>
</body>
</html>

Now lets look at the Middleware where the technology used is Spring MVC. First the request from ExtJS hits one of our spring REST based controller from there the request is deligated to service layer(Service IMPL) and from there again the request is deligated to DAO layer(DAO IMPL). lets look into our spring REST controller implementation

package com.spark.visionone.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spark.visionone.model.GenericMessageObject;
import com.spark.visionone.model.NewFrame;
import com.spark.visionone.model.OtherProduct;
import com.spark.visionone.service.ProductService;
import com.spark.visionone.utils.VisionOneUtils;

/**
 * @author Pavan Kumar Mantha
 *
 */
@Controller
@RequestMapping(value="/product")
public class ProductController {
	
	@Autowired
	ProductService productService;
	
	@RequestMapping(value="/newproduct",method =RequestMethod.POST)
	public @ResponseBody String saveProductDetails(HttpServletRequest httpServletRequest){
		
		String jsonStr = httpServletRequest.getParameter("productDetails");
		System.out.println(jsonStr);
		OtherProduct otherProduct = VisionOneUtils.JsonToJava(jsonStr, OtherProduct.class);
		GenericMessageObject genericMessageObject = productService.saveProductDetails(otherProduct);
		String jsonResonseStr = VisionOneUtils.JavaToJson(genericMessageObject);
		return jsonResonseStr;
	}
	
}

In the above implementation if you observer the method is annotaed as “@ResponseBody” which will help spring controller to return JSON object back to the ExtJS.

Now its time to see our Service Layer.

package com.spark.visionone.service;

import com.spark.visionone.model.GenericMessageObject;
import com.spark.visionone.model.NewFrame;
import com.spark.visionone.model.OtherProduct;

/**
 * @author Pavan kumar made class to return
 *         GenericMessageObject and passing OtherProduct object as parameter
 */
public interface ProductService {

	public GenericMessageObject saveProductDetails(OtherProduct otherProduct);

}

Now lets see the implementation of the service interface that we have created.

/**
 * 
 */
package com.spark.visionone.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.spark.visionone.dao.ProductDAO;
import com.spark.visionone.model.GenericMessageObject;
import com.spark.visionone.model.NewFrame;
import com.spark.visionone.model.OtherProduct;
import com.spark.visionone.service.ProductService;

/**
 * @author Pavan Kumar Mantha
 *
 */
@Service(value="productService")
public class ProductServiceImpl implements ProductService{

	@Autowired
	ProductDAO productDAO;
	
	@Override
	public GenericMessageObject saveProductDetails(OtherProduct otherProduct) {
		return productDAO.saveProduct(otherProduct);
	}

}

Now lets us look into the interface and its implementation of DAO Layer at once.

/**
 * 
 */
package com.spark.visionone.dao;

import com.spark.visionone.model.GenericMessageObject;
import com.spark.visionone.model.NewFrame;
import com.spark.visionone.model.OtherProduct;

/**
 * @author PavanKumar Mantha
 *
 */
public interface ProductDAO {

	public GenericMessageObject saveProduct(OtherProduct otherProduct);
}

/**
 * 
 */
package com.spark.visionone.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.spark.visionone.dao.ProductDAO;
import com.spark.visionone.model.GenericMessageObject;
import com.spark.visionone.model.NewFrame;
import com.spark.visionone.model.OtherProduct;

/**
 * @author PavanKumar Mantha
 *
 */
@Repository(value="productDAO")
public class ProductDAOImpl implements ProductDAO {

	@PersistenceContext
	EntityManager entityManager;
	/* (non-Javadoc)
	 * @see com.spark.visionone.dao.ProductDAO#saveProduct(com.spark.visionone.model.OtherProduct)
	 */
	@Override
	public GenericMessageObject saveProduct(OtherProduct otherProduct) {
		GenericMessageObject genericMessageObject = new GenericMessageObject();
		try {
			
			/*
			 *  logic to persist
			 *  entityManager.persist(otherProduct);
			 */
			entityManager.persist(otherProduct);
			System.out.println("Other Product: "+otherProduct.getBrandCollection());
			genericMessageObject.setSuccess(true);
			genericMessageObject.setMessage("details saved successfully !");
		} catch (Exception e) {
			e.printStackTrace();
			genericMessageObject.setSuccess(false);
			genericMessageObject.setMessage("Exception in saving details !");
		}
		return genericMessageObject;
	}
	
	
}

Here we used JPA to persist the objects to back end database.
the below are the different Model (pojo) classes that are used in the project for data storage and communication between different layers.

BaseVO.java

/**
 * 
 */
package com.spark.visionone.model;

import java.io.Serializable;
import java.sql.Date;

import javax.persistence.Column;

/**
 * @author PavanKumar Mantha
 * 
 */
public class BaseVO implements Serializable {

	private Date createdDate;
	private Date updateDate;

	/**
	 * @return the createdDate
	 */
	@Column
	public Date getCreatedDate() {
		return createdDate;
	}

	/**
	 * @param createdDate
	 *            the createdDate to set
	 */
	public void setCreatedDate(Date createdDate) {
		this.createdDate = createdDate;
	}

	/**
	 * @return the updateDate
	 */
	@Column
	public Date getUpdateDate() {
		return updateDate;
	}

	/**
	 * @param updateDate
	 *            the updateDate to set
	 */
	public void setUpdateDate(Date updateDate) {
		this.updateDate = updateDate;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((createdDate == null) ? 0 : createdDate.hashCode());
		result = prime * result
				+ ((updateDate == null) ? 0 : updateDate.hashCode());
		return result;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof BaseVO)) {
			return false;
		}
		BaseVO other = (BaseVO) obj;
		if (createdDate == null) {
			if (other.createdDate != null) {
				return false;
			}
		} else if (!createdDate.equals(other.createdDate)) {
			return false;
		}
		if (updateDate == null) {
			if (other.updateDate != null) {
				return false;
			}
		} else if (!updateDate.equals(other.updateDate)) {
			return false;
		}
		return true;
	}

}

OtherProduct.java

/**
 * 
 */
package com.spark.visionone.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author PavanKumar Mantha
 * 
 */
@Entity
@Table(name="new_product")
public class OtherProduct extends BaseVO implements Serializable {

	private String srNo;
	private String iteNumber;
	private String desc;
	private String itemCode;
	private String itemtype;
	private String ItemLocation;
	private String supplierName;
	private String brandCollection;
	private String active;
	private String discounted;
	private String dispensable;
	private String taxable;
	private String supplierCost;
	private String landingCost;
	private String lastOrdered;
	private String lastReceived;
	private String lastSold;
	private String quantityOnOrder;
	private String quantityOnHand;
	private String totalSold;
	private String quantityReceived;

	/**
	 * @return the srNo
	 */
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="SrNo")
	public String getSrNo() {
		return srNo;
	}

	/**
	 * @param srNo
	 *            the srNo to set
	 */
	public void setSrNo(String srNo) {
		this.srNo = srNo;
	}

	/**
	 * @return the iteNumber
	 */
	@Column
	public String getIteNumber() {
		return iteNumber;
	}

	/**
	 * @param iteNumber
	 *            the iteNumber to set
	 */
	public void setIteNumber(String iteNumber) {
		this.iteNumber = iteNumber;
	}

	/**
	 * @return the desc
	 */
	@Column
	public String getDesc() {
		return desc;
	}

	/**
	 * @param desc
	 *            the desc to set
	 */
	public void setDesc(String desc) {
		this.desc = desc;
	}

	/**
	 * @return the itemCode
	 */
	@Column
	public String getItemCode() {
		return itemCode;
	}

	/**
	 * @param itemCode
	 *            the itemCode to set
	 */
	public void setItemCode(String itemCode) {
		this.itemCode = itemCode;
	}

	/**
	 * @return the itemtype
	 */
	@Column
	public String getItemtype() {
		return itemtype;
	}

	/**
	 * @param itemtype
	 *            the itemtype to set
	 */
	public void setItemtype(String itemtype) {
		this.itemtype = itemtype;
	}

	/**
	 * @return the itemLocation
	 */
	@Column
	public String getItemLocation() {
		return ItemLocation;
	}

	/**
	 * @param itemLocation
	 *            the itemLocation to set
	 */
	public void setItemLocation(String itemLocation) {
		ItemLocation = itemLocation;
	}

	/**
	 * @return the supplierName
	 */
	@Column
	public String getSupplierName() {
		return supplierName;
	}

	/**
	 * @param supplierName
	 *            the supplierName to set
	 */
	public void setSupplierName(String supplierName) {
		this.supplierName = supplierName;
	}

	/**
	 * @return the brandCollection
	 */
	@Column
	public String getBrandCollection() {
		return brandCollection;
	}

	/**
	 * @param brandCollection
	 *            the brandCollection to set
	 */
	public void setBrandCollection(String brandCollection) {
		this.brandCollection = brandCollection;
	}

	/**
	 * @return the active
	 */
	@Column
	public String getActive() {
		return active;
	}

	/**
	 * @param active
	 *            the active to set
	 */
	public void setActive(String active) {
		this.active = active;
	}

	/**
	 * @return the discounted
	 */
	@Column
	public String getDiscounted() {
		return discounted;
	}

	/**
	 * @param discounted
	 *            the discounted to set
	 */
	public void setDiscounted(String discounted) {
		this.discounted = discounted;
	}

	/**
	 * @return the dispensable
	 */
	@Column
	public String getDispensable() {
		return dispensable;
	}

	/**
	 * @param dispensable
	 *            the dispensable to set
	 */
	public void setDispensable(String dispensable) {
		this.dispensable = dispensable;
	}

	/**
	 * @return the taxable
	 */
	@Column
	public String getTaxable() {
		return taxable;
	}

	/**
	 * @param taxable
	 *            the taxable to set
	 */
	public void setTaxable(String taxable) {
		this.taxable = taxable;
	}

	/**
	 * @return the supplierCost
	 */
	@Column
	public String getSupplierCost() {
		return supplierCost;
	}

	/**
	 * @param supplierCost
	 *            the supplierCost to set
	 */
	public void setSupplierCost(String supplierCost) {
		this.supplierCost = supplierCost;
	}

	/**
	 * @return the landingCost
	 */
	@Column
	public String getLandingCost() {
		return landingCost;
	}

	/**
	 * @param landingCost
	 *            the landingCost to set
	 */
	public void setLandingCost(String landingCost) {
		this.landingCost = landingCost;
	}

	/**
	 * @return the lastOrdered
	 */
	@Column
	public String getLastOrdered() {
		return lastOrdered;
	}

	/**
	 * @param lastOrdered
	 *            the lastOrdered to set
	 */
	public void setLastOrdered(String lastOrdered) {
		this.lastOrdered = lastOrdered;
	}

	/**
	 * @return the lastReceived
	 */
	@Column
	public String getLastReceived() {
		return lastReceived;
	}

	/**
	 * @param lastReceived
	 *            the lastReceived to set
	 */
	public void setLastReceived(String lastReceived) {
		this.lastReceived = lastReceived;
	}

	/**
	 * @return the lastSold
	 */
	@Column
	public String getLastSold() {
		return lastSold;
	}

	/**
	 * @param lastSold
	 *            the lastSold to set
	 */
	public void setLastSold(String lastSold) {
		this.lastSold = lastSold;
	}

	/**
	 * @return the quantityOnOrder
	 */
	@Column
	public String getQuantityOnOrder() {
		return quantityOnOrder;
	}

	/**
	 * @param quantityOnOrder
	 *            the quantityOnOrder to set
	 */
	public void setQuantityOnOrder(String quantityOnOrder) {
		this.quantityOnOrder = quantityOnOrder;
	}

	/**
	 * @return the quantityOnHand
	 */
	@Column
	public String getQuantityOnHand() {
		return quantityOnHand;
	}

	/**
	 * @param quantityOnHand
	 *            the quantityOnHand to set
	 */
	public void setQuantityOnHand(String quantityOnHand) {
		this.quantityOnHand = quantityOnHand;
	}

	/**
	 * @return the totalSold
	 */
	@Column
	public String getTotalSold() {
		return totalSold;
	}

	/**
	 * @param totalSold
	 *            the totalSold to set
	 */
	public void setTotalSold(String totalSold) {
		this.totalSold = totalSold;
	}
	
	/**
	 * @return the quantityReceived
	 */
	@Column
	public String getQuantityReceived() {
		return quantityReceived;
	}

	/**
	 * @param quantityReceived the quantityReceived to set
	 */
	public void setQuantityReceived(String quantityReceived) {
		this.quantityReceived = quantityReceived;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((ItemLocation == null) ? 0 : ItemLocation.hashCode());
		result = prime * result + ((active == null) ? 0 : active.hashCode());
		result = prime * result
				+ ((brandCollection == null) ? 0 : brandCollection.hashCode());
		result = prime * result + ((desc == null) ? 0 : desc.hashCode());
		result = prime * result
				+ ((discounted == null) ? 0 : discounted.hashCode());
		result = prime * result
				+ ((dispensable == null) ? 0 : dispensable.hashCode());
		result = prime * result
				+ ((iteNumber == null) ? 0 : iteNumber.hashCode());
		result = prime * result
				+ ((itemCode == null) ? 0 : itemCode.hashCode());
		result = prime * result
				+ ((itemtype == null) ? 0 : itemtype.hashCode());
		result = prime * result
				+ ((landingCost == null) ? 0 : landingCost.hashCode());
		result = prime * result
				+ ((lastOrdered == null) ? 0 : lastOrdered.hashCode());
		result = prime * result
				+ ((lastReceived == null) ? 0 : lastReceived.hashCode());
		result = prime * result
				+ ((lastSold == null) ? 0 : lastSold.hashCode());
		result = prime * result
				+ ((quantityOnHand == null) ? 0 : quantityOnHand.hashCode());
		result = prime * result
				+ ((quantityOnOrder == null) ? 0 : quantityOnOrder.hashCode());
		result = prime * result + ((srNo == null) ? 0 : srNo.hashCode());
		result = prime * result
				+ ((supplierCost == null) ? 0 : supplierCost.hashCode());
		result = prime * result
				+ ((supplierName == null) ? 0 : supplierName.hashCode());
		result = prime * result + ((taxable == null) ? 0 : taxable.hashCode());
		result = prime * result
				+ ((totalSold == null) ? 0 : totalSold.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof OtherProduct)) {
			return false;
		}
		OtherProduct other = (OtherProduct) obj;
		if (ItemLocation == null) {
			if (other.ItemLocation != null) {
				return false;
			}
		} else if (!ItemLocation.equals(other.ItemLocation)) {
			return false;
		}
		if (active == null) {
			if (other.active != null) {
				return false;
			}
		} else if (!active.equals(other.active)) {
			return false;
		}
		if (brandCollection == null) {
			if (other.brandCollection != null) {
				return false;
			}
		} else if (!brandCollection.equals(other.brandCollection)) {
			return false;
		}
		if (desc == null) {
			if (other.desc != null) {
				return false;
			}
		} else if (!desc.equals(other.desc)) {
			return false;
		}
		if (discounted == null) {
			if (other.discounted != null) {
				return false;
			}
		} else if (!discounted.equals(other.discounted)) {
			return false;
		}
		if (dispensable == null) {
			if (other.dispensable != null) {
				return false;
			}
		} else if (!dispensable.equals(other.dispensable)) {
			return false;
		}
		if (iteNumber == null) {
			if (other.iteNumber != null) {
				return false;
			}
		} else if (!iteNumber.equals(other.iteNumber)) {
			return false;
		}
		if (itemCode == null) {
			if (other.itemCode != null) {
				return false;
			}
		} else if (!itemCode.equals(other.itemCode)) {
			return false;
		}
		if (itemtype == null) {
			if (other.itemtype != null) {
				return false;
			}
		} else if (!itemtype.equals(other.itemtype)) {
			return false;
		}
		if (landingCost == null) {
			if (other.landingCost != null) {
				return false;
			}
		} else if (!landingCost.equals(other.landingCost)) {
			return false;
		}
		if (lastOrdered == null) {
			if (other.lastOrdered != null) {
				return false;
			}
		} else if (!lastOrdered.equals(other.lastOrdered)) {
			return false;
		}
		if (lastReceived == null) {
			if (other.lastReceived != null) {
				return false;
			}
		} else if (!lastReceived.equals(other.lastReceived)) {
			return false;
		}
		if (lastSold == null) {
			if (other.lastSold != null) {
				return false;
			}
		} else if (!lastSold.equals(other.lastSold)) {
			return false;
		}
		if (quantityOnHand == null) {
			if (other.quantityOnHand != null) {
				return false;
			}
		} else if (!quantityOnHand.equals(other.quantityOnHand)) {
			return false;
		}
		if (quantityOnOrder == null) {
			if (other.quantityOnOrder != null) {
				return false;
			}
		} else if (!quantityOnOrder.equals(other.quantityOnOrder)) {
			return false;
		}
		if (srNo == null) {
			if (other.srNo != null) {
				return false;
			}
		} else if (!srNo.equals(other.srNo)) {
			return false;
		}
		if (supplierCost == null) {
			if (other.supplierCost != null) {
				return false;
			}
		} else if (!supplierCost.equals(other.supplierCost)) {
			return false;
		}
		if (supplierName == null) {
			if (other.supplierName != null) {
				return false;
			}
		} else if (!supplierName.equals(other.supplierName)) {
			return false;
		}
		if (taxable == null) {
			if (other.taxable != null) {
				return false;
			}
		} else if (!taxable.equals(other.taxable)) {
			return false;
		}
		if (totalSold == null) {
			if (other.totalSold != null) {
				return false;
			}
		} else if (!totalSold.equals(other.totalSold)) {
			return false;
		}
		return true;
	}
}

GenericMessageObject.java

/**
 * 
 */
package com.spark.visionone.model;

import java.io.Serializable;

/**
 * @author PavanKumar Mantha
 * 
 */
public class GenericMessageObject implements Serializable{

	private Boolean success;
	private String message;

	/**
	 * @return the success
	 */
	public Boolean getSuccess() {
		return success;
	}

	/**
	 * @param success
	 *            the success to set
	 */
	public void setSuccess(Boolean success) {
		this.success = success;
	}

	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message
	 *            the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}

}

Here are the configuration files required for Spring and JPA to run un combination.
WEB-INF/spring/application-context.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:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:task="http://www.springframework.org/schema/task"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

	<!-- Activates various annotations to be detected in bean classes for ex @Autowired -->
	<context:annotation-config/>
	<mvc:annotation-driven></mvc:annotation-driven>
	
	<context:component-scan base-package="com.spark.visionone"/>
	
	<tx:annotation-driven/>
	
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="persistentUnit"/>
		<property name="dataSource" ref="dataSource"/>
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="showSql" value="true"/>
				<property name="generateDdl" value="false"/>
				<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
			</bean>
		</property>
	</bean>
	
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql://localhost:3306/visionone"/>
		<property name="username" value="root"/>
		<property name="password" value="root"/>
	</bean>
	
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory"/>
	</bean>
</beans>

WEB-INF/spring/spring-context.xml

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

	<context:annotation-config/>
	<mvc:annotation-driven></mvc:annotation-driven>
	
	<context:component-scan base-package="com.spark.visionone"/>
	
	<tx:annotation-driven/>
	
	
	<!-- <mvc:resources location="/extjs/**" mapping="/resources/extjs"/> -->
</beans:beans>

WEB-INF/classes/META-INF/persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
	version="2.0">
	
	<persistence-unit name="persistentUnit" transaction-type="RESOURCE_LOCAL">
	<class>com.spark.visionone.model.OtherProduct</class>
	<class>com.spark.visionone.model.BaseVO</class>
	<class>com.spark.visionone.model.GenericMessageObject</class>
	</persistence-unit>
	
</persistence>

The project depending libs are as follows:
project-libs

this completes the coding part and its time for deployment and running the project. we can deploy the project to any web container and ran and say submit once all the fields ad filled you can see the request to spring controller is fired as below and data is sent in JSON format

finally the screen looks like this:
finalScreen

request

Dedicated to all those who want to learn EXTJS
Happy Coding 🙂

James Gosling grades Oracle’s handling of Sun’s technology

Gosling says Oracle has done ‘surprisingly well’ with Java

With the four-year anniversary of Oracle’s Sun Microsystems acquisition looming, we reached out to Java founder James Gosling to rate how Oracle has done in shepherding Sun technology.
Gosling gives Oracle eyebrow-raising grades, lauding Oracle’s handling of Java,despite his past acrimony toward Oracle over Java, and giving Oracle a flat-out failing grade on what has become of Solaris OS.
Gosling was a longtime Sun technologist and, briefly, a CTO at Oracle right after Oracle bought Sun in January 2010. He is considered the father of Java, which was founded at Sun in 1995. Asked how different technologies have faired under Oracle’s stewardship, Gosling graded Oracle and offered his own perspectives:
sample

These days, Gosling is chief software architect at Liquid Robotics, which develops ocean-based robotics. After leaving Oracle in 2010, Gosling stopped presenting at the JavaOne technical conference, but he reappeared onstage at the event in October 2012.

Credits : directly taken from “www.infoworld.com”
Java is great…

Web services using JAXB

Hi Guys here is my brief post on how to develop web services using jaxb notation.

The Java Architecture for XML Binding API (JAXB) makes it easy to access XML documents from applications written in the Java programming language. JAXB is an alternative to using a SAX or DOM parser to access the data in an XML document. When you access an XML document with JAXB, first you bind the schema for the XML document into a set of Java classes that represents the schema. Then you unmarshal the XML document. Unmarshalling a document means creating a tree of content objects that represents the content and organization of the document.

You can also use JAXB to build an XML document. To build an XML document with JAXB, you first bind the schema for the XML document you want to build. Then you create a content tree. Lastly, you marshal the content tree into an XML document.

The following diagram, from Java Architecture for XML Binding API, shows the processes both for accessing and for building XML documents from Java applications.


Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion.
No extra jaxb libraries are required if you are using JDK1.6 or above, because JAXB is bundled in JDK 1.6.
Note
For JDK < 1.6, download JAXB from here and put “jaxb-api.jar” and “jaxb-impl.jar” on your project classpath.

now lets see how to code with “jaxb”

/**
 * 
 */
package com.spark.jaxb.model;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Pavan Mantha
 * 
 */
@SuppressWarnings("serial")
@XmlRootElement
public class Customer implements Serializable {

	private int id;
	private String firstName;
	private String lastName;
	private String designation;
	private String phoneNumber;

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	@XmlAttribute
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	@XmlElement
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	@XmlElement
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the designation
	 */
	public String getDesignation() {
		return designation;
	}

	/**
	 * @param designation
	 *            the designation to set
	 */
	@XmlElement
	public void setDesignation(String designation) {
		this.designation = designation;
	}

	/**
	 * @return the phoneNumber
	 */
	public String getPhoneNumber() {
		return phoneNumber;
	}

	/**
	 * @param phoneNumber
	 *            the phoneNumber to set
	 */
	@XmlElement
	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

}

now its time to code jaxb marshaller,

/**
 * 
 */
package com.spark.jaxb.marshaller;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.spark.jaxb.model.Customer;

/**
 * @author Pavan Mantha
 * 
 */
public class JaxbMarshaller {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Customer customer = new Customer();
		customer.setId(100);
		customer.setFirstName("Pavan");
		customer.setLastName("Mantha");
		customer.setDesignation("SoftwareEngineer");
		customer.setPhoneNumber("123-4567-890");

		try {

			File file = new File("C:\\customer.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

			// output pretty printed
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

			jaxbMarshaller.marshal(customer, file);
			jaxbMarshaller.marshal(customer, System.out);

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}

and unmarshaller as below.

/**
 * 
 */
package com.spark.jaxb.unmarshaller;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.spark.jaxb.model.Customer;

/**
 * @author Pavan Mantha
 * 
 */
public class JaxbUnmarshaller {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {

			File file = new File("C:\\customer.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
			System.out.println(customer);

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}

Happy Coding 🙂

Building REST web services using Jersey and Maven

Hi guys, here is my post regarding how to develop restful web services using jersey and maven. Before we go into development of service lets discuss some concepts of REST.
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.

Summary of JAX-RS Annotations

@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.

Now lets see how to develop the rest service.
1.first create a maven project and add the following dependencies to your POM.xml as below –

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spark.jersy.service</groupId>
	<artifactId>JersyService</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>JersyService</name>
	<description>JersyService</description>


	<dependencies>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-server</artifactId>
			<version>1.17</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-servlet</artifactId>
			<version>1.17</version>
		</dependency>
		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>jsr311-api</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-client</artifactId>
			<version>1.17</version>
		</dependency>
	</dependencies>
</project>

now its to code your rest service, lets name the service as RestService in the package “com.spark.rest.service” as below –

/**
 * 
 */
package com.spark.rest.service;

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 Sony
 *
 */
@Path("/hello")
public class RestService {

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Path("/{name}")
	public String getMessage(@PathParam("name") String name){

		return "{'name':"+name+",'desg':'SoftWareEngg','Age':'26'}";
	}

}

lets publish our web service as a servlet so, lets code web.xml as below –

<?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">
	
	<servlet>
		<servlet-name>jersey-servlet</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.spark.rest.service</param-value>
		</init-param>
		
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>jersey-servlet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
</web-app>

Test your service by deploying into Tomcat(any version, preferably >5.x) and request from browser as below –
http://localhost:8080/JerseyService/rest/hello/{yourname}”, in return you get a response of JSON string.

suppose, if u want to test the web service using a standalone client lets code a main method as below –

/**
 * 
 */
package com.spark.rest.service.client;

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.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 Sony
 * 
 */
public class JerseyRestClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		ClientConfig clientConfig = new DefaultClientConfig();
		Client client = Client.create(clientConfig);

		WebResource webResource = client.resource(getBaseURI());

		System.out.println(webResource.path("rest").path("hello/pavan")
				.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class)
				.toString());

	}

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

}

References:(with courtesy)
1.http://docs.oracle.com/javaee/6/tutorial/doc/giepu.html
2.http://www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/
3.http://www.vogella.com/articles/REST/article.html

Happy RESTful coding 🙂

Consuming web service using Spring 3.x

Hi guys, Here i am going to demonstrate how to consume web service using spring framework.Consuming web services with Spring framework is amazingly easy. It avoids the need of creating client side stubs during compile time and does the same at run time. A typical web service client can be configured as shown below-

inorder to get the spring capability for webservice please add the following dependencies to pom.xml as below-

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.spark.spring.webservice</groupId>
  <artifactId>SpringWebService</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringWebService</name>
  <description>SpringWebService</description>
  
  <dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-core</artifactId>
  		<version>3.1.1.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context</artifactId>
  		<version>3.1.1.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context-support</artifactId>
  		<version>3.1.1.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-beans</artifactId>
  		<version>3.1.1.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework.ws</groupId>
  		<artifactId>spring-ws-core</artifactId>
  		<version>2.1.1.RELEASE</version>
  	</dependency>
  </dependencies>
</project>

please configure your applicationContext.xml as below-

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

	<bean id="myWebService"
		class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
		<property name="serviceInterface" value="com.spark.webservice.TemperatureConverter" />
		<property name="wsdlDocumentUrl" value="http://localhost:8080/JBossWebServices?wsdl" />
		<property name="namespaceUri" value="http://impl.webservice.spark.com/" />
		<property name="serviceName" value="TemperatureConverter" />
		<property name="portName" value="TemperatureConverterImplPort" />
	</bean>

</beans>

Where serviceInterface is the business interface that clients will use for invoking service methods. wsdlDocumentUrl is the URL for the published WSDL file. Spring will download WSDL from the given URL and generate the client side stubs when it creates the bean usually during application start up. namespaceUri corresponds to the targetNamespace in the .wsdl file. serviceName corresponds to the service name in the .wsdl file. portName corresponds to the port name in the .wsdl file.

Note Please refer to my previous port to get the wsdl file.

Now accessing web service pretty easy, just get the bean from Spring context and use that to invoke methods-

/**
 * 
 */
package com.spark.spring.webservice.client;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spark.webservice.TemperatureConverter;

/**
 * @author Sony
 *
 */
public class SpringWebserviceClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		TemperatureConverter converter = (TemperatureConverter)applicationContext.getBean("myWebService");
		System.out.println(converter.convertCelsiusToFahrenheit(42.0));
	}

}

inorder to use the service we need to create the service interface type as below –

/**
 * 
 */
package com.spark.webservice;

import javax.jws.WebMethod;
import javax.jws.WebService;

/**
 * @author Sony
 *
 */
@SuppressWarnings("restriction")
@WebService
public interface TemperatureConverter {

	@WebMethod
	public double convertCelsiusToFahrenheit(double value);
	@WebMethod
	public double convertFahrenheitToCelsius(double value);
}

Thats it now run the main method and get the result.
Note: the service should be up and running in the server.

Happy Coding 🙂