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:)