JQGrid to display Apache Solr Data

Hi all, from past couple of weeks i was doing a POC on Solr in my project and there came a scenario where i need to pull the data from Solr server and display on JQGrid component. In this post let me show you how to do this task. The project structure looks as below.

jqgrid_project

let’s start with our index.html file as below.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Solr Data Drid</title>
<link href="css/jquery-ui-custom.css" media="screen" type="text/css" rel="stylesheet">
<link href="css/ui.jqgrid.css" media="screen" type="text/css" rel="stylesheet">
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="js/grid.locale-en.js"></script>
<script type="text/javascript" src="js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="custom_js/app.js"></script>
</head>
<body>
<table id="list2"></table>
<div id="pager2"></div>
</body>
</html>

Now comes the time for coding the app.js file where the actual logic reside. follow the comments carefully and the script is easy to understand.

/**
 * @author Pavan Kumar Mantha
 */

$(document)
		.ready(
				function() {
					var dataTable = $("#list2");
					var entityArray = [];

					dataTable.jqGrid({
						datatype : "local",
						colNames : [ 'id', 'lastName', 'firstName',
								'titleOfCourtesy' ],
						colModel : [ {
							name : 'id',
							index : 'id',
							width : 55
						}, {
							name : 'lastName',
							index : 'lastName',
							width : 90
						}, {
							name : 'firstName',
							index : 'firstName',
							width : 100
						}, {
							name : 'titleOfCourtesy',
							index : 'titleOfCourtesy',
							width : 80,
							align : "right"
						} ],
						rowNum : 10,
						rowList : [ 10, 20, 30 ],
						pager : '#pager2',
						sortname : 'id',
						viewrecords : true,
						sortorder : "desc",
						autowidth : true,
						caption : "Solr Data"
					});

					// handles the grid resize on window resize
					$(window).resize(
							function() {
								dataTable.jqGrid('setGridWidth', parseInt($(
										window).width()) - 20);
							});

					// Firing Ajax request to Solr server and getting data to
					// populate the jqgrid.
					// This ajax request is powered by cross domain
					$.ajaxSetup({
						crossDomain : true,
						scriptCharset : "utf-8",
						contentType : "jsonp; charset=utf-8"
					});

					var request = $
							.ajax({
								url : "http://localhost:8983/solr/collection1/select?q=*%3A*&wt=json&json.wrf=?&indent=true&rows=100",
								mthod : "GET",
								dataType : "jsonp"
							});

					request.done(function(data) {

						$.each(data.response.docs, function(i, doc) {
							var entityobject = {
								id : "",
								lastName : "",
								firstName : "",
								titleOfCourtesy : ""
							}

							entityobject.id = doc.id;
							entityobject.lastName = doc.lastName;
							entityobject.firstName = doc.firstName;
							entityobject.titleOfCourtesy = doc.titleOfCourtesy;

							entityArray.push(entityobject);
						});

						for (var i = 0; i <= entityArray.length; i++)
							jQuery("#list2").jqGrid('addRowData', i + 1,
									entityArray[i]);
					});

					request
							.fail(function(msg) {
								alert("Fetching of data from solr failed with error !");
							});
				});// end of (document).ready(function(){});


That is it, finally when we deploy this project to server and see the output it should look as below.
jqgrid_op

In my next post will be posting about the integration of SpringData and Apache Solr until then.
Happy coding jqgrid 🙂

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 🙂