Thursday 23 August 2012

WebService using RESTeasy

Webservice using RESTeasy is too simple. For creating the simple application we have to use the maven plugin or you can download the jar file and keep it inside the lib folder of the project.

First create a Dynamic Web Project and give any name you would like and then convert the project to a maven project and add the below dependency to the pom.xml.

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>RestEasy</groupId>
<artifactId>RestEasy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>RestEasy</name>
<description>RestEasy</description>
<dependencies>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.2.1.GA</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

Once you have done that then we need to create a class file with the name RestEasyTest.java. In this class file, @Path you need to specify for which this class need to be called as a mapping. then you need to create a method name showMessage and mention for what kind of call this method should respond. In the below example we are using the @Get. Now we need the parameter passed from the url to use in the method so we are using the {param} which will take the rest of the url after the "/test" and store it inside the string msg. Once this method is called we are returning the object of the Response.


RestEasyTest.java

package com.lnt.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/test")
public class RestEasyExample {

@GET
@Path("/{param}")
public Response showMessage(@PathParam("param") String msg) {

String result = "Restful example : " + msg;

return Response.status(200).entity(result).build();

}

}


Configuration of the project to use the resteasy servlets are done at the web.xml



web.xml



<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>RestEasy</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<!-- Auto scan REST service -->
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>

<!-- this need same with resteasy servlet url-pattern -->
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>

<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>

<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>


The listener org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap make sure that the REST services are registed and listened.

we are also providing the  esteasy.servlet.mapping.prefix as "/rest" as the resteasy url pattern uses the /rest/*.


Now start the server and hit the link as

"http://localhost:8080/RestEasy/rest/test/hello%20prajith"

Result would be : Restful example : hello prajith

Thursday 12 July 2012

Reflections in Java

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

There are three steps that must be followed to use these classes.

1. Obtain a java.lang.Class object for the class that you want to manipulate.
2. Call method defined in the java.lang.Class to get the information about the class you want to manipulate.
3. Use the reflection API to manipulate the information

Example of Reflection feature.

Reflection :


package com.lnt.scjp;

import java.lang.reflect.*;

public class Reflection {
private int f1(Object p, int x) throws NullPointerException {
if (p == null)
throw new NullPointerException();
return x;
}

public static void main(String args[]) {
try {
Class cls = Class.forName("com.lnt.scjp.Reflection");

Method methlist[] = cls.getDeclaredMethods();
for (int i = 0; i < methlist.length; i++) {
Method m = methlist[i];
System.out.println("name = " + m.getName());
System.out.println("decl class = " + m.getDeclaringClass());
Class pvec[] = m.getParameterTypes();
for (int j = 0; j < pvec.length; j++)
System.out.println("param #" + j + " " + pvec[j]);
Class evec[] = m.getExceptionTypes();
for (int j = 0; j < evec.length; j++)
System.out.println("exc #" + j + " " + evec[j]);
System.out.println("return type = " + m.getReturnType());
System.out.println("-----");
}
} catch (Throwable e) {
System.err.println(e);
}
}
}


Output:

name = main
decl class = class com.lnt.scjp.Reflection
param #0 class [Ljava.lang.String;
return type = void
-----
name = f1
decl class = class com.lnt.scjp.Reflection
param #0 class java.lang.Object
param #1 int
exc #0 class java.lang.NullPointerException
return type = int
-----

In the above class we are printing the information of the same class using the Reflection feature of the java. In the above class we have only used the Method class under the java.lang.reflect package. There are other class which the same package provide for modifications. Which can be seen in the below link.


Friday 15 June 2012

Getting Spring WebApplicationContext object in Spring non managed bean

In spring non managed bean its difficult to initialize the object using the spring framework. For this either you can use

ApplicationContext context = new ClassPathXmlApplicationContext("springapp-servlet.xml");

but using the above code loads the springapp-servlet.xml once again in the memory. In case of standalone application the above code will be fine but in case its a application running on server, loading the xml again will be costlier.So for getting the Spring WebApplicationContext object you can do as code marked in colored background. 


package com.lntinfotech.office.common;


import java.util.ArrayList;
import java.util.List;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.lntinfotech.office.dao.DAOImpl;
import com.lntinfotech.office.dao.DAOIntf;
import com.lntinfotech.office.domain.JiraTicket;

public class DWRImpl {
private Logger logger = LoggerFactory.getLogger(getClass());

public List<JiraTicket> jiraTicketDetails(String jiraTicket,
HttpServletRequest req, HttpServletResponse res) {
logger.debug("--> jiraTicketDetails(String name)  " + jiraTicket);
List<JiraTicket> list = new ArrayList<JiraTicket>();
try {
WebApplicationContext applicationContext = WebApplicationContextUtils
.getRequiredWebApplicationContext(req.getSession()
.getServletContext());

logger.debug("--> applicationContext   " + applicationContext);

DAOIntf daoIntf = (DAOImpl) applicationContext.getBean("daoIntf");
                        /* the above code gets the DAOImpl object via Spring IOC
                        * and its initializes all the other objects mapped in the spring                              WebApplicationContext
                        * removed unwanted code from the method......
                        */
} catch (Exception e) {
logger.error("Error   : ", e);
return null;
}
logger.debug("<-- jiraTicketDetails(String name)");
return list;
}

}

Custom Converter in Struts 2.3 and utilizing using annotations


In Struts we can write our own custom converter by extending to the StrutsTypeConverter and overriding the methods of the parent class. In the below example i have converted the string value received from the jsp to a Role object using the Struts annotation and the custom converter. I have not kept the Role class over here as you can convert this string to any object as per your requirement. Please don't forget to create a constructor in the POJO class as per the requirement other wise this converter wont work.

I have not overridden the convertToString method of the StrutsTypeConverter. This only because I am not using this conversion. It depends on the developer to override the methods according to the application need.


package com.lntinfotech.office.common;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lntinfotech.office.domain.Role;
import com.opensymphony.xwork2.conversion.TypeConversionException;

public class RoleConverter extends StrutsTypeConverter {
private Logger logger=LoggerFactory.getLogger(getClass());
@Override
public Role convertFromString(Map context, String[] values, Class toClass){
logger.debug("--> convertFromString String :"+values[0]);
Role role;
if (values != null && values.length > 0 && values[0] != null
&& values[0].length() > 0) {
try {
int id=Integer.valueOf(values[0]);
role=new Role(id);

} catch (Exception e) {
throw new TypeConversionException(e);
}
logger.debug("<-- convertFromString String :"+values[0]);
return role;
}
logger.debug("<-- convertFromString null");
return null;
}

@Override
public String convertToString(Map arg0, Object arg1) {
logger.debug("--> convertToString(Map arg0, Object arg1)");
// TODO Auto-generated method stub
return null;
}

}

In the above class we have created the a converter. So to use this we can use the Struts annotation. In the action class where you need this conversion to happen just annotate as 
@TypeConversion and give the complete path of the converter. I have removed other variables and method as its not necessary for this example. At run time when we are getting the dynamic value from the frontend the below code will call the converter and convert the value to the Role object and process the form as per the code. 

package com.lntinfotech.office.controller;

public class RegistrationAction extends ActionSupport {
private static final long serialVersionUID = 1L;

private Logger logger = LoggerFactory.getLogger(getClass());
        private Role role;

        public Role getRole() {
return role;
}

@TypeConversion(converter = "com.lntinfotech.office.common.RoleConverter")
public void setRole(Role role) {
this.role = role;
}

        @Action(value = "/createuser", results = {
@Result(location = "registrationSuccess.jsp", name = "success"),
@Result(location = "registration.jsp", name = "input"),
@Result(location = "registration.jsp", name = "error") }, className = "registerUser")
public String createUser() {
logger.debug("--> createUser()");
        //method code removed.
        return "success";
}

}

Casting list of array of objects and utilizing the same in jsp


In the below code the DAO class returns a list of objects. Now we need to iterate it and get the values of all the classes separately.
In the debug mode the list of array of object will look like as below.



Now to iterate this kind of list you need to first iterate as usual list and then cast it to Object array. Once its casted then we can get individual POJO classes. Only we need is to cast as per the sequence of the  POJO class. Please find the below code.

List mainMenu = daoIntf.getMenu();
logger.debug("List size "+mainMenu.size());
logger.debug("lsit  : "+mainMenu.get(0));
Iterator itr=mainMenu.iterator();
while(itr.hasNext()){
Object[] str=(Object[])itr.next();
logger.debug("str.length :"+str.length);
//menu=(Menu)str[0];
subMenuRole=(SubMenuRole)str[0];
subMenu=(SubMenu)str[1];
logger.debug("Menu Name :  " +subMenu.getMenu().getName()+ "  SubMenu :  "+subMenu.getName()+" Role : "+subMenuRole.getRole().getName());
}

We are setting the list in the session as we have got from the DAO class. In this list there are 2 POJO classes so we need to iterate and show it in the front end. 

menu.jsp

In the below jsp, please note the <s:iterator> tag is iterating the list which we have set in the session and we have given the list name during iteration is "usermenu". Once we have iterated the list then you can point to the pojo class by using the list name "usermenu[i]" where i is the sequence of pojo class which we have used to iterate the list in the java coding above. 

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
</head>

<body>
<div class="arrowlistmenu">
<s:iterator value="%{#session.mainMenuList}" var="usermenu"
status="user">
<s:if test="#user.first  == true">
<c:set var="menuElement" scope="page">
<s:property value="#usermenu[0].name" />
</c:set>
<h3 class="menuheader expandable">${menuElement}</h3>
<ul class="categoryitems">
</s:if>
<c:set var="currentMenuElement" scope="page">
<s:property value="#usermenu[0].name" />
</c:set>

<c:choose>
<c:when test="${currentMenuElement==menuElement}">
<li>
<a href="<%=request.getContextPath() %>/<s:property value="#usermenu[2].link" />.html"><s:property value="#usermenu[2].name" /></a>
</li>

</c:when>
<c:otherwise>
</ul>
<c:set var="menuElement" scope="page">
<s:property value="#usermenu[0].name" />
</c:set>
<h3 class="menuheader expandable">${menuElement}</h3>
<ul class="categoryitems">
<c:if test="${currentMenuElement==menuElement}">
<li>
<a href="<%=request.getContextPath() %>/<s:property value="#usermenu[2].link" />.html"><s:property value="#usermenu[2].name" /></a>
</li>
</c:if>
</c:otherwise>
</c:choose>
<s:if test="#user.last  == true">
</ul>
</s:if>
</s:iterator>
</div>
</body>
</html>


Hope this code helps some of the developers.