Monday, 16 March 2015

Spring Restful WebService with JSON

Hi Guys,

In this post we are going to see how to create a spring rest web-service with JSON as request and response. I have seen most of the guys are struggling with JSON as request and response in spring applications.

Lets see how to implement spring rest service with JSON using simple employee details processing.

Step 1: Create Java Maven Web application. Add the below dependencies in to your pom.xml

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
     
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>3.2.2.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <!-- Other community dependencies -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
     
        <dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>

 <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.3</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.3</version>
            <scope>provided</scope>
        </dependency>


Step 2: Create Employee bean for our request and response processing.


 @JsonIgnoreProperties(ignoreUnknown = true)
 public class Employee {

private Integer id;

private String name;

private String address;

private Integer salary;

      //getter's and setter's

 }

Step 3: Create our Employee Interface for request mapping and response processing using JSON.


@RequestMapping(value = "/employee")
 public interface IEmployee {

 @RequestMapping(value = "/createEmployee", method = RequestMethod.POST,  produces="application/json", consumes="application/json")
 public @ResponseBody Employee createEmployee(@RequestBody Employee emp);

 @RequestMapping(value = "/getAllEmployees", method = RequestMethod.POST,  produces="application/json", consumes="application/json")
    public @ResponseBody String getAllEmployees();

 @RequestMapping(value = "/getEmployee/{id}", method = RequestMethod.POST,    produces="application/json", consumes="application/json")
 public @ResponseBody Employee getEmployee(@PathVariable("id") int empId);

}


Here I am using @RequestMapping for mapping for services with spring application, My method is always POST method. My services will produce and consume JSON data so we need to use our media type as application/json. 

@RequestBoby will map my request JSON data with my Employee Bean.
@PathVariable("id") will map my employee id with my Employee bean
@ResponseBoby will return convert my response in to JSON object.

I am having 3 services in my employee application
1. /createEmployee - For creating Employee details.
2. /getAllEmployees - For getting list of all employees.
3. /getEmployee/{id} - For getting a particular employee by id.

So my services look like this.
http://localhost:8080/springrestservice/employee/createEmployee , In the same way u can call getAllEmployees and getEmployee/1. Here springrestservice is my project name.

Step 4: Create our Employee Controller


import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

@Controller
public class EmployeeController implements IEmployee {

Map<Integer, Employee> empData = new HashMap<Integer, Employee>();
ObjectMapper objectMapper = new ObjectMapper();

  public Employee createEmployee(@RequestBody Employee emp) {
        empData.put(emp.getId(), emp);
        return emp;

}

public String getAllEmployees() {

String allEmployees;
try {
allEmployees = objectMapper.writeValueAsString(empData);
} catch (Exception e) {

return "Exception Occured";
}

return allEmployees;
}

public Employee getEmployee(@PathVariable("id") int empId) {

return empData.get(empId);
}

}


In My controller i have a HashMap which used to store all employee details and later we can able to fetch the details based on the request. ObjectMapper is a Jackson class which used to write my data back to JSON while sending response.

Step 5: web.xml and dispatcher servlet.xml


web.xml

<web-app version="3.0"
         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_3_0.xsd"
         metadata-complete="true">
  <display-name>Archetype Created Web Application</display-name>

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

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
 
  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>

</web-app>

dispatcher-servlet.xml

Just add the below lines to your servlet.xml

        <context:component-scan base-package="in.springrestservice"/>

<mvc:annotation-driven />


Note: If your deploying your application in Jboss Server add the jackson dependencies in your jboss-deployment-structure.xml. When server started all these dependencies will add to class loading.


<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
   <deployment>
      <dependencies>
      <module name="org.codehaus.jackson.jackson-core-asl"/>
      <module name="org.codehaus.jackson.jackson-mapper-asl"/>
                        <module name="org.slf4j"/>
      </dependencies>
   </deployment>
</jboss-deployment-structure>


Project Structure:


Let's test our application with the above services. Use Mozilla Rest Client or Chrome Client.

1. CreateEmployee
Insert employees as much as you can. You will get the response as a JSON data with inserted employee details.




2. GetALLEmployees
Get all employees from our Map we stored in the previous call. We will get all the employees we inserted in to our Map.


3. GetEmployeeById
Get a particular employee from the Map using employee Id.


That's all Folks.. Hope you all got idea on Spring rest service with JSON.



Friday, 20 February 2015

JqGrid and Spring 3 MVC Integration With MongoDB

Hi Guys,
In this tutorial we will build a Spring 3 MVC Application which uses MongoDB in the back-end for retrieving and updating  the jqGrid data from presentation layer.

What is jqGrid?

jqGrid is an Ajax-enabled JavaScript control that provides solutions for representing and manipulating tabular data on the web. Since the grid is a client-side solution loading data dynamically through Ajax callbacks, it can be integrated with any server-side technology, including PHP, ASP, Java Servlets, JSP, ColdFusion, and Perl.

jqGrid uses a jQuery Java Script Library and is written as plugin for that package.

Source: http://www.trirand.com/jqgridwiki/doku.php

Here's a screenshot of what we will be doing:


Our application is a simple system for managing a list of users. The presentation layer uses a jqGrid to display the data which is built on top of the JQuery, a great JavaScript framework. The business layer is composed of simple Spring beans annotated with @Controller and @Service. We are using MongoDB for storing our user information, which in-turn used by Spring for retrieving  and updating the data from jqGrid.

Let's start by defining our domain User for MongoDB to map our bean with database.

User.Java

package in.grid.dao;

/**
 * A simple POJO to represent our user domain for MongoDB connection  
 *
 */

import java.util.Date;

import org.springframework.data.annotation.Id;

import org.springframework.data.mongodb.core.index.Indexed;

import org.springframework.data.mongodb.core.mapping.Document;



@Document(collection = "users")

public class User {


@Id

private String id;
@Indexed
private String ic;
private String name;
private int age;
private Date createdDate;

public User(String ic, String name, int age, Date createdDate)
{
this.ic = ic;
this.name = name;
this.age = age;
this.createdDate = createdDate;
}

  /**
   * Getters and Setters
   *
  */
}


Now we define our RequestDao Domain which used to Map JSON data from presentation layer to Business Layer.

RequestDao .java

package in.grid.dao;

import java.util.Date;

public class RequestDao {

private String id;

private String ic;

private String name;

private int age;

private Date createdDate;

        /**
      * Getters and Setters 
     */
}

Let's move on to the controllers. 
GridController.java

Notice our controllers are simple classes annotated with @Controller and @RequestMapping. Same with the @Service annotation, this class becomes a Spring Controller that's capable to handle URI-template-based requests.

package in.grid.controller;

import in.grid.dao.RequestDao;
import in.grid.dao.User;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
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.ResponseBody;

@Controller
public class GridController {

@Autowired
MongoOperations mongoOperations;

@RequestMapping(value = "/getGridData",method=RequestMethod.GET)      
    public @ResponseBody String getAll(HttpServletRequest request){
String result = null;
System.out.println("Fetching Data From DB");

try
{
List<User> users = mongoOperations.findAll(User.class);

ObjectMapper mapper = new ObjectMapper();
result = mapper.writeValueAsString(users);

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


System.out.println("Data: "+result);

        return result;
    }

@RequestMapping(value = "/saveGridData",method=RequestMethod.POST)      
    public @ResponseBody String saveData(@RequestBody RequestDao requestDao,     HttpServletRequest request){

String id = requestDao.getId();
System.out.println("Saving data to db");

try
{
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
User user = mongoOperations.findOne(query, User.class);
user.setAge(requestDao.getAge());
user.setCreatedDate(requestDao.getCreatedDate());
user.setIc(requestDao.getIc());
user.setName(requestDao.getName());
mongoOperations.save(user);

List<User> users = mongoOperations.findAll(User.class);
System.out.println(users);


}catch(Exception e)
{
e.printStackTrace();
return "Some Thing Happened Please try after some time!!!";
}

return "Data Stord Successfully!!!";  
    }

}


The GridController has twomappings: 
/spring/getGridData -- reterive data from MongoDb
/spring/saveData -- Save data to MongoDB after editing form jqGrid

Let's move on to the presentation layer. 
index.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>JQGrid Example</title>
<link href="<c:url value="/resources/css/jquery-ui.css" />" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" type="text/css" href="<c:url value="/resources/css/ui.jqgrid.css" />"/>
  <script src="<c:url value="/resources/js/jquery-1.9.1.js" />"></script>
  <script src="<c:url value="/resources/js/jquery-ui.min.js"/>"></script>
  <script src="<c:url value="/resources/js/grid.locale-en.js"/>"></script>
    <script src="<c:url value="/resources/js/jquery.jqGrid.min.js"/>"></script>
    <script src="<c:url value="/resources/js/grid.js"/>"></script>
</head>
<body>
<div id="griddiv" align="center">
<table id="rowed5" align="center"></table>
 <div id="pager"></div> <br>
 <input type="button" id="upload-trigger" Value="Save Data">
 </div>
</body>
</html>

Note: Do not ignore DOCTYPE in your jsp!!!. In jqGrid the pager will become very large.

I created a custom js file called grid.js for defining all my javascript code.

$(function() {
$('#upload-trigger').prop('disabled', true);

  $("#rowed5").jqGrid({      
    url : "spring/getGridData",
    datatype : "json",
    mtype: "GET",
    colNames:['Id','Ic', 'Name', 'Age','CreatedDate'],
    colModel:[
        {name:'id',index:'id', width:250, sorttype: "int", editable:false,editoptions:{readonly:true,size:10}},
        {name:'ic',index:'ic', width:90,editable:true,editoptions:{size:25}},
        {name:'name',index:'name', width:200, editable:true,editoptions:{size:10}},
        {name:'age',index:'age', width:60,align:"right",editable:true,editoptions:{size:10}},
        {name:'createdDate',index:'createdDate',width:200, editable: true}
    ],
    onSelectRow: function(id){
    $('#upload-trigger').prop('disabled', false);
    },
    rowNum:5,
    rowList:[5,10,15],
    pager:'#pager',
    rownumbers:true,
    autoencode: true,
    sortname: 'id',
    viewrecords: true,
    sortorder: "asc",
    caption:"JQGrid Example",
    height:"auto",
    loadonce: true,
    editurl: 'clientArray',
    jsonReader : {
    root: "d.rows",
        page: "d.page",
        total: "d.total",
        records: "d.records",
        repeatitems: false
    }

  }).jqGrid('navGrid', '#pager', { edit: true, add: false, del: true, search: true }, {closeAfterEdit: true}, {closeAfterAdd:true}, {}, {closeAfterSearch: true});

  $("#upload-trigger").click(function() {
console.log("Inside save");
   var selRowId = $("#rowed5").jqGrid ('getGridParam', 'selrow');
   var rowObject = $('#rowed5').getRowData(selRowId);
   console.log(JSON.stringify(rowObject));
   $.ajax({
   type: 'POST',
   contentType : 'application/json; charset=utf-8',
   url: 'spring/saveGridData',
   data: JSON.stringify(rowObject),
   success: function (response) {
    alert(response);
   
   },
   error:function(request, textStatus, errorThrown) {
       alert(errorThrown);
   }
});
 
});

});


Another important setting you must look at is the jsonReader we declared inside the jqGrid: jsonReader : { root: "d.rows", page: "d.page", total: "d.total", records: "d.records", repeatitems: false } The names in colmodel must exactly match the properties you're passing in your JSON data. It's case sensitive! FIRSTNAME and firstName are not the same names!
Let's return to Spring. Typical with any Spring application, we must declare a few required beans in the xml configuration. dispatcher-servlet.xml web.xml
web.xml
<web-app version="3.0"
         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_3_0.xsd"
         metadata-complete="true">
  <display-name>Archetype Created Web Application</display-name>

  <welcome-file-list>
        <welcome-file>/WEB-INF/views/index.jsp</welcome-file>
</welcome-file-list>

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

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/spring/*</url-pattern>
    </servlet-mapping>
 
  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>
</web-app>
dispatcher-servlet.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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:mongo="http://www.springframework.org/schema/data/mongo" 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/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.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd"> <context:component-scan base-package="in.grid"/> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewRes olver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- Connection to MongoDB server --> <mongo:db-factory id="mongoDbFactory" host="localhost" port="27017" dbname="gridpoc"/> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> </bean> </beans>
Note: I created this application on Maven dependency, we need to add all our dependencies to pom.xml.
Hope you guys got good idea on Jqgrid With Spring MVC using MongoDb..
That's all Folks...