Monday 17 August 2015

How to add Oracle JDBC Driver in Your Maven local repository

In this post i am going to show you how to install ojdbc.jar under maven local repository.

Due to Oracle license restriction, there is NO public Maven repository provides Oracle JDBC driver. To use Oracle jdbc drive with Maven, you have to install it manually into your Maven local repository.

Step 1: How to get ojdbc.jar?

  • Download ojdbc.jar from oracle website or any other websites.
  • Or you can use the ojdbc.jar from your oracle database installed directory.
Step 2: Install ojdbc.jar in Maven local Repository.

    mvn install:install-file -Dfile={Path/to/your/ojdbc.jar} -DgroupId=com.oracle 
   -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar


So, For me the directory is D:\ojdbc6-11.2.0.3.jar. So the maven install look like
mvn install:install-file -Dfile=D:\ojdbc6-11.2.0.3.jar -DgroupId=com.oracle 
-DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar

Once Your build success check the ojdbc.jar under your maven local repository.

Step 3: pom.xml

<project ...>
 <dependencies>>
  <!-- ORACLE database driver -->
  <dependency>
   <groupId>com.oracle</groupId>
   <artifactId>ojdbc6</artifactId>
   <version>11.2.0.3</version>
  </dependency>
 </dependencies>
</project>

That's all Folks..

Monday 4 May 2015

The service did not start due to a logon failure

Hi Guys,

In this post i am going to write some thing related to windows Services. In windows some services related with our system username and password and that service's do start based on the  credentials provided for e.g Oracle database services. So before the service get start's it will check for username and password that we initially used to install the services(software).

After some period of time if we changed the password it wont get update to the services which are using the system credentials. So lets see how to resolve this issue in windows.

The service did not start due to a logon failure - Windows Service error.

Step 1:

Go to ControlPanel --> Administrative Tools --> View local services


Step 2:

Select the service you need to update with current credentials and select properties. Go to Log On Tab shown in-below screen shot. Update the password which currently used as system password. click on apply and then ok. 



We are done.. Now go to task manager select the service you want to start.

That's All Folks..

Hope you guys got idea on how to solve the above window service issue.


Monday 23 March 2015

Spring CXF Rest Webservices Using JSON with Exception Handling

Spring CXF Rest Webservices Using JSON with Exception Handling

This is a simple tutorial on how to create a simple JAX-RS Web Service in Java using Spring and Apache CXF. This service will be follow the request/response pattern, it will using HTTP POSTs which are formatted JSON requests and it will produce JSON responses.

This will run on JBoss-Application Server v6.2. This will show you how to create a JAX-RS Web Service for managing User objects, you can fetch, insert, update and delete them. It will use an in-memory store to keep it simple.

Step 1: Create a new Maven web application project in java using eclipse. Add the below dependencies in your pom.xml.

<dependencies>
      <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-bundle</artifactId>
    <version>2.7.6</version>
    <exclusions>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-asm</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-jaxws_2.2_spec</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-continuation</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-http</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-io</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-util</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-security</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>2.7.6</version>
</dependency>

<dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.11</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.11</version>
        </dependency>
     
        <dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.11</version>
</dependency>
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>
     
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>

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

In the above pom.xml i am excluding some of the dependencies from cxf-bundle for the better performance of our project.

Step 2: Create our User Model for mapping our JSON request with our Application.

package in.springrestcxf.user;

public class User {

private Integer id;
private String name;
private String email;
private String city;
private String state;
     
       //getters and setters for above attributes.
}

Step 3: Create our Response Model for sending back the response to client in JSON format.

package in.springrestcxf.response;

import java.util.List;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import in.springrestcxf.user.User;

public class Response {

private String message;

         //Use JsonSerialize for excluding non null and empty values in JSON response
@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
private User user;

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
private List<User> users;

private boolean success;
     
        //getters and setters
}

Step 4: Create our User Interface Which used to Map the rest request with our Application with JSON as Request and Response.

package in.springrestcxf.usermanager;

import in.springrestcxf.response.Response;
import in.springrestcxf.springexep.MyRestException;
import in.springrestcxf.user.User;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

public interface UserManager
{
@POST
@Path("/fetchUserById")
@Consumes({ MediaType.APPLICATION_JSON })
 @Produces({ MediaType.APPLICATION_JSON })
public Response fetchUserById(User request);

@POST
@Path("/fetchAllUsers")
@Consumes({ MediaType.APPLICATION_JSON })
 @Produces({ MediaType.APPLICATION_JSON })
public Response fetchAllUsers();

@POST
@Path("/insertUser")
@Consumes({ MediaType.APPLICATION_JSON })
 @Produces({ MediaType.APPLICATION_JSON })
public Response insertUser(User request);

@POST
@Path("/updateUser")
@Consumes({ MediaType.APPLICATION_JSON })
 @Produces({ MediaType.APPLICATION_JSON })
public Response updateUser(User request);

@POST
@Path("/deleteUser")
@Consumes({ MediaType.APPLICATION_JSON })
 @Produces({ MediaType.APPLICATION_JSON })
public Response deleteUser(User request);

public User getUser(User request) throws MyRestException;

public Response processErrorCodes(MyRestException e) throws MyRestException;

}


In our User Interface we have four different operations for our user. We are producing and consuming JSON as request and response using @Produces and @Consumes Annotations. @POST use to specify our request as POST method.

1. Insert User (For inserting users in to ArrayList).
2. Fetch All Users(Fetch All users from the ArrayList that we have saved in Insert User).
3. Fetch User By Id(Fetch the particular user based on the id passed with our request).
4. Update User(Update the particular user based on the id).
5. Delete User(Delete the user from Array-list based on the id passed).

Step 5: Create our Implementation of our User Interface for writing for operations.

package in.springrestcxf.managerimpl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import in.springrestcxf.response.Response;
import in.springrestcxf.springexep.MyRestException;
import in.springrestcxf.user.User;
import in.springrestcxf.usermanager.UserManager;

public class UserManagerImpl implements UserManager {

List<User> users = new ArrayList<User>();   //Put all the user request in list.
Response response = new Response();         //Send back the response.


public Response fetchUserById(User request) {

try
{
request = getUser(request);

if(request!=null)
{
response.setMessage("Your Employee Details");
response.setUser(request);
response.setUsers(null);
response.setSuccess(true);
return response;
}

response.setMessage("Employee Not Found");
response.setUser(null);
response.setUsers(null);
response.setSuccess(false);

}
catch(MyRestException springCxfException)
{
try {
processErrorCodes(springCxfException);
} catch (MyRestException e) {
e.printStackTrace();
}
}
return response;
}

public Response fetchAllUsers(){
try
{
response.setMessage("Employee Details");
response.setUser(null);
response.setUsers(users);
response.setSuccess(true);
}catch(Exception exception)
{
response.setMessage(exception.getLocalizedMessage());
response.setSuccess(false);
response.setUser(null);
response.setUsers(null);
}
return response;
}

public Response insertUser(User request){

try
{
users.add(request);
response.setMessage("Employee Inserted Successfully");
response.setUser(request);
response.setUsers(null);
response.setSuccess(true);
}
catch(Exception exception)
{
response.setMessage(exception.getLocalizedMessage());
response.setSuccess(false);
response.setUser(null);
response.setUsers(null);
}
return response;
}

public Response updateUser(User request) {

try
{
User user = getUser(request);

if(user!=null)
{
user.setCity(request.getCity());
user.setEmail(request.getEmail());
user.setName(request.getName());
user.setState(request.getState());

response.setMessage("Employee Updated Successfully");
response.setUser(user);
response.setUsers(null);
response.setSuccess(true);
return response;
}

response.setMessage("Employee Not Found");
response.setUser(null);
response.setUsers(null);
response.setSuccess(false);
}catch(MyRestException springCxfException)
{
try {
processErrorCodes(springCxfException);
} catch (MyRestException e) {
e.printStackTrace();
}
}

return response;
}

public Response deleteUser(User request) {

try
{
Iterator<User> it = users.iterator();
while (it.hasNext()) {
User user = it.next();
if(user.getId()==request.getId())
{
it.remove(); //Delete the User object from list using iterator method.
response.setMessage("Employee Deleted Successfully");
response.setUser(null);
response.setUsers(null);
response.setSuccess(true);
return response;
}
}
response.setMessage("Employee Not Found");
response.setUser(null);
response.setUsers(null);
response.setSuccess(false);
}catch(Exception exception)
{
response.setMessage(exception.getLocalizedMessage());
response.setSuccess(false);
response.setUser(null);
response.setUsers(null);
}

return response;
}

/*Check whether the User is present id list or not*/
public User getUser(User request) throws MyRestException {

try
{

for(User user : users)
{
if(user.getId()==request.getId())
{
return user;
}
}
}catch(Exception e)
{
e.printStackTrace();
throw new MyRestException(e.getMessage(), "Exception");
}
return null;

}

public Response processErrorCodes(MyRestException e)
throws MyRestException {

if(e.getErrorCode().equals("Exception"))
{
e.printStackTrace();
response.setMessage(e.getLocalizedMessage());
response.setSuccess(false);
response.setUser(null);
response.setUsers(null);
}
else
{
e.printStackTrace();
response.setMessage(e.getLocalizedMessage());
response.setSuccess(false);
response.setUser(null);
response.setUsers(null);
}

return response;

}

}



In this class i wrote all my operations which implemented from my interface. I am using Array List for storing all the user details which get from our request and the list is used for further processing. I am having getUser() method for checking whether the user is present in list or not. This is common to all operations. I have my own Exception class which used to handle exceptions other than CXF exceptions and fault. If exception occurred i am calling processErrorCodes() method to return back the response with exception message and code. We will see how to handle CXF exceptions in our application in step 7.


Step 6: Create our own custom exception class which used to handle our exceptions in our application and we can process error-code and exception message and send it back to the client.

package in.springrestcxf.springexep;

import java.io.Serializable;

public class MyRestException extends Exception implements Serializable {

private static final long serialVersionUID = 1L;
private String errorCode="Unknown_Exception";
 
    public MyRestException(String message, String errorCode){
        super(message);
        this.errorCode=errorCode;
    }
   
    public String getErrorCode(){
        return this.errorCode;
    }

}

Step 7: Create our own Exception class which used to handle CXF Exception while processing request and response. If any exception occurs during request or response processing this class will send back the response with status and exception message to the client. We need to implement ExceptionMapper which used to handle the exceptions.
For e.g while sending the request user didn't set the content-type as application/json, So while processing the request our custom class will catch the exception and send back the same to client.
We need to define the exception class in our configuration file under <jaxrs:providers>, So CXF will automatically map our exception class with our application.

package in.springrestcxf.springexep;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
@Produces({ MediaType.APPLICATION_JSON })
public class ExceptionHandler implements ExceptionMapper<Exception> {

public Response toResponse(Exception exception) {
Response.Status status;

status = Response.Status.BAD_REQUEST;

        return Response.status(status).entity(exception.getLocalizedMessage()).build();

}

}


@Provider is to inform CXF that we have our own custom CXF exception class which used to handle all CXF exception in our application.
In the above exception class i implement ExceptionMapper with Exception class which used to handle all exceptions including RunTimeExceptions also. We can pass any kind of Exception inside ExceptionMapper based on our requirement.

Step 8: CXF configuration file(rest-content.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cxf="http://cxf.apache.org/core"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
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://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

  <context:component-scan base-package="in.springrestcxf"/>
 
<bean id="userManagerService"
class="in.springrestcxf.managerimpl.UserManagerImpl">
</bean>

<bean id="jsonProvider"
class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>

<bean id="exceptionHandler"
class="in.springrestcxf.springexep.ExceptionHandler" />

  <jaxrs:server id="userManagerREST" address="/user">
  <jaxrs:serviceBeans>
  <ref bean="userManagerService"/>
  </jaxrs:serviceBeans>
  <jaxrs:extensionMappings>
            <entry key="json" value="application/json"/>
        </jaxrs:extensionMappings>
  <jaxrs:providers>
<ref bean="jsonProvider" />
<ref bean="exceptionHandler" />
</jaxrs:providers>
  </jaxrs:server>

</beans>


In my configuration file i mapped my bean classes which used to configure with CXF for processing request, response and Exceptions. UserManagerImpl is my Service bean which used to map all the request and process response based on the data. I mapped my CXF exception handler class under <jaxrs:providers> in order to catch the exception and further send back the response to client. I am using the rest address as /user in order to map my request.

Step 9: 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>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
 
  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/rest-content.xml</param-value>
    </context-param>
 
</web-app>

So here i mapped my servlet as CXF servlet which will start while our application started. and i mapped the url pattern as /services/* which used to map my rest request.

Step 10:  JBoss deployment structure(If you are deploying your application under JBoss)

<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.codehaus.jackson.jackson-jaxrs"/>
         <module name="org.slf4j"/>
      </dependencies>
   </deployment>
</jboss-deployment-structure>

It will load all the jars at run time of application.

Note: Jboss 6 or latest version's have their own JAX-RS and CXF servlet, So when you are running your application some collision between jar files will happen and you will get No Such Method Error while processing CXF related Exception. For over come that download the latest version of JBOSS jar files and put it inside your  \jboss-eap 6.2\modules\system\layers\base folder. In my case i am using JBOSS 6.2 version which used to collide with my application jar files. So i downloaded the JBOSS rest easy jars of v3.0.9 and replace all the jars with my JBoss modules.

For more details refer http://stackoverflow.com/questions/24139097/resteasy-client-nosuchmethoderror

Step 11: Sample request and Response

1. http://localhost:8080/springrestcxf/services/user/insertUser
2. http://localhost:8080/springrestcxf/services/user/fetchAllUsers
3. http://localhost:8080/springrestcxf/services/user/fetchUserById
4. http://localhost:8080/springrestcxf/services/user/updateUser
5. http://localhost:8080/springrestcxf/services/user/deleteUser

Above is the URL which we are used to call rest service integrated with our appplication.

Insert User


Fetch All Users(Input - {} )

Fetch User by Id

Update User

Delete User


Fetch All users After Deleting particular user from list


 CXF Exception while sending JSON request and validating the request inside CXF



In the above Screen shot you can able to see the exception return by our ExceptionHandler class that we created to handle CXF Exception. In the above request i am not passing the JSON data in a correct format. I put multiple commas in between the key and values, So while processing the request CXF transport validate the request and throws the exception to our custom class from there i am returning the status and exception happened in CXF transport. In the same way we can able to handle any Exception that happens inside CXF transport or Interceptors.

That's all Folks..
Hope you guys got good idea on CXF rest service Using Spring with Exception Handling.


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...