Month: December 2015

Shallow Copy vs Deep Copy in Java

Posted on

java-logo

Shallow Copy 


Shallow copy is a bit-wise copy of an object. So a new object is created that has an exact copy of the values in the original object.If any of the fields of the object are references to other object then only the reference addresses are copied.

One important Point to be Noted from the Person Class:

Person class doesn’t implements Clonable interfaces so is it the reason why cloned and original object point to same Persone Object.

Points To be Noted :

  1. Changes to the cloned Person object is getting reflected in the original object as well.
  2. Changes to the direct attribute(field i.e. a) of cloned object is not updated in original object.
class Employee {

 private String name;
 private int id;
 public Employee() {}
 public Employee(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [name=");
  builder.append(name);
  builder.append(", id=");
  builder.append(id);
  builder.append("]");
  return builder.toString();
 }
 public Object clone() throws CloneNotSupportedException{
  System.out.println(" Clone method of Employee Class doesn't get called ever.");
  return super.clone();
  
 }
}

Now run CloneTest class again and notice the output.Output is still the same. In fact Person class clone() method is not called at all; and hence you will not notice print statement put in its clone method.

package com.clone.example; 

public class ShallowCopyTest {
 
 public static void main(String args[]) throws CloneNotSupportedException{
  
  Employee employee = new Employee(1,"Ajay Kumar");
  Department department = new Department(1001,employee);
  System.out.println(" Department Details"+department);
  System.out.println(" Employee   Details"+department.getEmployee());

  // Shallow Cloning of Employee Object.
  
  Department department_clone_1 = (Department)department.clone();
  System.out.println(" Clone Department Details"+department_clone_1);
  
  // After cloning of Department object , Get Employee Object and made changes in properties.
  Employee employee_clone_1 = department_clone_1.getEmployee();
  employee_clone_1.setName(" Ram Kumar ");
  
  /*
   * Shallow Copy : Employee Clone Objects are point to same reference
   * of Original Employee Object so any changes get reflected to Original
   * Object of Employee. 
   *  
   */
  
  System.out.println("  Real Object  : "+ department);
  System.out.println("  Clone Object : "+ department_clone_1);
 
 }
}  

class Employee {

 private String name;

 private int id;

 public Employee() {}

 public Employee(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [name=");
  builder.append(name);
  builder.append(", id=");
  builder.append(id);
  builder.append("]");
  return builder.toString();
 }

 

}

class Department implements Cloneable {

 private int department;

 private Employee employee;

 public Department() {}

 public Department(int department, Employee employee) {
  this.department = department;
  this.employee = employee;
 }

 public int getDepartment() {
  return department;
 }

 public void setDepartment(int department) {
  this.department = department;
 }

 public Employee getEmployee() {
  return employee;
 }

 public void setEmployee(Employee employee) {
  this.employee = employee;
 }

 public Object clone() throws CloneNotSupportedException {
  return super.clone();

 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Department [department=");
  builder.append(department);
  builder.append(", employee=");
  builder.append(employee);
  builder.append("]");
  return builder.toString();
 }

}


Output is : 

Department DetailsDepartment [department=1001, employee=Employee [name=Ajay Kumar, id=1]]
Employee   DetailsEmployee [name=Ajay Kumar, id=1]

Clone Department DetailsDepartment [department=1001, employee=Employee [name=Ajay Kumar, id=1]]
Real Object  : Department [department=1001, employee=Employee [name= Ram Kumar , id=1]]

Clone Object : Department [department=1001, employee=Employee [name= Ram Kumar , id=1]]

Deep Copy

A Deep Copy, copies all fields, and makes copies of dynamically allocated memory pointed to by fields. So a deep copy occurs when an object is copied along with the objects to which it refers.

So in our case deep copy will have a separate Person copy so that changes in Clone1 doesn’t get reflected in Original object.

So now it’s easy to understand what is a Deep Copy :


We just need to make sure that clone method creates a new copy of Person object. That’s it !

package com.clone.example;

class Employee implements Cloneable {

 private String name;

 private int id;

 public Employee() {

 }

 public Employee(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [name=");
  builder.append(name);
  builder.append(", id=");
  builder.append(id);
  builder.append("]");
  return builder.toString();
 }

 public Object clone() throws CloneNotSupportedException {
  return super.clone();

 }

}

class Department implements Cloneable {

 private int department;

 private Employee employee;

 public Department() {

 }

 public Department(int department, Employee employee) {

  this.department = department;
  this.employee = employee;

 }

 public int getDepartment() {

  return department;

 }

 public void setDepartment(int department) {
  this.department = department;
 }

 public Employee getEmployee() {
  return employee;
 }

 public void setEmployee(Employee employee) {
  this.employee = employee;
 }

 public Object clone() throws CloneNotSupportedException {
  Department d = (Department) super.clone();
  d.employee = (Employee) employee.clone();
  return d;

 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Department [department=");
  builder.append(department);
  builder.append(", employee=");
  builder.append(employee);
  builder.append("]");
  return builder.toString();
 }
}

public class DeepCopyTest {

 public static void main(String args[]) throws CloneNotSupportedException {

  Employee employee = new Employee(1, "Ajay Kumar");
  Department department = new Department(1001, employee);
  System.out.println(" Department Details" + department);
  System.out.println(" Employee   Details" + department.getEmployee());
  // Shallow Cloning of Employee Object.

  Department department_clone_1 = (Department) department.clone();
  System.out.println(" Clone Department Details" + department_clone_1);

  // After cloning of Department object , Get Employee Object and made
  // changes in properties.
  Employee employee_clone_1 = department_clone_1.getEmployee();
  employee_clone_1.setName(" Ram Kumar ");
  /**
   * Deep Copy : So in our case deep copy will have a separate Person copy
   * so that changes in Clone1 doesn't get reflected in Original object.
   */
  System.out.println("  Real Object  : " + department);
  System.out.println("  Clone Object : " + department_clone_1);

 }

}

Output :

Department DetailsDepartment [department=1001, employee=Employee [name=Ajay Kumar, id=1]]
Employee   DetailsEmployee [name=Ajay Kumar, id=1]
Clone Department DetailsDepartment [department=1001, employee=Employee [name=Ajay Kumar, id=1]]
Real Object  : Department [department=1001, employee=Employee [name=Ajay Kumar, id=1]]
Clone Object : Department [department=1001, employee=Employee [name= Ram Kumar , id=1]]

Injecting a prototype/Session bean into a singleton bean

Posted on Updated on

spring-logo

 

 

 

In Spring, most of the beans we work with are Singletons. If a singleton bean is wired with yet another singleton bean, there is absolutely no problem. But if it is wired with a bean which is of different scope, say prototype, how does it work? Here is the example:
RequestProcessor.Java


public class RequestProcessor {

    private RequestValidator validator;

    public void handleRequest(String requestId){
        validator.validate(requestId);
        // Process the request and update
    }

    public RequestValidator getValidator() {
        return validator;
    }

    public void setValidator(RequestValidator validator) {
        this.validator= validator;
    }

}

RequestValidator.Java


public class RequestValidator {

    private List errorMessages = new ArrayList();

    public RequestValidator() {
        System.out.println("Validator instance created!");
    }

    // Validates the request and populates error messages
    public void validate(String requestId){

    }

    public List getErrorMessages() {
        return errorMessages;
    }

}

And here is the spring configuration:


<bean id="requestProcessor" class="com.pramati.spring.RequestProcessor">
<property name="validator" ref="validator"/>
</bean>

<bean id="validator" scope="prototype" class="com.pramati.spring.RequestValidator"/>

With this configuration, it is expected that when ever I fetch requestProcessor from application context, it will be wired with a new validator as we declared the validator bean is of prototype scope. But this does not happen.
When the application context gets initialized, it sees that requestProcessor is a singleton bean and initializes it to the context after wiring it with all the dependencies set. So from then onwards when we request context for requestProcessor, it return the same bean every time. To solve this issue, we have 2 approaches:

1.Lookup Method injection: For this, we have to declare the beans as follows:


<bean id="requestProcessor" class="com.pramati.spring.RequestProcessor">
 <lookup-method name="getValidator" bean="validator"/>
</bean>

<bean id="validator" scope="prototype" class="com.pramati.spring.RequestValidator"/>

The Spring Framework implements method injection by using CGLIB library to generate dynamically a subclass that overrides the method. So for the method to be overridden, we have to define that method in the class and either provide a dummy implementation for it or make it abstract. Making a method abstract implies that class also has to be made abstract which will make it difficult to unit test. So providing a dummy implementation is a better choice.
Whenever we define a bean with lookup methods, Spring creates a subclass of the bean and overrides those methods which are marked as lookup-methods. And this subclassed bean gets registered into the context. The subclass delegates all the non-lookup methods to the original class. For the lookup methods, it overrides the implementation. So in our example, when getValidator() is called, it returns a new validator instance.
We can roughly imagine our new subclass(registered in container) like this:


requestProcessor = new RequestProcessor(){
    public RequestValidator getValidator(){
        return context.getBean("validator");
    }
};

We could have directly fetched the bean from application context in RequestProcessor itself. But this would mean that the class is directly coupled to Spring framework. To do this in a cleaner way, we can use lookup injection. This puts all the spring related stuff at one place.

2. Scoped Proxies: This can be implemented as:


<bean id="requestProcessor" class="com.pramati.spring.RequestProcessor">
<property name="validator" ref="validator"/>
</bean>

<bean id="validator" scope="prototype" class="com.pramati.spring.RequestValidator">
<!-- This instructs the container to proxy the current bean-->
<aop:scoped-proxy/>
</bean>

Remember, in the case of look up method injection, proxy is created for singleton bean. But in case of scoped proxies, proxy is created for prototype bean and wired into the singleton bean during the process of registering the singleton bean in the context. The proxy thus created understands the scope and returns instances based on the requirements of the scope. So in our case, requestProcessor holds a reference to proxy in place of validator.
And in case of lookup method injection, when requestProcessor gets loaded into the context, validator will not be initialized at all. And when we call the look up method, it returns the prototype bean. But instead of calling the method, if you try to directly access the prototype bean(assuming it is accessible), it gives a Nullpointer Exception as it didn’t get initialized(We are not wiring it using property tag of bean)
In case of this, we can also configure how a proxy can be created. It can be done in 2 ways:-

  1. CGLIB library which directly subclasses the object. This is the default option of Spring. For this, we must have CGLIB library our class path.
  2. Java Dynamic Proxies. For this to be activated, we have to call:

<aop:scoped-proxy proxy-target-class="false"/>

Here in this case, we don’t need any additional libraries in our class path. But the scoped bean must implement at least one interface and it has to be referred through the same interface at all places in order to get itself wired.

Few points to note:
1. Both method injection and scoped proxies work not only for prototype beans. This works more generic. Whenever a bean of different scope is injected into a singleton bean, we can use any of these techniques to ensure that we get a corresponding scope object.
2. Note that in the proxy, the method returning the prototype bean is overridden to return a new instance for every single call.
Suppose we want to display the error messages that we have got after validation:


requestProcessor.getValidator().validate();
for(String message: requestProcessor.getValidator().getErrorMessages()){
logger.log(LogLevel.ERROR, message);
}

This code seems to print the error messages we have got after validation process. But this will never print any error messages even if there are many validation failures. This happens because requestProcessor.getValidator() returns a new validator instance every time it is called. So for this to work, the code has to be modified as:


RequestValidator validator = requestProcessor.getValidator();
validator.validate();
for(String message: validator.getErrorMessages()){
logger.log(LogLevel.ERROR, message);
}

This happens only in case of prototype beans but works perfectly in case of other non-singleton scopes(request, session, global-session).

The singleton scope
When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

The session scope
With the above bean definition in place, the Spring container will create a brand new instance of the bean , for the lifetime of a single HTTP Session.
According to Spring framework reference, a different approach needs to be followed in cases where a class which “lives longer”(singleton bean in this case) needs to be injected with another class having a comparatively shorter life-span(session-scoped bean). The approach is different for prototype & singleton scope though.
In your XML, what we want is that the singletonBean instance should be instantiated only once, and it should be injected with sessionBean. But since sessionBean is session-scoped(which means it should be re-instantiated for every session), the configuration is ambiguous(as the dependencies are set at instantiation time and the session scoped value can change later also).
So instead of injecting with that class, it’s injected with a proxy that exposes the exact same public interface as sessionBean. The container injects this proxy object into the singletonBean bean, which is unaware that this sessionBean reference is a proxy. It’s specified by writing this tag in the sessionBean:


<aop:scoped-proxy/>

XML Configuration:


<bean name="singletonBean" class="somepkg.SingletonBean">
<property name="someProperty" ref="sessionBean"/>
</bean>

<bean name="sessionBean" class="somepkg.SessionBean" scope="session">
<aop:scoped-proxy/>
</bean>

When a singletonBean instance invokes a method on the dependency-injected sessionBean object, it actually is invoking a method on the proxy. The proxy then fetches the real sessionBean object from (in this case) the HTTP Session, and delegates the method invocation onto the retrieved real sessionBean object.

Singleton beans with prototype-bean dependencies

Lookup Method Injection

When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies are resolved at instantiation time. Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean.
However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies.


<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="command" class="fiona.apple.AsyncCommand" scope="prototype">
<!-- inject dependencies here as required -->
</bean>

<!-- commandProcessor uses statefulCommandHelper -->
<bean id="commandManager" class="fiona.apple.CommandManager">
<lookup-method name="createCommand" bean="command"/>
</bean>

Lookup method injection is the ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container. The lookup typically involves a prototype bean as in the scenario described in the preceding section. The Spring Framework implements this method injection by using bytecode generation from the CGLIB library to generate dynamically a subclass that overrides the method.

This Topic is copied from this site.

How are constructors called during serialization and deserialization?

Posted on Updated on

This topic is taken up from this source.

How are the constructors called during serialization and deserialization

  1. When there is one class implementing serializable?
  2. When there is parent/child relationship and only child implements serializable?
  3. When there is parent/child relationship and both parent and child implements serializable?

Few opinion related to  question:

1) If one class is implementing serializable and only that class is there no parent class is there. constructor flow is like default constructor will be call of the parent class who is not implemented serializable. in this case it is Object class. so No-arg constructor of Object class will run and will create dummy object and while calling readObject() field will be set by reflection and data which is saved in memory or file.

2) if only child implements serializable then flow will goes till the base class which is not serializable. if dierect base class is not serialized then (that class should have NO-Arg constructor) NO-Arg constructor will run for base class in this case.

3) if all the parents are serialized then flow will goes to Object class and No-Arg constructor will run of Object class.

Note : But you can serialize by implementing externalizable interface then default constructor (NO-ARG) will be called of that class only not of parent class on deserialization process.

Example here:-


package com.itexpert.serialization.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class A {
	protected int field;

	A() {
		System.out.println("A::Default Constructor");
	}

	A(int i) {
		this.field = i;
		System.out.println("A::Parameter Constructor");
	}

	public int getField() {
		return field;
	}

	public void setField(int field) {
		this.field = field;
	}

	@Override
	public String toString() {
		return String.format("A [field=%s]", field);
	}

}

class B extends A implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6197736672294431667L;
	protected int field;

	B() {
		System.out.println("B::Default Constructor");
	}

	B(int i) {
		this.field = i;
		System.out.println("B::Parameter Constructor " + field);
	}

	@Override
	public String toString() {
		return String.format("B [field=%s]", field);
	}

	public int getField() {
		return field;
	}

	public void setField(int field) {
		this.field = field;
	}

}

public class ChildDeseralizationTest {
	public static void main(String args[]) throws FileNotFoundException,
			IOException, ClassNotFoundException {
		File file = new File("d:\\session.txt");
		ObjectOutput out = new ObjectOutputStream(new FileOutputStream(file));
		B writeChild = new B();
		out.writeObject(writeChild);
		out.close();
		System.out.println("===========Restore Object By Deserialization ==============");
		ObjectInput input = new ObjectInputStream(new FileInputStream(file));
		B readB = (B) input.readObject();
		System.out.println(readB.getField());
		input.close();
	}
}


Output here :-

A::Default Constructor
B::Default Constructor
===========Restore Object By Deserialization ==============
A::Default Constructor
0

Next, What will happen if Parent class “A” implements “Serializable” interface then Output should be like :-

A::Default Constructor
B::Default Constructor
===========Restore Object By Deserialization ==============
0

The output difference clearly said that during deserialization, non-serialization class No-Arg constructor gets invoked. In the second scenario output (  if Parent class “A” implements “Serializable” ), recursively default constructor will call upto base class or Object Class until JVM Compiler gets to know which class doesn’t implement Serialization interface so Default constructor will call to that class.

 

Deserialization doesn’t invoke the constructor because the purpose of it is to express the state of the object as it was serialized, running constructor code could interfere with that.

Spring4 + Hibernate 4 + JSON Example with XML Configuration

Posted on Updated on

spring_mvc_rest

 

 

 

 

 

In this article, we will show you how to produce JSON as a Http response.

Technologies used:

  1. JDK 1.6
  2. Spring 4.0.3.RELEASE
  3. Hibernate 4.3.4.Final
  4. Jackson 2.4.1
  5. Eclipse 3.6
  6. Maven 3

Project hierarchy in Eclipse :-

Spring4HibernateJSONExample-project-hierarchy

 

 

 

 

 

 

 

 

 

 

 

 

Following REST Services to be Exposed:-

REST service URI Methods Parameter Description
/API/enquiry GET None Fetch out all record of enquiry
/API/enquiry/{enquiry_id} GET enquiry_id Fetch out a specified record of enquiry Table base on {enquiry_id}
/API/enquiry POST Send Enquiry Object in JSON format Add a record
/API/enquiry/{enquiry_id} DELETE enquiry_id Delete a specified record from Enquiry Table.
/API/enquiry PUT Send Enquiry Object in JSON format Update existing record

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/maven-v4_0_0.xsd">

<groupId>com.spring.itexpert</groupId>
<modelVersion>4.0.0</modelVersion>
<artifactId>Spring4HibernateJSONExample</artifactId>
<name>Spring4HibernateJSONExample</name>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<description>
Root Project For Spring + Hibernate + JSON Application
</description>
<properties>

<!-- Generic properties -->
<java.version>1.6</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<cglib.version>2.2.2</cglib.version>
<!-- Spring -->
<spring-framework.version>4.0.3.RELEASE</spring-framework.version>
<hibernate.version>4.3.4.Final</hibernate.version>

<jackson-version>2.4.1</jackson-version>
</properties>

<dependencies>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring JDBC Support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring core & mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- CGLib for @Configuration -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>${cglib.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Servlet API Support -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
</dependency>
</dependencies>

<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/web</warSourceDirectory>
<warName>Spring4HibernateJSONExample</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>

<finalName>Spring4HibernateJSONExample</finalName>
</build>
</project>

Spring-servlet.xml:-


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<context:annotation-config />
<mvc:annotation-driven />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.databaseurl}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<context:component-scan base-package="com.spring.itexpert" />

</beans>

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_2_5.xsd"
id="WebApp_ID" version="2.5">

<display-name>Web Application</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

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

hibernate.cfg.xml


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<mapping class="com.spring.itexpert.hibernate.model.Enquiry" />
</session-factory>
</hibernate-configuration>

jdbc.properties:-


jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/myDB
jdbc.username=root
jdbc.password=root

EnquiryController.Java  :


package com.spring.itexpert.controller;

import java.security.Principal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.spring.itexpert.dao.EnquiryRepository;
import com.spring.itexpert.hibernate.model.Enquiry;


@Controller
@RequestMapping("/API/enquiry")
public class EnquiryController {

	@Autowired
	private EnquiryRepository enquiryRepository;
	
	@ResponseBody
	@ResponseStatus(value=HttpStatus.OK)
	@RequestMapping(method=RequestMethod.GET)
	public List getListOfEnquiry(){
		List enquiries = enquiryRepository.getListOfEnquriry();
		return enquiries;
	}
	
	@ResponseBody
	@ResponseStatus(value=HttpStatus.OK)
	@RequestMapping(value="/{enquiry_id}",method=RequestMethod.GET)
	public Enquiry getEnquiry(@PathVariable("enquiry_id") Long enquiry_id){
		System.out.println(enquiry_id);
		return enquiryRepository.getEnquiry(enquiry_id) ;
	}
	
	
	@ResponseBody
	@ResponseStatus(value=HttpStatus.OK)
	@RequestMapping(method=RequestMethod.POST)
	public void getSaveEnquiry(Principal principal, @RequestBody Enquiry e){
		enquiryRepository.save(e);;
	}
	
	@ResponseBody
	@ResponseStatus(value=HttpStatus.OK)
	@RequestMapping(value="/{enquiry_id}",method=RequestMethod.DELETE)
	public  void deleteEnquiry(@PathVariable("enquiry_id") Long enquiry_id, Principal principal){
		enquiryRepository.delete(enquiry_id);
	}
	
	@ResponseStatus(value=HttpStatus.OK)
	@RequestMapping(method=RequestMethod.PUT)
	public void editEnquiry(@RequestBody Enquiry e,Principal principal){
		System.out.println(e);
		enquiryRepository.update(e);
	}
		
}


EnquiryRepository.Java


package com.spring.itexpert.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.spring.itexpert.hibernate.model.Enquiry;


@Repository
@Transactional
public class EnquiryRepository {

	@Autowired
	private SessionFactory sessionFactory;

	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	public List getListOfEnquriry() {
		List list = getSession().createCriteria(Enquiry.class).list();
		return list;
	}
	public List getListOfEnquriry(Integer maxPageSize,Integer maxRecord) {
		List list = getSession().createCriteria(Enquiry.class)
				.setMaxResults(maxRecord)
				.setFirstResult(maxPageSize)
				.list();
		return list;
	}
	
	public void update(Enquiry e){
		getSession().merge(e);
	}
	
	public void save(Enquiry e){
		getSession().merge(e);
	}
	
	public void delete(Long enquiry_id){
		Enquiry e = (Enquiry)getSession().get(Enquiry.class, enquiry_id);
		getSession().delete(e);
		
	}
	
	public Enquiry getEnquiry(long id){
		Enquiry e = (Enquiry)getSession().get(Enquiry.class, id);
		System.out.println(e.toString());
		return e != null? e:new Enquiry();
	}
	
}


Enquiry.Java


package com.spring.itexpert.hibernate.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Type;

@Entity
@Table(name = "enquiry")
public class Enquiry {

	@Id
	@GeneratedValue
	private long id;
	private String name;
	private String course;
	private String status;
	private String preferences;
	private String location;
	private String place;
	private String remarks;
	private String email;

	private String source;
	private String mobile;
	@Column
	@Temporal(TemporalType.TIMESTAMP)
	@Type(type="timestamp")
	private Date enquiry_date;
	
	@Column
	@Temporal(TemporalType.TIMESTAMP)
	@Type(type="timestamp")
	private Date updated_date;
	
	
	public Enquiry(){}
	
	public Enquiry(String studentname, String course, String status,
			String preference, String remarks, String email, String source,
			String mobile,Date enquiry_date) {
		this.name = studentname;
		this.course = course;
		this.status = status;
		this.preferences = preference;
		this.remarks = remarks;
		this.email = email;
		this.source = source;
		this.mobile = mobile;
		this.enquiry_date = enquiry_date;
	}

	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setStudentname(String studentname) {
		this.name = studentname;
	}
	public String getCourse() {
		return course;
	}
	public void setCourse(String course) {
		this.course = course;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	public String getPreferences() {
		return preferences;
	}
	public void setPreference(String preference) {
		this.preferences = preference;
	}
	public String getRemarks() {
		return remarks;
	}
	public void setRemarks(String remarks) {
		this.remarks = remarks;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getSource() {
		return source;
	}
	public void setSource(String source) {
		this.source = source;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	

	public Date getEnquiry_date() {
		return enquiry_date;
	}

	public void setEnquiry_date(Date enquiry_date) {
		this.enquiry_date = enquiry_date;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setPreferences(String preferences) {
		this.preferences = preferences;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public String getPlace() {
		return place;
	}

	public void setPlace(String place) {
		this.place = place;
	}

	public Date getUpdated_date() {
		return updated_date;
	}

	public void setUpdated_date(Date updated_date) {
		this.updated_date = updated_date;
	}

	@Override
	public String toString() {
		return String
				.format("Enquiry [id=%s, name=%s, course=%s, status=%s, preferences=%s, location=%s, place=%s, remarks=%s, email=%s, source=%s, mobile=%s, enquiry_date=%s, updated_date=%s]",
						id, name, course, status, preferences, location, place,
						remarks, email, source, mobile, enquiry_date,
						updated_date);
	}

	
}


Spring MVC + JSON = 406 Not Acceptable + characteristics not acceptable according to the request “accept” headers ()

Posted on Updated on

This is the  very common mistake that typically happened during the configuration Spring + JSON. Recently we faced such issues with Spring 4 + Hibernate configuration so by digging some blogs and own effort make this issues fixed.

below are some steps that need to be changed in configuration file so we can get rid of “Response Error 406 :-characteristics not acceptable according to the request “accept” headers ()

Get rid of this issues by adding **@EnableWebMvc** in Controller class.

@Controller
@RequestMapping("/API/course")
@EnableWebMvc
public class CourseController {
@Autowired
private com.item.DAO.CourseRepository courseRepository;

@ResponseStatus(value=HttpStatus.OK)
@RequestMapping(method=RequestMethod.GET)
public @ResponseBody List<Course> getListOfCourse(){
List<Course> courses = courseRepository.getListOfCourse();
return courses ;
}

or add following lines in xml configuration file if XML configuration is being used in your project.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<bean>

and add following dependencies in your pom.xml file:-


<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.1</version>
</dependency>

See complate example here.

We hope this will help you out, Thanks !!