jqGrid + Servlet

Hello all, one of my fiend has a requirement to generate a data grid model so, we thought directly using jqGrid component here is my tutorial which will populate data in grid format.
Step 1: jqGrid will call servlet using an Ajax call.
Step 2: Servlet returns data in the form of JSON.
Step 3: jqGrid Component will parse JSON data from servlet and render it in the component.
Step 4: giving additional functionality as “add,edit,delete” directly to jqGrid component.
prj_structure

lets start looking at the logic
GridServlet.java

package com.spark.javaee.servlets;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

/**
 * Servlet implementation class LoginServlet
 */
public class GridServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		GridModel gridModel1 = new GridModel();
		gridModel1.setId(1);
		gridModel1.setFirstName("PavanKumar");
		gridModel1.setLastName("Mantha");
		gridModel1.setCity("Hyderabad");
		gridModel1.setState("AndhraPradesh");
		gridModel1.setPhoneNumber("1234567890");
		
		GridModel gridModel2 = new GridModel();
		gridModel2.setId(2);
		gridModel2.setFirstName("PavanKumar");
		gridModel2.setLastName("Mantha");
		gridModel2.setCity("Hyderabad");
		gridModel2.setState("AndhraPradesh");
		gridModel2.setPhoneNumber("1234567890");
		
		List<GridModel> gridModels = new ArrayList<>();
		gridModels.add(gridModel1);
		gridModels.add(gridModel2);
		
		JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(gridModels);
		String json = "{'page':1,'total':'2','records':'1','rows':"+jsonArray+"}";
		JSONObject jsonObject = (JSONObject)JSONSerializer.toJSON(json);
		
		PrintWriter out = response.getWriter();
		out.print(jsonObject.toString());
	}

}

Lets look at the model class
GridModel.java

/**
 * 
 */
package com.spark.javaee.servlets;

import java.io.Serializable;

/**
 * @author Sony
 * 
 */
public class GridModel implements Serializable {

	private int id;
	private String firstName;
	private String lastName;
	private String city;
	private String State;
	private String phoneNumber;

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

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

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

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

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

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

	/**
	 * @return the city
	 */
	public String getCity() {
		return city;
	}

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

	/**
	 * @return the state
	 */
	public String getState() {
		return State;
	}

	/**
	 * @param state
	 *            the state to set
	 */
	public void setState(String state) {
		State = state;
	}

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

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

}

now its time to look at jsp

<%@page import="java.util.Date"%>
<%@ 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>jqGird Demo</title>
<link rel="stylesheet"
	href="assets/themes/redmond/jquery.ui.all.css">

<script src="assets/js/jquery-1.8.0.min.js"></script>
<script src="assets/ui/jquery.ui.core.js"></script>
<script src="assets/ui/jquery.ui.widget.js"></script>
<script src="assets/ui/jquery.ui.datepicker.js"></script>
<script src="assets/js/grid.locale-en.js"></script>
<script src="assets/js/jquery.jqGrid.src.js"></script>
<script src="assets/js/jquery-ui-1.8.23.custom.min.js"></script>
<script src="assets/js/json2.js"></script>


<link rel="stylesheet" href="assets/demos.css">
<link rel="stylesheet" href="assets/ui.jqgrid.css">
<script src="js/getGridData.js"></script>
</head>
<body>
	<table id="list">
		<tr>
			<td />
		</tr>
	</table>
	<div id="pager"></div>
</body>
</html>

lets look at the javascript

/**
 * Code for JQuery Grid.
 */
$(document)
		.ready(
				function() {
					$("#list")
							.jqGrid(
									{
										url : 'http://localhost:8080/JQueryTest/GridServlet',
										datatype : 'json',
										mtype : 'POST',
										colNames : [ 'id', 'firstName',
												'lastName', 'city', 'state',
												'phoneNumber' ],
										colModel : [ {
											name : 'id',
											index : 'id',
											width : 100
										}, {
											name : 'firstName',
											index : 'firstName',
											width : 150,
											editable : true
										}, {
											name : 'lastName',
											index : 'lastName',
											width : 150,
											editable : true
										}, {
											name : 'city',
											index : 'city',
											width : 80,
											editable : true
										}, {
											name : 'state',
											index : 'state',
											width : 100,
											editable : true
										}, {
											name : 'phoneNumber',
											index : 'phoneNumber',
											width : 80,
											editable : true
										} ],
										pager : '#pager',
										rowNum : 10,
										rowList : [ 10, 20, 30 ],
										sortname : 'invid',
										sortorder : 'desc',
										viewrecords : true,
										gridview : true,
										caption : 'Data Report',
										jsonReader : {
											repeatitems : false,
										},
										editurl : "http://localhost:8080/JQueryTest/GridServlet"
									});
					jQuery("#list").jqGrid('navGrid', '#pager', {
						edit : true,
						add : true,
						del : true,
						search : true
					});
				});


This is how the result looks by loading data
load

This is how the result looks after clicking add button and the request:
request

This is how the result looks after clicking edit button and the request:
edit

Happy Coding 🙂

JSON in JavaEE 7

Hello guys..During week end i was doing lot of research on new technologies and newly released JavaEE 7 API. I found a very good enhancement in the API, i.e “JSON”. In modern day Programming when compared to lagecy apps the communication is completely depending on JSON data rather XML format, because of JSON’s readability and Object oriented nature. JSR-353 has bought a new feature in JavaEE 7, they included JSON API in JavaEE 7. Previous to JavaEE 7 most of us are relying on third party libs to form JSON structure now its all JavaEE 7 responsibility. I researched few things in the JSON(JavaEE 7) and here are my findings.

Note:Please add the following Maven dependency in you pom.xml file to get the JSON support from JavaEE 7

<dependencies>
	<dependency>
		<groupId>org.glassfish</groupId>
		<artifactId>javax.json</artifactId>
		<version>1.0.1</version>
	</dependency>
</dependencies>

JSON: is a text-based data exchange format derived from JavaScript that is used in web services and other connected applications.
The following example shows JSON data for a sample object that contains name-value pairs. The value for the name “phoneNumbers” is an array whose elements are two objects.

{
   "firstName": "PavanKumar",
   "lastName": "Mantha",
   "age": 27,
   "streetAddress": "100 JavaEE RandD",
   "city": "Hyderabad",
   "state": "AP",
   "postalCode": "12345",
   "phoneNumbers": [
      { "Mobile": "111-111-1111" },
      { "Home": "222-222-2222" }
   ]
}

JSON has the following syntax:

Objects are enclosed in braces {}, their name-value pairs are separated by a comma (,) and the name and value in a pair are separated by a colon (:). Names in an object are strings, whereas values may be of any of the six data types, including another object or an array.

Arrays are enclosed in brackets [], and their values are separated by a coma (,). Each value in an array may be of a different type, including another array or an object.

When objects and arrays contain other objects or arrays, the data has a tree-like structure.

Use of JSON:

JSON is commonly used to serialize and de-serialize object data and communicate over internet between two or more applications running in different environments, these application an be programmed in different languages but JSON can be a common platform to communicate. To my understanding this is the modern approach in compatible with legacy communication over XML.

Generating and Parsing JSON Data With Example
Note: please read JSR-353 support for JSON in JavaEE 7 oracle documentation for more details and API Spec.

Create JSONObject by reading Json data:

import java.io.FileReader;
import javax.json.Json;
import javax.json.JsonReader;
import javax.json.JsonStructure;
...
JsonReader reader = Json.createReader(new FileReader("jsondata.txt"));
JsonStructure jsonst = reader.read();

Creating JSON Object from Application:

JsonObjectBuilder jsonObjectBuilder = (JsonObjectBuilder) Json
				.createObjectBuilder();
		JsonObject jsonObject = jsonObjectBuilder
				.add("firstName", "PavanKumar")
				.add("lastName", "Mantha")
				.add("age", 27)
				.add("streetAddress", "100 JavaEE RandD")
				.add("city", "Hyderabad")
				.add("state", "AP")
				.add("postalCode", "12345")
				.add("phoneNumbers",
						Json.createArrayBuilder()
								.add(Json.createObjectBuilder()
										.add("type", "mobile")
										.add("number", "111-111-1111"))
								.add(Json.createObjectBuilder()
										.add("type", "home")
										.add("number", "222-222-2222")))
				.build();

Traversing a JSON Object:

public static void navigateTree(JsonValue tree, String key) {
		if (key != null)
			System.out.print("Key " + key + ": ");
		switch (tree.getValueType()) {
		case OBJECT:
			System.out.println("OBJECT");
			JsonObject object = (JsonObject) tree;
			for (String name : object.keySet())
				navigateTree(object.get(name), name);
			break;
		case ARRAY:
			System.out.println("ARRAY");
			JsonArray array = (JsonArray) tree;
			for (JsonValue val : array)
				navigateTree(val, null);
			break;
		case STRING:
			JsonString st = (JsonString) tree;
			System.out.println("STRING " + st.getString());
			break;
		case NUMBER:
			JsonNumber num = (JsonNumber) tree;
			System.out.println("NUMBER " + num.toString());
			break;
		case TRUE:
		case FALSE:
		case NULL:
			System.out.println(tree.getValueType().toString());
			break;
		}

	}

How to write JSON Object to Stream?

try {
			StringWriter stringWriter = new StringWriter();
			JsonWriter jsonWriter = Json.createWriter(stringWriter);
			jsonWriter.writeObject(jsonObject);
			jsonWriter.close();

			FileWriter fileWriter = new FileWriter(new File("D:\\jsonDate.txt"));
			fileWriter.write(stringWriter.toString());
			fileWriter.close();

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

Parsing Json Object Data:

JsonParser jsonParser = Json.createParser(new StringReader(
				jsonModelString.toString()));
		while (jsonParser.hasNext()) {
			JsonParser.Event event = jsonParser.next();
			if (event == event.KEY_NAME) {
				System.out.print(event.toString() + " "
						+ jsonParser.getString() + " - ");
			} else if (event == event.VALUE_NUMBER) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			} else if (event == event.VALUE_STRING) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			}
		}

Now the following is the complete picture of the above concepts

/**
 * 
 */
package com.spark.javaee;

import java.io.File;
import java.io.FileWriter;
import java.io.StringReader;
import java.io.StringWriter;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonString;
import javax.json.JsonValue;
import javax.json.JsonWriter;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonParser;

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

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

		JsonJavaeeApiDemo javaeeApiDemo = new JsonJavaeeApiDemo();
		JsonObject jsonObject = javaeeApiDemo.createJsonObject();
		javaeeApiDemo.createJsonDataFile(jsonObject);
		javaeeApiDemo.iterateObjectModel(jsonObject.toString());
		System.out.println("===============================================");
		javaeeApiDemo.generateJsonData(jsonObject);
		JsonJavaeeApiDemo.navigateTree(jsonObject, jsonObject.toString());
	}

	public void iterateObjectModel(String jsonModelString) {
		JsonParser jsonParser = Json.createParser(new StringReader(
				jsonModelString.toString()));
		while (jsonParser.hasNext()) {
			JsonParser.Event event = jsonParser.next();
			if (event == event.KEY_NAME) {
				System.out.print(event.toString() + " "
						+ jsonParser.getString() + " - ");
			} else if (event == event.VALUE_NUMBER) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			} else if (event == event.VALUE_STRING) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			}
		}
	}

	public JsonObject createJsonObject() {

		JsonObjectBuilder jsonObjectBuilder = (JsonObjectBuilder) Json
				.createObjectBuilder();
		JsonObject jsonObject = jsonObjectBuilder
				.add("firstName", "PavanKumar")
				.add("lastName", "Mantha")
				.add("age", 27)
				.add("streetAddress", "100 JavaEE RandD")
				.add("city", "Hyderabad")
				.add("state", "AP")
				.add("postalCode", "12345")
				.add("phoneNumbers",
						Json.createArrayBuilder()
								.add(Json.createObjectBuilder()
										.add("type", "mobile")
										.add("number", "111-111-1111"))
								.add(Json.createObjectBuilder()
										.add("type", "home")
										.add("number", "222-222-2222")))
				.build();
		return jsonObject;
	}

	public static void navigateTree(JsonValue tree, String key) {
		if (key != null)
			System.out.print("Key " + key + ": ");
		switch (tree.getValueType()) {
		case OBJECT:
			System.out.println("OBJECT");
			JsonObject object = (JsonObject) tree;
			for (String name : object.keySet())
				navigateTree(object.get(name), name);
			break;
		case ARRAY:
			System.out.println("ARRAY");
			JsonArray array = (JsonArray) tree;
			for (JsonValue val : array)
				navigateTree(val, null);
			break;
		case STRING:
			JsonString st = (JsonString) tree;
			System.out.println("STRING " + st.getString());
			break;
		case NUMBER:
			JsonNumber num = (JsonNumber) tree;
			System.out.println("NUMBER " + num.toString());
			break;
		case TRUE:
		case FALSE:
		case NULL:
			System.out.println(tree.getValueType().toString());
			break;
		}

	}

	public void createJsonDataFile(JsonObject jsonObject) {
		try {
			StringWriter stringWriter = new StringWriter();
			JsonWriter jsonWriter = Json.createWriter(stringWriter);
			jsonWriter.writeObject(jsonObject);
			jsonWriter.close();

			FileWriter fileWriter = new FileWriter(new File("D:\\jsonDate.txt"));
			fileWriter.write(stringWriter.toString());
			fileWriter.close();

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

	}

	public void generateJsonData(JsonObject jsonObject) {
		try {
			FileWriter writer = new FileWriter("D:\\test.txt");
			JsonGenerator gen = Json.createGenerator(writer);
			gen.writeStartObject().write("firstName", "PavanKumar")
					.write("lastName", "Mantha").write("age", 27)
					.write("streetAddress", "100 javaEE RandD")
					.write("city", "JavaCity").write("state", "AP")
					.write("postalCode", "12345")
					.writeStartArray("phoneNumbers").writeStartObject()
					.write("type", "mobile").write("number", "111-111-1111")
					.writeEnd().writeStartObject().write("type", "home")
					.write("number", "222-222-2222").writeEnd().writeEnd()
					.writeEnd();
			gen.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

Happy Coding with JSON 🙂

courtesy: Oracle docs
ref:http://docs.oracle.com/javaee/7/tutorial/doc/jsonp.htm#GLRBB

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 🙂