Spring MVC Security

Hi All, these days most of the people are asking me how to execute Spring Security in their Applications, as i did not worked on it, i thought of implementing myself, and here is the outcome(this post).Sometimes you need to secure our application page from unauthorized access. In the below example, we will ensure secure URL access by providing custom Login form . User need to provide correct login credential to view the page.

Using Servlet filters, Spring Security catch the incoming HTTP request and enforce security checking by providing custom Login form.

The project structure looks as below.
proj_struct

Lets have a look at the configuration first and then will go to logic.

spring-security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/security
	http://www.springframework.org/schema/security/spring-security-3.2.xsd">

	<http auto-config="true">
		<intercept-url pattern="/admin**" access="ROLE_USER" />
		<form-login
			login-page="/login"
			default-target-url="/welcome"
			authentication-failure-url="/login?error"
			username-parameter="username"
			password-parameter="password"/>
		<logout logout-success-url="/login?logout"/>
		<csrf/>
	</http>

	<authentication-manager>
		<authentication-provider>
			<user-service>
				<user name="pavan" password="pavan@123" authorities="ROLE_USER" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

</beans:beans>

In above congratulation, the /admin and sub-folders of it are all password protected.Cross Site Request Forgery (CSRF) Protection, If CSRF is enabled, you have to include a _csrf.token in the page you want to login or logout.

mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	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">

	<context:component-scan base-package="com.spark.spring.security" />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
</beans>

once our spring configurations are done, lets move on to logic.

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

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.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Sony
 *
 */
@Controller
public class SecurityController {

	@RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
	public ModelAndView getWelcomePage() {

		ModelAndView view = new ModelAndView();
		view.addObject("Title", "Spring Security Demo");
		view.addObject("Message", "Spring Security Welcomes you !");
		view.setViewName("hello");
		return view;
	}

	@RequestMapping(value = { "/admin**" }, method = RequestMethod.GET)
	public ModelAndView getAdminPage() {

		ModelAndView model = new ModelAndView();
		model.addObject("Title", "Spring Security Demo");
		model.addObject("Message", "This is protected admin page!");
		model.setViewName("admin");

		return model;
	}

	// Spring Security, Custom login page uses this control method
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(
			@RequestParam(value = "error", required = false) String error,
			@RequestParam(value = "logout", required = false) String logout) {

		ModelAndView model = new ModelAndView();
		if (error != null) {
			model.addObject("error", "Invalid username and password!");
		}

		if (logout != null) {
			model.addObject("msg", "You've been logged out successfully.");
		}
		model.setViewName("login");

		return model;

	}
}

if you look at the above logic the admin page will be secured by redirecting us to the custom login page using “login” method shown in the above controller. Now its time to design the UI pages

hello.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page session="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	
	<h1>Title : ${Title}</h1>	
	<h1>Message : ${Message}</h1>	
</body>
</html>

admin.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>
<html>
<body>
	<h1>Title : ${Title}</h1>
	<h1>Message : ${Message}</h1>

	<c:url value="/j_spring_security_logout" var="logoutUrl" />

	<!-- csrt for log out-->
	<form action="${logoutUrl}" method="post" id="logoutForm">
		<input type="hidden" name="${_csrf.parameterName}"
			value="${_csrf.token}" />
	</form>

	<script>
		function formSubmit() {
			document.getElementById("logoutForm").submit();
		}
	</script>

	<c:if test="${pageContext.request.userPrincipal.name != null}">
		<h2>
			Welcome : ${pageContext.request.userPrincipal.name} | <a
				href="javascript:formSubmit()"> Logout</a>
		</h2>
	</c:if>

</body>
</html>

login.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login Page</title>
<style>
.error {
	padding: 15px;
	margin-bottom: 20px;
	border: 1px solid transparent;
	border-radius: 4px;
	color: #a94442;
	background-color: #f2dede;
	border-color: #ebccd1;
}

.msg {
	padding: 15px;
	margin-bottom: 20px;
	border: 1px solid transparent;
	border-radius: 4px;
	color: #31708f;
	background-color: #d9edf7;
	border-color: #bce8f1;
}

#login-box {
	width: 300px;
	padding: 20px;
	margin: 100px auto;
	background: #fff;
	-webkit-border-radius: 2px;
	-moz-border-radius: 2px;
	border: 1px solid #000;
}
</style>
</head>
<body onload='document.loginForm.username.focus();'>

	<h1>Spring Security Custom Login Form </h1>

	<div id="login-box">

		<h3>Login with Username and Password</h3>

		<c:if test="${not empty error}">
			<div class="error">${error}</div>
		</c:if>
		<c:if test="${not empty msg}">
			<div class="msg">${msg}</div>
		</c:if>

		<form name='loginForm'
			action="<c:url value='j_spring_security_check' />" method='POST'>

			<table>
				<tr>
					<td>User:</td>
					<td><input type='text' name='username' value=''></td>
				</tr>
				<tr>
					<td>Password:</td>
					<td><input type='password' name='password' /></td>
				</tr>
				<tr>
					<td colspan='2'><input name="submit" type="submit"
						value="submit" /></td>
				</tr>
			</table>

			<input type="hidden" name="${_csrf.parameterName}"
				value="${_csrf.token}" />

		</form>
	</div>

</body>
</html>

Thats it its the end of the Sample project which is implemented with Spring Security. finally lets have look at our pom.xml as below.

pom.xml

<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.security</groupId>
	<artifactId>SpringSecurityTutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>SpringSecurityTutorial</name>
	<description>SpringSecurityTutorial</description>

	<properties>
		<jdk.version>1.6</jdk.version>
		<spring.version>4.0.4.RELEASE</spring.version>
		<spring.security.version>3.2.3.RELEASE</spring.security.version>
		<jstl.version>1.2</jstl.version>
	</properties>

	<dependencies>

		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>${spring.security.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${spring.security.version}</version>
		</dependency>

		<!-- jstl for jsp page -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>
	</dependencies>
</project>

web.xml

<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<display-name>Spring MVC Secure Application</display-name>

	<!-- Spring MVC -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>

	<!-- Loads Spring Security config file -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring-security.xml
		</param-value>
	</context-param>

	<!-- Spring Security -->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy
		</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

So here are the output screens of the application.
type http://localhost:8080/SpringSecurityTutorial/ you be redirected to the below page.

welcome

once we type http://localhost:8080/SpringSecurityTutorial/ you be redirected to login page as its secured.
login

login-error

login-success

logout

Happy Securing the applications. ๐Ÿ™‚
Happy coding ๐Ÿ™‚

FusionCharts+Spring+Ajax calls

Hello all, in this post i am going to take you on a tour how to render fusion charts data dynamically. In my previous post i explained rendering data statically. Here i explain how to make Ajax calls, using ajax we are going to populate region,country. Based on the region and country we get the oilConsumedByCountry by year and change this data based on the country changed, and create a dashboard which displays “Pie and Bar” charts.

*Note: This post assumes you already downloaded FusionCharts API and Maven
Following is the script for creating db table.

DROP TABLE IF EXISTS `test`.`oilconsumebycountry`;
CREATE TABLE  `test`.`oilconsumebycountry` (
  `Region` varchar(45) NOT NULL,
  `Country` varchar(45) NOT NULL,
  `Fipscd` varchar(45) NOT NULL,
  `year_1980` double NOT NULL,
  `year_1981` double DEFAULT NULL,
  `year_1982` double DEFAULT NULL,
  `year_1983` double DEFAULT NULL,
  `year_1984` double DEFAULT NULL,
  `year_1985` double DEFAULT NULL,
  `year_1986` double DEFAULT NULL,
  `year_1987` double DEFAULT NULL,
  `year_1988` double DEFAULT NULL,
  `year_1989` double DEFAULT NULL,
  `year_1990` double DEFAULT NULL,
  `year_1991` double DEFAULT NULL,
  `year_1992` double DEFAULT NULL,
  `year_1993` double DEFAULT NULL,
  `year_1994` double DEFAULT NULL,
  `year_1995` double DEFAULT NULL,
  `year_1996` double DEFAULT NULL,
  `year_1997` double DEFAULT NULL,
  `year_1998` double DEFAULT NULL,
  `year_1999` double DEFAULT NULL,
  `year_2000` double DEFAULT NULL,
  `year_2001` double DEFAULT NULL,
  `year_2002` double DEFAULT NULL,
  `year_2003` double DEFAULT NULL,
  `year_2004` double DEFAULT NULL,
  `year_2005` double DEFAULT NULL,
  `year_2006` double DEFAULT NULL,
  `year_2007` double DEFAULT NULL,
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

lets have a look at configuration files applicationContext.xml,spring-context.xml,hibernate-cfg.xml,web.xml respectively.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	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.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/jdbc
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

	<context:component-scan base-package="com.spark.spring"></context:component-scan>
	<context:annotation-config />
	<tx:annotation-driven />
	
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
		<property name="password" value="root"></property>
		<property name="username" value="root"></property>
	</bean>

	<bean id="getCountryByCode" class="com.spark.spring.dao.GetCountryByCode">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property ref="dataSource" name="dataSource"></property>
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
		<property name="configurationClass">
			<value>org.hibernate.cfg.AnnotationConfiguration</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>
</beans>

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

	<context:annotation-config />
	<context:component-scan base-package="com.spark.spring"></context:component-scan>
	
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="suffix">
			<beans:value>.jsp</beans:value>
		</beans:property>
		<beans:property name="prefix">
			<beans:value>/</beans:value>
		</beans:property>
	</beans:bean>

</beans:beans>

<?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>
		<mapping class="com.spark.spring.model.Oilconsumebycountry" />
	</session-factory>
</hibernate-configuration>
<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	
	<servlet>
		<servlet-name>springServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-context.xml</param-value>
		</init-param>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>springServlet</servlet-name>
		<url-pattern>/spring/*</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>ajaxView.jsp</welcome-file>
	</welcome-file-list>
</web-app>

GlobalAjaxController.java
This controller calls the DAO layes to fetch the data required by client and converts it to JSON format and returns it back to client.

/**
 * 
 */
package com.spark.spring.controller;

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

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

import com.spark.spring.dao.OilconsumebycountryDAO;
import com.spark.spring.model.Oilconsumebycountry;

/**
 * @author Sony
 *
 */
@Controller
@RequestMapping(value="/load/**")
public class GlobalAjaxController {
	
	@Autowired
	OilconsumebycountryDAO oilconsumebycountryDAO;

	@RequestMapping(value="/load/allreagions")
	protected @ResponseBody String loadRegions(){

		List<String> regions = oilconsumebycountryDAO.getAllRegions();
		JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( regions );  
		return jsonArray.toString();
	}
	
	@RequestMapping(value="/load/{region}")
	protected @ResponseBody String loadCountriesByregion(@PathVariable String region){

		List<String> regions = oilconsumebycountryDAO.getCountriesByRegion(region);
		JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( regions );  
		return jsonArray.toString();
	}
	
	@RequestMapping(value="/load/{region}/{country}")
	protected @ResponseBody String loadConsuptionByCountryAndRegion(@PathVariable String region,@PathVariable String country){

		Oilconsumebycountry oilconsumebycountry = oilconsumebycountryDAO.getAllOilConsumedByCountriesAndRegion(region, country);
		
		String consuption = "{}";
		List<Double> oil = new ArrayList<Double>();
		oil.add(oilconsumebycountry.getYear1980());
		oil.add(oilconsumebycountry.getYear1981());
		oil.add(oilconsumebycountry.getYear1982());
		oil.add(oilconsumebycountry.getYear1983());
		oil.add(oilconsumebycountry.getYear1984());
		oil.add(oilconsumebycountry.getYear1985());
		oil.add(oilconsumebycountry.getYear1986());
		oil.add(oilconsumebycountry.getYear1987());
		oil.add(oilconsumebycountry.getYear1988());
		oil.add(oilconsumebycountry.getYear1989());
		oil.add(oilconsumebycountry.getYear1990());
		oil.add(oilconsumebycountry.getYear1991());
		oil.add(oilconsumebycountry.getYear1992());
		oil.add(oilconsumebycountry.getYear1993());
		oil.add(oilconsumebycountry.getYear1994());
		oil.add(oilconsumebycountry.getYear1995());
		oil.add(oilconsumebycountry.getYear1996());
		oil.add(oilconsumebycountry.getYear1997());
		oil.add(oilconsumebycountry.getYear1998());
		oil.add(oilconsumebycountry.getYear1999());
		oil.add(oilconsumebycountry.getYear2000());
		oil.add(oilconsumebycountry.getYear2001());
		oil.add(oilconsumebycountry.getYear2002());
		oil.add(oilconsumebycountry.getYear2003());
		oil.add(oilconsumebycountry.getYear2004());
		oil.add(oilconsumebycountry.getYear2005());
		oil.add(oilconsumebycountry.getYear2006());
		oil.add(oilconsumebycountry.getYear2007());
		
		JSONObject jsonObject = (JSONObject)JSONSerializer.toJSON(consuption);
		JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(oil);
		jsonObject.put("consuption", jsonArray);
		System.out.println(jsonObject);
		return jsonObject.toString();
	}
}

OilconsumebycountryDAO.java

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

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.spark.spring.model.Oilconsumebycountry;

/**
 * @author Sony
 *
 */
@Repository(value="oilconsumebycountryDAO")
public class OilconsumebycountryDAO extends HibernateDaoSupport{

	@Autowired
	public void init(SessionFactory sessionFactory){
		setSessionFactory(sessionFactory);
	}
	
	public Oilconsumebycountry getAllOilConsumedByCountriesAndRegion(String region,String country){
		List<Integer> id = null;
		String hql = "select o.id from Oilconsumebycountry o where o.region=:region and o.country=:country";
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Query query = session.createQuery(hql);
		query.setParameter("region", region);
		query.setParameter("country", country);
		id = query.list();
		session.close();
		Oilconsumebycountry oilconsumebycountry = getHibernateTemplate().get(Oilconsumebycountry.class, id.get(0));
		return oilconsumebycountry;
	}
	
	public List<String> getCountriesByRegion(String region){
		List<String> countries = null;
		String hql = "select distinct o.country from Oilconsumebycountry o where o.region=:region";
		try {
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Query query = session.createQuery(hql);
			query.setParameter("region", region);
			countries = query.list();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return countries;
	}
	
	public List<String> getAllRegions(){
		List<String> regions = null;
		String hql = "select distinct o.region from Oilconsumebycountry o";
		try {
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Query query = session.createQuery(hql);
			regions = query.list();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return regions;
	}
}

Oilconsumebycountry.java

package com.spark.spring.model;

import java.io.Serializable;

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

/**
 * <p>
 * Pojo mapping TABLE oilconsumebycountry
 * </p>
 * <p>
 * </p>
 * 
 * <p>
 * Generated at Sun Jul 07 16:38:56 IST 2013
 * </p>
 * 
 * @author Sony 
 * 
 */
@Entity
@Table(name = "oilconsumebycountry", catalog = "test")
@SuppressWarnings("serial")
public class Oilconsumebycountry implements Serializable {

	/**
	 * Attribute region.
	 */
	private int id;
	/**
	 * Attribute region.
	 */
	private String region;

	/**
	 * Attribute country.
	 */
	private String country;

	/**
	 * Attribute fipscd.
	 */
	private String fipscd;

	/**
	 * Attribute year1980.
	 */
	private Double year1980;

	/**
	 * Attribute year1981.
	 */
	private Double year1981;

	/**
	 * Attribute year1982.
	 */
	private Double year1982;

	/**
	 * Attribute year1983.
	 */
	private Double year1983;

	/**
	 * Attribute year1984.
	 */
	private Double year1984;

	/**
	 * Attribute year1985.
	 */
	private Double year1985;

	/**
	 * Attribute year1986.
	 */
	private Double year1986;

	/**
	 * Attribute year1987.
	 */
	private Double year1987;

	/**
	 * Attribute year1988.
	 */
	private Double year1988;

	/**
	 * Attribute year1989.
	 */
	private Double year1989;

	/**
	 * Attribute year1990.
	 */
	private Double year1990;

	/**
	 * Attribute year1991.
	 */
	private Double year1991;

	/**
	 * Attribute year1992.
	 */
	private Double year1992;

	/**
	 * Attribute year1993.
	 */
	private Double year1993;

	/**
	 * Attribute year1994.
	 */
	private Double year1994;

	/**
	 * Attribute year1995.
	 */
	private Double year1995;

	/**
	 * Attribute year1996.
	 */
	private Double year1996;

	/**
	 * Attribute year1997.
	 */
	private Double year1997;

	/**
	 * Attribute year1998.
	 */
	private Double year1998;

	/**
	 * Attribute year1999.
	 */
	private Double year1999;

	/**
	 * Attribute year2000.
	 */
	private Double year2000;

	/**
	 * Attribute year2001.
	 */
	private Double year2001;

	/**
	 * Attribute year2002.
	 */
	private Double year2002;

	/**
	 * Attribute year2003.
	 */
	private Double year2003;

	/**
	 * Attribute year2004.
	 */
	private Double year2004;

	/**
	 * Attribute year2005.
	 */
	private Double year2005;

	/**
	 * Attribute year2006.
	 */
	private Double year2006;

	/**
	 * Attribute year2007.
	 */
	private Double year2007;

        // Generate Getters and Setters..

}

This is the JSP file used as view, data from controller is rendered here using a jquery script.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script
	src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="inner_js/FusionCharts.js"></script>
<script src="inner_js/inner_js.js"></script>
</head>
<body>
	<table>
		<tr>
			<td>Regions:<select id="regions" name="regions"></select></td>
			<td>Countries:<select id="country" name="country"></select></td>
		</tr>
	</table>
	<div style="width: 1300px;">
		<div id="piechartContainer" style="float: left; width: 600px;">FusionCharts
			XT will load here!</div>
		<div id="barchartContainer" style="float: right; width: 600px;">FusionCharts
			XT will load here!</div>
		<br style="clear: left;" />
	</div>
</body>
</html>

This is the javascript file from which the Ajax calls are fired to the controller, and data is collected by this script and rendered into view.

$(document).ready(function(){
	$.ajax({
		url:"http://localhost:8080/SpringFusionCharts/spring/load/allreagions",
		dataType:"json",
		success:function(data){
			var options = '<option>----select----</option>';
		      for (var i = 0; i < data.length; i++) {
		        options += '<option value="' + data[i] + '">' + data[i] + '</option>';
		      }
		      $("#regions").html(options);

		},error:function(data){
		}
	});
	
	$("#regions").on("change",function(){
		$.ajax({
			url:"http://localhost:8080/SpringFusionCharts/spring/load/"+$(this).val(),
			dataType:"json",
			success:function(data){
				var options = '<option>----select----</option>';
			      for (var i = 0; i < data.length; i++) {
			        options += '<option value="' + data[i] + '">' + data[i] + '</option>';
			      }
			      $("#country").html(options);

			},error:function(data){
			}
		});
	});
	
	$("#country").on("change",function(){
		var dataStr = {
				'chart' : {
					'caption' : 'oil consumed by country',
					'xAxisName' : 'years',
					'yAxisName' : 'consuption',
					'numberPrefix' : ''
				},
				'data' : [ ]
			};
		var dataObjectArray = new Array();
		
		var myPieChart = new FusionCharts("Charts/Pie3D.swf",
				"myChartId", "750", "450", "0");
		var myBarChart = new FusionCharts("Charts/Column3D.swf",
				"myChartId2", "750", "450", "0");
		$.ajax({
			url:"http://localhost:8080/SpringFusionCharts/spring/load/"+$("#regions").val()+"/"+$(this).val(),
			dataType:"json",
			success:function(data){
				var i = 1980;
				$.each(data.consuption, function(key, value) {
					var dataObject = {
							label:'',
							value:''
						};
					dataObject.label = "year_"+i;
					dataObject.value = value;
					dataObjectArray.push(dataObject);
					i++;
				});
				dataStr.data = dataObjectArray;
				myPieChart.setJSONData(dataStr);
				myPieChart.render("piechartContainer");

				myBarChart.setJSONData(dataStr);
				myBarChart.render("barchartContainer");
			},error:function(data){
			}
		});
		
	});
});

Output1:
data1

Output2:
After changing the region and country the data changes dynamically.
data2
Happy Coding ๐Ÿ™‚

Spring3+Hibernate3+FusionChartsXT for reporting

Hello all, from past few days i was working on some reports and dashboards so the requirement is to call some spring services, which return the data in the form of JSON. my responsibility is to receive the JSON data and feed it to correct chart and render it so im here to share my experience in the form of small example.

please create a database as shown below:

DROP TABLE IF EXISTS `test`.`maps`;
CREATE TABLE  `test`.`maps` (
  `ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `STATE_NAME` varchar(100) NOT NULL,
  `STATE_CODE` varchar(10) NOT NULL,
  `POPULATION` varchar(5) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

please download the fusionchartsXT latest(trail) version from here, after you download, create a mavanized project in eclipse.
In the pom.xml please add the below content.

<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.fusioncharts</groupId>
	<artifactId>SpringFusionCharts</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>SpringFusionCharts</name>
	<description>SpringFusionCharts</description>

	<properties>
		<jdk.version>1.6</jdk.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate</artifactId>
			<version>3.5.4-Final</version>
			<type>pom</type>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-annotations</artifactId>
			<version>3.5.4-Final</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.15</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.12.1.GA</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringFusionCharts</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>false</downloadJavadocs>
					<wtpversion>2.0</wtpversion>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

once this step is done all your dependencies(jar files) are managed my maven.now go and create “WEB-INF,charts,javascript” folders in src/main/webapp. In WEB-INF please put web.xml as follows.

<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
	
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-context.xml</param-value>
		</init-param>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/spring/*</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

After this step please extract the downloaded FusionChartsXT.zip in desired location, from that navigate to the folder charts, copy all the swf files and put them in the charts folder of your eclipse(src/main/webapp/charts)
now again from the FusionChartsXT home copy “FusionCharts.js,Jquery.min.js” and put them in javascript folder of your eclipse.
Now it’s time to code logic.Lets integrate Spring and Hibernate to query the database and here i transform the
result from database to JSON format, and return that to JSP.

Note: please create separate packages for interfaces and their implementations as it gives the project a clear separation between layers(good practice)

Let us see the ServiceLayer:

package com.spark.spring.fusioncharts.service;

import java.util.List;

import com.spark.spring.fusioncharts.model.Maps;

public interface GetStatasticsDataService {

	public List<Maps> getPopulationByCountry();
}

/**
 * 
 */
package com.spark.spring.fusioncharts.service.impl;

import java.util.List;

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

import com.spark.spring.fusioncharts.dao.GetStatasticsData;
import com.spark.spring.fusioncharts.model.Maps;
import com.spark.spring.fusioncharts.service.GetStatasticsDataService;

/**
 * @author Sony
 *
 */
@Service(value="GetStatasticsDataServiceImpl")
public class GetStatasticsDataServiceImpl implements GetStatasticsDataService {

	@Autowired
	GetStatasticsData getStatasticsData;
	
	/* (non-Javadoc)
	 * @see com.spark.spring.fusioncharts.service.GetStatasticsDataService#getOilConsumebyCountry()
	 */
	@Override
	public List<Maps> getPopulationByCountry() {
		
		return getStatasticsData.getOilConsumebyCountry();
	}

}

Let us see the DAOLayer:

/**
 * 
 */
package com.spark.spring.fusioncharts.dao;

import java.util.List;

import com.spark.spring.fusioncharts.model.Maps;

/**
 * @author Sony
 *
 */
public interface GetStatasticsData {

	public List<Maps> getPopulationByCountry();
}

/**
 * 
 */
package com.spark.spring.fusioncharts.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.spark.spring.fusioncharts.dao.GetStatasticsData;
import com.spark.spring.fusioncharts.model.Maps;

/**
 * @author Sony
 *
 */
@Repository(value="GetStatasticsDataImpl")
public class GetStatasticsDataImpl extends HibernateDaoSupport implements GetStatasticsData{

	@Autowired
	public void init(SessionFactory factory) {
	    setSessionFactory(factory);
	}
	
	@Override
	public List<Maps> getPopulationByCountry() {
		
		List<Maps> mapsList = getHibernateTemplate().loadAll(Maps.class);
		return mapsList;
	}

}

Let us see the ModelLayer:

package com.spark.spring.fusioncharts.model;

import java.io.Serializable;

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

/**
 * <p>Pojo mapping TABLE maps</p>
 * <p></p>
 *
 * <p>Generated at Sun Jun 30 20:56:48 IST 2013</p>
 * @author Salto-db Generator v1.0.16 / EJB3
 * 
 */
@Entity
@Table(name = "maps")
@SuppressWarnings("serial")
public class Maps implements Serializable {

	/**
	 * Attribute id.
	 */
	private Integer id;
	
	/**
	 * Attribute stateName.
	 */
	private String stateName;
	
	/**
	 * Attribute stateCode.
	 */
	private String stateCode;
	
	/**
	 * Attribute population.
	 */
	private String population;
	
	
	/**
	 * <p> 
	 * </p>
	 * @return id
	 */
	@Basic
	@Id
	@GeneratedValue
	@Column(name = "ID")
		public Integer getId() {
		return id;
	}

	/**
	 * @param id new value for id 
	 */
	public void setId(Integer id) {
		this.id = id;
	}
	
	/**
	 * <p> 
	 * </p>
	 * @return stateName
	 */
	@Basic
	@Column(name = "STATE_NAME", length = 100)
		public String getStateName() {
		return stateName;
	}

	/**
	 * @param stateName new value for stateName 
	 */
	public void setStateName(String stateName) {
		this.stateName = stateName;
	}
	
	/**
	 * <p> 
	 * </p>
	 * @return stateCode
	 */
	@Basic
	@Column(name = "STATE_CODE", length = 10)
		public String getStateCode() {
		return stateCode;
	}

	/**
	 * @param stateCode new value for stateCode 
	 */
	public void setStateCode(String stateCode) {
		this.stateCode = stateCode;
	}
	
	/**
	 * <p> 
	 * </p>
	 * @return population
	 */
	@Basic
	@Column(name = "POPULATION", length = 5)
		public String getPopulation() {
		return population;
	}

	/**
	 * @param population new value for population 
	 */
	public void setPopulation(String population) {
		this.population = population;
	}
}

Let us see the ControllerLayer:

/**
 * 
 */
package com.spark.spring.fusioncharts.controller;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spark.spring.fusioncharts.model.Maps;
import com.spark.spring.fusioncharts.service.GetStatasticsDataService;

/**
 * @author Sony
 *
 */
@Controller
public class ChartsController {
	
	@Autowired
	GetStatasticsDataService getStatasticsDataService;

	@RequestMapping(value="/charts")
	public @ResponseBody String getChartsDashboard(){
		List<Maps> oilconsumebycountries = getStatasticsDataService.getPopulationByCountry();
		JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(oilconsumebycountries);
		return jsonArray.toString();
	}
	
	

}

Now let’s start looking at the resource files inorder to configure the application.

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	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.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/jdbc
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

	<context:component-scan base-package="com.spark.spring.fusioncharts"></context:component-scan>
	<context:annotation-config></context:annotation-config>
	<mvc:annotation-driven></mvc:annotation-driven>

	<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/test" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
		<property name="configurationClass">
			<value>org.hibernate.cfg.AnnotationConfiguration</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>
</beans>

spring-context

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

	<!-- Enables the Spring MVC @Controller programming Model -->
	<context:component-scan base-package="com.spark.spring.fusioncharts"></context:component-scan>
	<context:annotation-config></context:annotation-config>
	<annotation-driven></annotation-driven>

	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix">
			<beans:value>/WEB-INF/pages/</beans:value>
		</beans:property>
		<beans:property name="suffix">
			<beans:value>.jsp</beans:value>
		</beans:property>

	</beans:bean>

</beans:beans>

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>
        <mapping class="com.spark.spring.fusioncharts.model.Maps" />
    </session-factory>
</hibernate-configuration>

log4j.properties

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D\:\\logger.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
 
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
 
# Root logger option
#log4j.rootLogger=debug, file, stdout
log4j.rootLogger=info, ROOT, file
#log4j.rootLogger=fatal, file, stdout
#log4j.rootLogger=ERROR, file, stdout

Now lets code the view(JSP) part of our project.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>spring3.2+Fusion Charts</title>
<script type="text/javascript" src="javascript/jquery.min.js"></script>
<script type="text/javascript" src="javascript/FusionCharts.js"></script>
<script type="text/javascript" src="javascript/Mycharts.js"></script>
</head>
<body>
	<div style="width: 1300px;">
		<div id="piechartContainer" style="float: left; width: 600px;">FusionCharts XT will load here!</div>
		<div id="barchartContainer" style="float: right; width: 600px;">FusionCharts XT will load here!</div>
		<br style="clear: left;" />
	</div>
	
	<div style="width: 1300px;">
		<div id="pyramidchartContainer" style="float: left; width: 600px;">FusionCharts XT will load here!</div>
		<div id="linechartContainer" style="float: right; width: 600px;">FusionCharts XT will load here!</div>
		<br style="clear: left;" />
	</div>

</body>
</html>

inorder to render the charts in our dashboard please write your own javascript code as follows
Mycharts.js

$(document).ready(
		function() {
			$.ajax({
				url : "http://localhost:8080/SpringMVC/spring/charts",
				dataType : "json",
				success : function(data) {
					
					var dataObjectArray = new Array();
					
					var myPieChart = new FusionCharts("Charts/Pie3D.swf",
							"myChartId", "750", "450", "0");
					var myBarChart = new FusionCharts("Charts/Column3D.swf",
							"myChartId2", "750", "450", "0");
					var myLineChart = new FusionCharts("Charts/Line.swf",
							"myChartId3", "750", "450", "0");
					var myPyramidChart = new FusionCharts("Charts/Pyramid.swf",
							"myChartId3", "750", "450", "0");

					var dataStr = {
						'chart' : {
							'caption' : 'population per state',
							'xAxisName' : 'states',
							'yAxisName' : 'population',
							'numberPrefix' : ''
						},
						'data' : [ ]
					};

					$.each(data, function(key, value) {
						//alert(value.population + "" + value.stateName);
						var dataObject = {
								label:'',
								value:''
							}
						dataObject.label = value.stateName;
						dataObject.value = value.population;
						dataObjectArray.push(dataObject);
					});
					
					dataStr.data = dataObjectArray;
					myPieChart.setJSONData(dataStr);
					myPieChart.render("piechartContainer");

					myBarChart.setJSONData(dataStr);
					myBarChart.render("barchartContainer");

					myLineChart.setJSONData(dataStr);
					myLineChart.render("linechartContainer");

					myPyramidChart.setJSONData(dataStr);
					myPyramidChart.render("pyramidchartContainer");

				},
				error : function(data) {

				}
			});
		});

once done please run the poject and in browser it shows as below. report of same data with four different charts.
FusionChartsReport

Happy Coding:)

Spring Integration with JPA/Hibernate using maven – I

Hi all here is my post regarding integration of some of the best frameworks available in the market, Spring+JPA/Hibernate.
Springโ€™s Basic concept: Inversion of Control

The basic concept of spring is the Inversion of Control pattern (dependency injection). In Spring, programmers donโ€™t need to create user objects but they need to describe how they should be created (in applicationContext.xml or using annotations). Programmers need not directly connect components and services together in code but describe which services are needed by which components in a configuration file or using annotations. The spring container is responsible for all this. Spring creates all the objects, connects them together by setting the necessary properties, and determines when methods will be invoked.
So using Spring framework the integration between technologies become loosely coupled.

Requirements:
Spring 3.1
JPA2.x/Hibernate 3.x
Eclipse 4.2 with Maven
Mysql Database

The major parts of the Credentials application explained below are:

The Entity classes
The DAO class which will contain common db operation code and functions
The service class โ€“ which is the actual business class.. This will contain actual business logic in it. In our example, we save Credentials bean information using this class.
Explained in the next tutorial
The client โ€“ The client can be a jsp / jsf web components or it can be a simple java program, which gets the service bean from spring and calls business method.
The springโ€™s applicationContext.xml descriptor which specifies what are the objects to be created when starting the application and where they should be injected.

Letโ€™s go through the tutorial step by step.You can download the full project code at the end of the tutorial:
i explain how to Retrieve and Insert and leave Delete and Update to be coded yourself(for fun).

Step1:create a maven project in eclipse.
step2:update the pom.xml file as shown 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</groupId>
	<artifactId>SpringIntegration</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>SpringIntegration</name>
	<description>SpringIntegration</description>

	<properties>
		<org.slf4j-version>1.6.1</org.slf4j-version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.18</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</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-core</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-crypto</artifactId>
			<version>3.1.0.RELEASE</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.10</version>
		</dependency>


		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Hibernate Validator -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.2.0.CR1</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>3.4.0.GA</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>tomcat-maven-plugin</artifactId>
				<version>1.0-beta-1</version>
			</plugin>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>7.4.0.v20110414</version>
				<configuration></configuration>
			</plugin>
		</plugins>
		<pluginManagement>
			<plugins>
				<!--This plugin's configuration is used to store Eclipse m2e settings 
					only. It has no influence on the Maven build itself. -->
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>
											org.apache.maven.plugins
										</groupId>
										<artifactId>
											maven-compiler-plugin
										</artifactId>
										<versionRange>
											[2.3.2,)
										</versionRange>
										<goals>
											<goal>compile</goal>
											<goal>testCompile</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore></ignore>
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
	<!-- needed for XmlSchema -->
	<repositories>
		<repository>
			<id>ibiblio</id>
			<name>ibiblio maven repository</name>
			<url>http://ibiblio.org/maven/</url>
			<layout>legacy</layout>
		</repository>
		<repository>
			<id>apache</id>
			<name>Apache maven repository</name>
			<url>http://www.apache.org/dist/java-repository/</url>
			<layout>legacy</layout>
		</repository>
	</repositories>

</project>

Step3:put web.xml in src/main/webapp/WEB-INF/ as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- Defines all the spring context information for all servlets and Filters 
		that share the info -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:application-context.xml</param-value>
	</context-param>

	<!-- creates spring container listener shared by all servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- request processing servlet -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-context.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/spring/*</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>pages/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

put all the configuration files in the src/main/resources folder of your maven project.

Step4: lets code our first configuration file “application-context.xml” as shown below.

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
			http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- component scan for @component,@Repositry,@Service -->
	<context:component-scan base-package="com.spark" />
	
	<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/test" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<!-- JPA EntityManagerFactory -->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
		p:dataSource-ref="dataSource">
		<property name="persistenceUnitName" value="MyPersistenceUnit"/> 
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="database" value="MYSQL" />
				<property name="showSql" value="true" />
			</bean>
		</property>
	</bean>

	<!-- Transaction manager for a single JPA EntityManagerFactory (alternative 
		to JTA) -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
		p:entityManagerFactory-ref="entityManagerFactory" />

	<!-- Activates various annotations to be detected in bean classes for eg 
		@Autowired -->
	<context:annotation-config />

	<!-- enable the configuration of transactional behavior based on annotations -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

	<!-- Property Configurator -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties" />
	</bean>

</beans>

Step5:lets code our second configuration file “spring-context.xml” which internally imports one more configuration file “controllers.xml”, this spring-context.xml file goes as a parameter for DispatcherServlet class of Spring framework.

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

	<!-- Enables the Spring MVC @Controller programming Model -->
	<annotation-driven />

	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/" />
		<beans:property name="suffix" value=".html" />
	</beans:bean>

	<!-- Imports user-defined @Controller beans that process client requests -->
	<beans:import resource="controllers.xml" />

</beans:beans>

Step6: controllers.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd	
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- Activates various annotations to be detected in bean classes -->	
	<context:annotation-config />
	<context:spring-configured />
	<!-- enable the configuration of transactional behavior based on annotations -->
	<tx:annotation-driven/>

	<!-- Scans within the base package of the application for @Components to configure as beans -->
	<context:component-scan base-package="com.spark" />
	
	
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="10000000" />
	</bean>
	
	
</beans>

Step7: Lets put the log4j.properties


log4j.rootCategory=debug, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=C://templog/clinicComponet.log
log4j.appender.logfile.MaxFileSize=1MB

# Keep three backup files
log4j.appender.logfile.MaxBackupIndex=3
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout

#Pattern to output : date priority [category] - <message>line_separator
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - <%m>%n

So now we have finished coding our configuration just start with our logic
create the followiing packages in src/main/java folder of maven project as follows.

com.spark.controller
com.spark.dao
com.spark.service
com.spark.model

Lets start coding Java now. first step is coding our model class(POJO) as below.

/**
 * 
 */
package com.spark.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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 * @author Sony
 * 
 */

@Entity
@Table(name = "credentials")
@NamedQueries({
@NamedQuery(name="Credentials.getAllRecords",
    query="SELECT o FROM Credentials o")          
})
public class Credentials implements Serializable{

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "ID")
	private int id;

	@Column(name = "username")
	private String username;

	@Column(name = "password")
	private String password;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

once our pojo is ready lets decide the business logic that is our service class. we will code an interface and its implementation class as follows

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

import java.util.List;

import com.spark.model.Credentials;

/**
 * @author Sony
 *
 */
public interface CredentialsService {

    void save(Credentials credentials);
    Credentials findById(Long id);       
    List<Credentials> findAll();   
}

and following is the implementation class

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

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.spark.dao.CredentialsDao;
import com.spark.dao.CredentialsDaoImpl;
import com.spark.model.Credentials;

/**
 * @author Sony
 *
 */
@Service("credentialService")
public class CredentialsServiceImpl implements CredentialsService {

	@Autowired
	CredentialsDao credentialsDao;
	
	public CredentialsDao getCredentialsDao() {
		return credentialsDao;
	}

	public void setCredentialsDao(CredentialsDao credentialsDao) {
		this.credentialsDao = credentialsDao;
	}

	/* (non-Javadoc)
	 * @see com.spark.service.CredentialsService#save(com.spark.model.Credentials)
	 */
	@Override
	public void save(Credentials credentials) {
		// TODO Auto-generated method stub
		credentialsDao.save(credentials);

	}

	/* (non-Javadoc)
	 * @see com.spark.service.CredentialsService#findById(java.lang.Long)
	 */
	@Override
	public Credentials findById(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see com.spark.service.CredentialsService#findAll()
	 */
	@Override
	public List<Credentials> findAll() {
		// TODO Auto-generated method stub
		return credentialsDao.findAll();
	}

}

Now its time to code our core database logic. The database logic is handled by JPA EntityManager, the object is injected into the EntityManager using the @PersistenceContext annotation its the responsibility of the Spring container to inject the EntityManager Implementation object after it scans the annotation. We will code the dao layer same as we did with service layer with an interface and its implementation class. please note that the dao is annotated as @Transactional that means the database operations will be executed under a transactional context
when spring scans the annotation.

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

import java.util.List;

import com.spark.model.Credentials;

/**
 * @author Sony
 *
 */
public interface CredentialsDao {

    public List<Credentials> findAll();
    public void save(Credentials credentials);
    public Credentials findById(int id);

}

following is the implementation class for the interface.

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

import java.util.List;

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

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.spark.model.Credentials;

/**
 * @author Sony
 *
 */
@Transactional
@Component
public class CredentialsDaoImpl implements CredentialsDao {
	
	@PersistenceContext
	private EntityManager entityManager;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	/* (non-Javadoc)
	 * @see com.spark.dao.CredentialsDao#findAll()
	 */
	@Override
	public List<Credentials> findAll() {
		// TODO Auto-generated method stub
		List<Credentials> credentials = null;
		try {
			credentials = entityManager.createNamedQuery("Credentials.getAllRecords").getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return credentials;
	}

	/* (non-Javadoc)
	 * @see com.spark.dao.CredentialsDao#save(com.spark.model.Credentials)
	 */
	@Override
	public void save(Credentials credentials) {
		// TODO Auto-generated method stub
		try {
			
			entityManager.persist(credentials);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/* (non-Javadoc)
	 * @see com.spark.dao.CredentialsDao#findById(int)
	 */
	@Override
	public Credentials findById(int id) {
		// TODO Auto-generated method stub
		return null;
	}

}

Now its time to code controller which is responsible for deligating the requests to service layer and there to dao layer. In the retrieve method the response returned from the method will be a JSON String

/**
 * 
 */
package com.spark.controller;

import java.util.List;

import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

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.model.Credentials;
import com.spark.service.CredentialsService;

/**
 * @author Sony
 *
 */
@Controller
public class SpringController {

	@Autowired(required=true)
	CredentialsService credentialsService;
	
	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public @ResponseBody String handleInsertRequest(@Valid String username,@Valid String password){
		
		String returnStatus = "Details Saved Successfully";
				
		Credentials credentials = new Credentials();
		credentials.setUsername(username);
		credentials.setPassword(password);
		
		credentialsService.save(credentials);
		
		return returnStatus;
	}
	
	@RequestMapping(value="/retrieve",method=RequestMethod.POST)
	public @ResponseBody String handleRetrieveRequest(){
				
		List<Credentials> credentials = credentialsService.findAll();
		
		JSONObject responseDetailsJson = new JSONObject();
	    JSONArray jsonArray = new JSONArray();

	    for (int i = 0; i < credentials.size(); i++)
	    {
	      JSONObject formDetailsJson = new JSONObject();
	      formDetailsJson.put("username", credentials.get(i).getUsername());
	      formDetailsJson.put("password", credentials.get(i).getPassword());

	      jsonArray.add(formDetailsJson);
	    }
	    responseDetailsJson.put("credentials", jsonArray);
	    
	    return responseDetailsJson.toString();
		
	}
}

I will post the the UI related stuff(JSP) in the next tutorial to call the controller.

Happy Coding ๐Ÿ™‚

Android Rest Client to call Spring MVC Project โ€“ Part 2

Hi all in the previous post i have shown you how to create a mavenized Spring MVC Project with full configuration in that the Spring controller is returning a JSON String, now this is the string we want to collect in android client by calling it using Spring-Rest-Template.

The Jar files required for this application are
android-support-v4.jar
spring-android-auth-1.0.0.RELEASE.jar
spring-android-core-1.0.0.RELEASE.jar
spring-android-rest-template-1.0.0.RELEASE.jar

For JSON Support add the following jar files
jackson-core-asl-1.9.11.jar
jackson-mapper-asl-1.9.11.jar

commons-httpclient-3.1.jar is used to HttpHeader Support.

package com.example.springandroid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;

public class MainActivity extends ListActivity {

	private static String[] content = { "JavaSE", "JavaEE", "JavaME" };

	public static final int ADD_MENU = Menu.FIRST + 1;
	public static final int REFRESH_MENU = Menu.FIRST + 2;
	public static final int EDIT_MENU = Menu.FIRST + 3;
	public static final int REMOVE_MENU = Menu.FIRST + 4;

	private ArrayList<String> arrayList = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getUpdates.start();

		registerForContextMenu(getListView());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(Menu.NONE, ADD_MENU, Menu.NONE, "Add Content");
		menu.add(Menu.NONE, REFRESH_MENU, Menu.NONE, "Refresh Content");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(Menu.NONE, EDIT_MENU, Menu.NONE, "Edit Content");
		menu.add(Menu.NONE, REMOVE_MENU, Menu.NONE, "Remove Content");
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ADD_MENU:
			addContent();
			return true;

		case REFRESH_MENU:
			initAdapter();
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();

		@SuppressWarnings("rawtypes")
		ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
		switch (item.getItemId()) {
		case EDIT_MENU:
			final String item1 = arrayList.get(info.position);
			// item1 = item1.toUpperCase();
			final View addView = getLayoutInflater().inflate(
					R.layout.activity_main, null);
			final EditText name = (EditText) addView.findViewById(R.id.title);
			new AlertDialog.Builder(this)
					.setTitle("Add Content")
					.setView(addView)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								@SuppressWarnings("unchecked")
								public void onClick(DialogInterface dialog,
										int whichButton) {
									@SuppressWarnings("rawtypes")
									ArrayAdapter adapter = (ArrayAdapter) getListAdapter();

									name.setText(item1);
									adapter.insert(name.getText().toString(),
											info.position);
								}
							}).setNegativeButton("Discard", null).show();
			adapter.remove(arrayList.get(info.position));

			return (true);
		case REMOVE_MENU:
			adapter.remove(arrayList.get(info.position));
			return (true);
		}
		return super.onContextItemSelected(item);
	}

	private Thread getUpdates = new Thread() {
		public void run() {

			String url = "http://10.40.230.54:8080/AndroidSpring/spring/retrieve";

			HttpHeaders requestHeaders = new HttpHeaders();
			requestHeaders.setContentType(new MediaType("text", "xml"));

			HttpEntity<String> requestEntity = new HttpEntity<String>(
					requestHeaders);

			RestTemplate restTemplate = new RestTemplate();
			restTemplate.getMessageConverters().add(
					new StringHttpMessageConverter());
			ResponseEntity<String> responseEntity = restTemplate.exchange(url,
					HttpMethod.POST, requestEntity, String.class);
			final String result = responseEntity.getBody();
			Log.d("Message", result); // prints the response collected from the server

			
			try {
				
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						JSONObject jsonObject;
						try {
							jsonObject = new JSONObject(result);
							Log.d("JSON is", ""+jsonObject.toString());
							
							initAdapter();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						
					}
				});

				
			} catch (Exception e) {
			}
		}
	};

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void initAdapter() {
		arrayList = new ArrayList<String>();
		Log.d("String Array Length:", "" + content.length);
		for (String contents : content) {
			arrayList.add(contents);
		}
		setListAdapter(new ArrayAdapter(this,
				android.R.layout.simple_list_item_1, arrayList));
	}

	private void addContent() {
		final View addView = getLayoutInflater().inflate(
				R.layout.activity_main, null);
		new AlertDialog.Builder(this).setTitle("Add Content").setView(addView)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@SuppressWarnings({ "rawtypes", "unchecked" })
					public void onClick(DialogInterface dialog, int whichButton) {
						ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
						EditText name = (EditText) addView
								.findViewById(R.id.title);
						adapter.add(name.getText().toString());
						
					}
				}).setNegativeButton("Discard", null).show();
	}
	
	
}

if you want to send parameters to Spring app. Please code the controller relavently i am giving the android call to Spring controller

private Thread addToDataBase = new Thread(){
		public void run(){
			String url = "http://10.40.230.54:8080/AndroidSpring/spring/insert?username={username}&password={password}";

			HttpHeaders requestHeaders = new HttpHeaders();
			requestHeaders.setContentType(new MediaType("text", "xml"));

			HttpEntity<String> requestEntity = new HttpEntity<String>(
					requestHeaders);

			RestTemplate restTemplate = new RestTemplate();
			restTemplate.getMessageConverters().add(
					new StringHttpMessageConverter());
			/*ResponseEntity<String> responseEntity = restTemplate.exchange(url,
					HttpMethod.POST, requestEntity, String.class);*/
			Map<String, Object> uriVariables = new HashMap<String, Object>();
		    uriVariables.put("username", "Administrator");
		    uriVariables.put("password", "Administrator123");

		    ResponseEntity<String> responseEntity = restTemplate.exchange(url,
					HttpMethod.POST, requestEntity, String.class,uriVariables);
			Log.d("Message", responseEntity.getBody());
		}
	};

Happy Coding ๐Ÿ™‚

Android Rest Client to call Spring MVC Project – Part 1

Hi All, This time i had very tough time to show my proof of concept to one of my colleague regarding java Spring mvc and Android. the requirement is quite direct we have to create a Spring MVC project and deploy it to server and call the spring controller using Android Activity. Thanks to spring it has released Spring-rest-template api using which we can call the business logic that is deployed in the server as spring controller. so here is my example code to you how to call spring mvc using Android Rest Client

in this part i will be explaining u how to create a spring mvc project using maven dependencies.

Note: dont code network related logic in the main thread of android activity it will lead to android.os.NetworkOnMainThreadException

Create a mavenized Spring Project as below:
Step1: POM.xml

<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.android.spring</groupId>
	<artifactId>AndroidSpring</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>AndroidSpring</name>
	<description>AndroidSpring</description>

	<properties>
		<org.slf4j-version>1.6.1</org.slf4j-version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.18</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</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-core</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-crypto</artifactId>
			<version>3.1.0.RELEASE</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.10</version>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Hibernate Validator -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.2.0.CR1</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>3.4.0.GA</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>tomcat-maven-plugin</artifactId>
				<version>1.0-beta-1</version>
			</plugin>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>7.4.0.v20110414</version>
				<configuration></configuration>
			</plugin>
		</plugins>
		<pluginManagement>
			<plugins>
				<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>
											org.apache.maven.plugins
										</groupId>
										<artifactId>
											maven-compiler-plugin
										</artifactId>
										<versionRange>
											[2.3.2,)
										</versionRange>
										<goals>
											<goal>compile</goal>
											<goal>testCompile</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore></ignore>
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
	<!-- needed for XmlSchema -->
	<repositories>
		<repository>
			<id>ibiblio</id>
			<name>ibiblio maven repository</name>
			<url>http://ibiblio.org/maven/</url>
			<layout>legacy</layout>
		</repository>
		<repository>
			<id>apache</id>
			<name>Apache maven repository</name>
			<url>http://www.apache.org/dist/java-repository/</url>
			<layout>legacy</layout>
		</repository>
	</repositories>

</project>

Step2:Place all configuration files in src/main/resources of ur maven project
code for application-context.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
			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
			http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
			http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

	<!-- component scan for detecting @controller annotations -->
	<context:component-scan base-package="com.spark.android"></context:component-scan>
	
	<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
	<task:executor id="myExecutor" pool-size="5"/>
	<task:scheduler id="myScheduler" pool-size="10"/>
	
	<tx:annotation-driven/>
	
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="MyPersistenceUnit" />
		<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/android" />
		<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>

code for controllers.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd	
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- Activates various annotations to be detected in bean classes -->	
	<context:annotation-config></context:annotation-config>

	<!-- Scans within the base package of the application for @Components to configure as beans -->
	<context:component-scan base-package="com.spark.android" />
	
	
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="10000000" />
	</bean>
	
	
</beans>

code for spring-context.xml

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

	<!-- Enables the Spring MVC @Controller programming Model -->
	<annotation-driven />

	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/" />
		<beans:property name="suffix" value=".html" />
	</beans:bean>

	<!-- Imports user-defined @Controller beans that process client requests -->
	<beans:import resource="controllers.xml" />

</beans:beans>

For database interaction i decided to make use of JPA over Hibernate, so create a folder META-INF(All caps) in your src/main/resources/ and pleace persistence.xml file in it with the following code.

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="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
	<class>com.spark.android.model.Credentials</class>
	</persistence-unit>
	
</persistence>

now that we have completed our configuration its time for us to write the model classes and business logic for handling requests from android client and return responce. Here we use JSON for communication layer. notice that you put the code in appropriate packages.
source code for controller

/**
 * 
 */
package com.spark.android.controller;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spark.android.model.Credentials;

/**
 * @author Mantha Pavan Kumar
 *
 */
@Controller
public class AndroidSpringController {

	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public @ResponseBody String handleInsertRequest(){
		
		Credentials credentials = new Credentials();
		credentials.setUsername("PavanKumar");
		credentials.setPassword("pavan~123!");
		
		JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( credentials );  
		
		return jsonObject.toString();
	}
}

and following is the model class(POJO)

/**
 * 
 */
package com.spark.android.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 Mantha Pavan Kumar
 *
 */
@Entity
@Table(name="contacts")
public class Credentials implements Serializable{

	private int id;
	private String username;
	private String password;
	
	/**
	 * @return
	 */
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public int getId() {
		return id;
	}
	/**
	 * @param id
	 */
	public void setId(int id) {
		this.id = id;
	}
	/**
	 * @return
	 */
	@Column(name="username")
	public String getUsername() {
		return username;
	}
	/**
	 * @param username
	 */
	public void setUsername(String username) {
		this.username = username;
	}
	/**
	 * @return
	 */
	@Column(name="password")
	public String getPassword() {
		return password;
	}
	/**
	 * @param password
	 */
	public void setPassword(String password) {
		this.password = password;
	}
}

once this is ready now lets start coding your web.xml file as our project is a web application. create a folder WEB-INF(all caps) in src/main/webapps/

code for web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- Defines all the spring context information for all servlets and Filters 
		that share the info -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:application-context.xml</param-value>
	</context-param>

	<!-- creates spring container listener shared by all servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- request processing servlet -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-context.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/spring/*</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>pages/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

now its time to test the application open cmd and navigate to the project folder and issue “mvn clean install package”
without quotes it will download all jar files needed by your application and it builds the war file(bueauty of maven)
now your project is ready for deployment issue the command “mvn tomcat:run” without quotes your tomcats starts and your war will be deployed now your Spring MVC project is up and running lets see how to code Android REST client and communicate with Spring Web App in Part-II.

Happy Coding ๐Ÿ™‚