Friday, 12 September 2014

Spring Transaction

Just Small project done for testing Spring Transaction. For future reference I am writing this Blog.

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>SpringSecurity</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
   <servlet-name>spring-security</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>spring-security</servlet-name>
   <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>
 
        <!-- Loads Spring Security config file -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   /WEB-INF/spring-security-servlet.xml
  </param-value>
 </context-param>
 
</web-app>



spring-security-servlet.xml

 

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:tx="http://www.springframework.org/schema/tx"
 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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
 
 <context:component-scan base-package="com.prajith.*" />
 
 <bean
   class="org.springframework.web.servlet.view.InternalResourceViewResolver">
   <property name="prefix">
  <value>/view/</value>
   </property>
   <property name="suffix">
  <value>.jsp</value>
   </property>
 </bean>
   
    <!-- Initialization for data source -->
   <bean id="dataSource" 
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://localhost:3306/maverick"/>
      <property name="username" value="root"/>
      <property name="password" value="*******"/>
   </bean>

   <!-- Initialization for TransactionManager -->
   <bean id="transactionManager" 
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource"  ref="dataSource" />    
   </bean>
 
  <!-- enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="transactionManager"/><!-- a PlatformTransactionManager is still required -->
</beans>

For making annotation driven need to add the code.
<tx:annotation-driven transaction-manager="transactionManager"/>

Transaction manager changes with the interacting platform.

Platform                     TransactionManager or PlatFormTransactionManager
 JDBC                         org.springframework.jdbc.datasource.DataSourceTransactionManager
 JTA                            org.springframework.transaction.jta.JtaTransactionManager 

 Hibernate                    org.springframework.orm.hibernate3.HibernateTransactionManager

 

Types of Probagation defined in the Spring Docs










MANDATORY :Support a current transaction, throw an exception if none exists.
NESTED :Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.
NEVER :Execute non-transactionally, throw an exception if a transaction exists.
NOT_SUPPORTED : Execute non-transactionally, suspend the current transaction if one exists.
REQUIRED : Support a current transaction, create a new one if none exists.
REQUIRES_NEW : Create a new transaction, suspend the current transaction if one exists.
SUPPORTS : Support a current transaction, execute non-transactionally if none exists. 

SpringTransactionTest.java 

package com.prajith.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.prajith.web.service.EmployeeServiceIntf;

@Controller
public class SpringTransactionTest {

 @Autowired
 EmployeeServiceIntf employeeServiceIntf;
 
 public void setEmployeeServiceIntf(EmployeeServiceIntf employeeServiceIntf) {
  this.employeeServiceIntf = employeeServiceIntf;
 }
 
 @RequestMapping(value="/sqltransactionTest")
 public ModelAndView testTransaction(){
  ModelAndView model= new ModelAndView("admin");
  try{
   employeeServiceIntf.testTransaction(); 
  }catch(Exception e){
   System.out.println(e);
  }
  return model;
 }
}



EmployeeServiceIntf.java


package com.prajith.web.service;

public interface EmployeeServiceIntf {
 public void testTransaction() throws Exception;
}
 

EmployeeServiceImpl.java
 

package com.prajith.web.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.prajith.web.dao.EmployeeDAOIntf;
import com.prajith.web.domain.Employee;
import com.prajith.web.domain.Salary;

@Service
public class EmployeeServiceImpl implements EmployeeServiceIntf {

 @Autowired
 private EmployeeDAOIntf employeeDAOIntf;
 
 public void setEmployeeDAOIntf(EmployeeDAOIntf employeeDAOIntf) {
  this.employeeDAOIntf = employeeDAOIntf;
 }

 @Transactional// autoscan makes this method transactional
 public void testTransaction() throws Exception {
  // TODO Auto-generated method stub
  
  Employee emp=new Employee();
  emp.setEmpName("prajith");
  
  Salary sal =new Salary();
  sal.setEmpNo(1);
  sal.setSalary(20000);
  employeeDAOIntf.insertEmp(emp);
  employeeDAOIntf.insertSalary(sal);
  
  Employee emp1=new Employee();
  emp1.setEmpName("pooja");
  
  Salary sal1 =new Salary();
  sal1.setEmpNo(3);//purposefully kept so that DB will throw error.
  sal1.setSalary(204440);
  employeeDAOIntf.insertEmp(emp1);
  employeeDAOIntf.insertSalary(sal1);
 }

}



EmployeeDAOIntf
 

package com.prajith.web.dao;

import com.prajith.web.domain.Employee;
import com.prajith.web.domain.Salary;

public interface EmployeeDAOIntf {
 public void insertEmp(Employee emp) throws Exception;
 public void insertSalary(Salary emp) throws Exception;
}


EmployeeDAOImpl


package com.prajith.web.dao;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.prajith.web.domain.Employee;
import com.prajith.web.domain.Salary;

@Repository
public class EmployeeDAOImpl implements EmployeeDAOIntf{

 String sql1 = "insert into Employee (empname) values (?)";
 String sql2 = "insert into Salary (empid, Salary) values (?, ?)";
 @Autowired
 private DataSource dataSource;
 
 public DataSource getDataSource() {
  return dataSource;
 }

 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }

 public void insertEmp(Employee emp) throws Exception {
  // TODO Auto-generated method stub
  System.out.println("Employee Insertion");
  JdbcTemplate jt=new JdbcTemplate(dataSource);
  jt.update(sql1,emp.getEmpName());
  System.out.println("--> Employee data inserted : " );
 }

 public void insertSalary(Salary sal) throws Exception {
  // TODO Auto-generated method stub
  System.out.println("Salary Insertion");
  JdbcTemplate jt=new JdbcTemplate(dataSource);
  jt.update(sql2,sal.getEmpNo(),sal.getSalary());
  System.out.println("salary inserted successfully : ");
 }

}

Sunday, 7 September 2014

Converting Java object into JavaScript object

Recently I had a requirement to change a java object into JavaScript object when the request is submitted and response is received. I dint want to make a ajax call because the data was available when I received the response but i was not able to get that in JavaScript object from the request. I did Google and found some of the possible solution as per the link. The below code from the site was workable but I had a complex object


<script>  
    var myMap = {  
      <c:forEach items="${theMap}" var="item" varStatus="loop">  
        ${item.key}: '${item.value}' ${not loop.last ? ',' : ''}  
      </c:forEach>  
    };  
</script>  
and it require many levels of iteration and the creation of the same object with the above logic was difficult and thus it was better to go for ajax than creating the JavaScript object from the request.

Then i realized the object we are trying to create using the above logic is exactly same as the json object then perhaps sending json string and trying to convert that will be much more easier than doing the above logic. It was much more easier than the above logic so am pasting my test project for any one who require such requirements in future.

Simple pojo trying to convert.
Employee.java


package springapp.domain;

public class Employee {

    private String name;
    private String age;
    private Address address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Employee [name=" + name + ", age=" + age + ", address="
                + address + "]";
    }
    
} 

Address.java


package springapp.domain;

public class Address {

    private String street;
    private String city;
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    @Override
    public String toString() {
        return "Address [street=" + street + ", city=" + city + "]";
    }
    
}
 



class converting List of employee to json object and setting into request scope

JspVariableTest.java


package springapp.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import junit.framework.Test;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import springapp.domain.Address;
import springapp.domain.Employee;


public class JspVariableTest implements Controller{

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        ModelAndView view=new ModelAndView("jspVariabletest");
        List<Employee> empList=new ArrayList<Employee>();
        
        Employee emp=new Employee();
        emp.setAge("27");
        emp.setName("prajith");
        Address add=new Address();
        add.setStreet("Testing");
        add.setCity("Mumbai");
        emp.setAddress(add);
        
        Employee emp2=new Employee();
        emp2.setAge("27");
        emp2.setName("pooja");
        Address add2=new Address();
        add2.setCity("chennai");
        add2.setStreet("2nd street");
        emp2.setAddress(add2);
        
        empList.add(emp);
        empList.add(emp2);
        
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("empList", empList);
        view.addObject("empMap",map);//adding the map object to the request 
        
        ObjectMapper mapper=new ObjectMapper();// jackson lib for converting to json
        String empMapString=mapper.writeValueAsString(map);// json string
        view.addObject("empMapString",empMapString);
        
        return view;
    }
}
 

  


Now simple jsp to convert java object to JavaScript. I have kept actual java Object and json Object to show the difference how it assigns to the JavaScript variable.

jspVariabletest.jsp


<%@ 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">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script>
var empMap="${empMap}";// acutal java object assigning to javascript variable 
var empObj=${empMapString};//actual jsonString assigning to javascript variable

</script>
<c:forEach items="${empMap}" var="entry">
    Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
</body>
</html> 








Now i have debugged the code in google chrome developer tool and attached the screen shot of the two objects we have created and assigned to JavaScript variable.

The java Map object we are getting in string  which i have assigned to empMap variable of javascipt and the json object we are getting as JavaScript object which I have assigned to empObj. Which is ready to use. If we apply the other logic i have got from the other site, it would have took long time to change this simple object to JavaScript object which is not feasible for changing complex object.


Thursday, 28 November 2013

HttpServletRequestWrapper class usage or Modify HttpServletRequest Object including header information

Recently i came across a requirement where for time being I need to send some information in header of HttpServletRequest object. Setting it in browser level was not a option as we cant setup the header information everytime and in every system.

So did browsing little bit and found a solution. Also came to know many people are looking for it so would like to share the code for doing a work around using HttpServletRequestWrapper.

In the below project, going to insert value in the HttpServletRequest object as parameter and later modifying the object in the java code to get the value using method getHeader() of HttpServletRequest object.

Project Name : EditHeaderVariable 

First create a dynamic web project with the name you would like to give and put necessary jar files. I have made it as spring mvc project using maven. Giving below the dependency requirements in pom.xml file.

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>EditHeaderVariable</groupId>  
  <artifactId>EditHeaderVariable</artifactId>  
  <version>0.0.1-SNAPSHOT</version>  
  <name>EditHeaderVariable</name>  
  <description>EditHeaderVariable</description>  
  <dependencies>  
       <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-core</artifactId>  
            <version>3.2.4.RELEASE</version>  
            <type>jar</type>  
            <scope>compile</scope>  
       </dependency>  
       <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-web</artifactId>  
            <version>3.2.4.RELEASE</version>  
            <type>jar</type>  
            <scope>compile</scope>  
       </dependency>  
       <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-webmvc</artifactId>  
            <version>3.2.4.RELEASE</version>  
            <type>jar</type>  
            <scope>compile</scope>  
       </dependency>  
  </dependencies>  
 </project>  

web.xml

Adding spring DispatcherServlet and other filter as required.

 <?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>EditHeaderVariable</display-name>  
  <welcome-file-list>  
   <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>  
  <servlet>  
   <servlet-name>editHeader</servlet-name>  
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!--  
   <init-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>  
   </init-param>  
   --><load-on-startup>1</load-on-startup>  
  </servlet>  
   <context-param>  
      <param-name>contextConfigLocation</param-name>  
      <param-value>/WEB-INF/editHeader-servlet.xml</param-value>  
  </context-param>  
  <servlet-mapping>  
   <servlet-name>editHeader</servlet-name>  
   <url-pattern>*.html</url-pattern>  
  </servlet-mapping>  
  <listener>  
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  </listener>  
  <filter>  
       <filter-name>modifyRequestObjectFilter</filter-name>  
       <filter-class>com.prajith.filter.ModifyRequestObjectFilter</filter-class>  
  </filter>  
  <filter-mapping>  
       <filter-name>modifyRequestObjectFilter</filter-name>  
       <url-pattern>/*</url-pattern>  
  </filter-mapping>  
 </web-app>  

editHeader-servlet.xml

enabling autoscan feature of the spring.

 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xmlns:context="http://www.springframework.org/schema/context"  
      xsi:schemaLocation="http://www.springframework.org/schema/beans   
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
      http://www.springframework.org/schema/context  
      http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
      <context:component-scan base-package="com.prajith" />  
      <bean id="viewResolver"  
           class="org.springframework.web.servlet.view.InternalResourceViewResolver" >  
       <property name="prefix">  
        <value>jsp/</value>  
       </property>  
       <property name="suffix">  
        <value>.jsp</value>  
       </property>  
     </bean>  
 </beans>  

index.jsp

welcome page for the application where we are giving option to enter some value in the form which we want to get in the header of the HttpServletRequest object created on submission.

 <%@ 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>  
 </head>  
 <body>  
      <form method="post" action="testheader.html">  
           write the header value to get : <input id="headerTest" name="headerTest" type="text" />  
           <input type="submit" value="submit"/>  
      </form>  
 </body>  
 </html>  

result.jsp

This jsp is just to redirect 2 time without wasting time on again clicking and redirecting. This jsp is also to show that the second  HttpServletRequest object does't contain any information passed in earlier HttpServletRequest object but still we are able to get the value of the earlier submitted request in the getHeader() method of the new HttpServletRequest object.

 <%@ 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>  
 </head>  
 <body>  
 <%response.sendRedirect("/EditHeaderVariable/resultCheck.html");%>  
 </body>  
 </html>  

result2.jsp

This jsp shows the value which we submitted in the first request from the index.jsp by getting the value from the getHeader() method of the HttpServletRequest object from session so that we need not submit the header information every time we need.

 <%@ 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>  
 </head>  
 <body>  
 ${message}  
 </body>  
 </html>  

HeaderController.java

This controller is for just printing and redirecting to the correct jsp resource. 
 
 package com.prajith.httpservlet;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 import org.springframework.stereotype.Controller;  
 import org.springframework.web.bind.annotation.RequestMapping;  
 import org.springframework.web.servlet.ModelAndView;  
 @Controller  
 public class HeaderController {  
      @RequestMapping("/testheader")  
      public ModelAndView testHeader(HttpServletRequest request, HttpServletResponse response){  
           System.out.println("testheader");  
           System.out.println(request.getHeader("headerTest"));  
           return new ModelAndView("result");  
      }  
      @RequestMapping("/resultCheck")  
      public ModelAndView resultCheck(HttpServletRequest request, HttpServletResponse response){  
           System.out.println("resultCheck");  
           System.out.println(request.getHeader("headerTest"));  
           return new ModelAndView("result2","message",request.getHeader("headerTest"));  
      }  
 }  

ModifyRequestObjectFilter.java 

 This filter has been created so that we can modify the request object before reaching the controller. On reaching the controller, the controller gets modified HttpServletRequest object. In the below code you can see we have overridden the dofilter method of the filter interface and changed the ServletRequest object by casting the new class ModifyRequest which extends to HttpServletRequestWrapper class to ServletRequest object

 package com.prajith.filter;  
 import java.io.IOException;  
 import javax.servlet.Filter;  
 import javax.servlet.FilterChain;  
 import javax.servlet.FilterConfig;  
 import javax.servlet.ServletException;  
 import javax.servlet.ServletRequest;  
 import javax.servlet.ServletResponse;  
 import javax.servlet.annotation.WebFilter;  
 import javax.servlet.http.HttpServletRequest;  
 /**  
  * Servlet Filter implementation class ModifyRequestObjectFilter  
  */  
 @WebFilter("/ModifyRequestObjectFilter")  
 public class ModifyRequestObjectFilter implements Filter {  
   /**  
    * Default constructor.   
    */  
   public ModifyRequestObjectFilter() {  
     // TODO Auto-generated constructor stub  
   }  
      /**  
       * @see Filter#destroy()  
       */  
      public void destroy() {  
           // TODO Auto-generated method stub  
      }  
      /**  
       * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)  
       */  
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
           // TODO Auto-generated method stub  
           // place your code here  
           // pass the request along the filter chain  
           try{  
                request=(ServletRequest)new ModifyRequest((HttpServletRequest)request);  
                chain.doFilter(request, response);  
           }catch(Exception e){  
                System.out.println("error "+e);  
           }  
      }  
      /**  
       * @see Filter#init(FilterConfig)  
       */  
      public void init(FilterConfig fConfig) throws ServletException {  
           // TODO Auto-generated method stub  
      }  
 }  

ModifyRequest.java

This class extends to HttpServletRequestWrapper class and overrides getHeader method. In this method we don't want to loose the originality of the method so we have coded as super.getHeader() which calls the parent class method and returns the value accordingly. In case the returned value is null then we are modifying the value to be returned as per our need.
This is not only to modity the getHeader() method but also can be used to modify other method of the HttpServletRequest as per our need.
 
 package com.prajith.filter;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletRequestWrapper;  
 public class ModifyRequest extends HttpServletRequestWrapper {  
      private HttpServletRequest req;  
      private String value=null;  
      public ModifyRequest(HttpServletRequest request) {  
           super(request);  
           req=request;  
           // TODO Auto-generated constructor stub  
      }  
      @Override  
      public String getHeader(String name){  
           value=super.getHeader(name);  
           if(value==null){  
                value=req.getParameter(name);  
                if(req.getParameter(name) !=null)  
                req.getSession().setAttribute(name, req.getParameter(name));  
           }  
           if(req.getParameter(name)==null){  
                value=(String)req.getSession().getAttribute(name);  
           }  
           return value;  
      }  
 }  

project structure image :


maven library dependency:



Monday, 25 March 2013

Creating class inside Interface

Recently i came to know that it is possible to create a class inside a interface. Its just for those people who don't know it is possible.

First we will be creating one interface as below.

TestClassinsideInterface.java

package com.lnt.test;

public interface TestClassinsideInterface {
 void dofoo();
 Ifoo ifoo=new Ifoo();

 final class Ifoo implements TestClassinsideInterface{

    @Override
    public void dofoo() {
        // TODO Auto-generated method stub
        System.out.println("inside dofoo");
    }
   
 }
}


Now creating class with main method to access the class inside interface.


TestInnerInterfaceClass.java


package com.lnt.test;

public class TestInnerInterfaceClass {

   
    public static void main(String[] args){
        TestClassinsideInterface testInterface=TestClassinsideInterface.ifoo;
        testInterface.dofoo();
    }
}
 

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