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.