RESTful example with Tomcat and maven

Posted on Updated on

RESTful example with Tomcat and Maven

This is a Simple example of RESTful using jersey service in eclipse which is intended to explore how to implement RESTful services in our project. In web.xml file, Full qualified package is given to scan all services class under this package it will automatically happened at deployment time also servlet-mapping defined services mapping pattern in this case /rest/* means all RESTful container will be treated all services as RESTful service that start with /rest/*. example :-

  • /rest/user
  • /rest/user/{user_id}

Create and configure a pom.xml which contains all required dependencies for RESTful.

pom.xml file under root directory in your project:-


<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.rest</groupId>
<modelVersion>4.0.0</modelVersion>
<artifactId>RESTfulExample1</artifactId>
<name>RESTfulExample1</name>
<version>1.1-SNAPSHOT</version>
<packaging>war</packaging>

<description>
RESTful Example1
</description>

<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" -->
<artifactId>jersey-container-servlet</artifactId>
<version>2.17</version>
</dependency>
<!-- Required only when you are using JAX-RS Client -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.2.3</version>
</dependency>

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

<finalName>ITCM</finalName>
</build>
</project>


Project explorer in Eclipse : –

project-explorer

Project src files :-

com.rest.service

UserInfoService.Java :- Intended of this class is to produce and consume resources using RESTful service.


package com.rest.service;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.rest.model.User;
import com.rest.repository.UserRepository;

@Path("/user")
public class UserInfoService {
private UserRepository userRepo = new UserRepository();

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getUsers(){
return Response.ok().entity(userRepo.getAllUsers()).build();
}

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{user_id}")
public Response getUser(@PathParam("user_id") int user_id){
return Response.ok().entity(userRepo.getUser(user_id)).build();
}

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response postUser(User user){
userRepo.insert(user);
return Response.ok().status(Status.OK).build();
}

@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response putUser(User user){
userRepo.update(user);
return Response.ok().build();
}

@DELETE
@Path("/{user_id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response deleteUser(@PathParam("user_id") int user_id){
userRepo.deleteUser(user_id);
return Response.ok().build();
}


}

 com.rest.reporitory

UserRepository.Java :- Intended of repository class to perform CRUD operation over user data.


package com.rest.repository;

import java.util.Collection;

import com.rest.factory.UserRepositoryFactory;
import com.rest.model.User;

public class UserRepository {
private UserRepositoryFactory userFactory = UserRepositoryFactory.getInstance();

public User getUser(int id){
return userFactory.getUser(id);
}

public Collection<User> getAllUsers(){
return userFactory.getListOfUsers().values();
}

public User deleteUser(int id){
return userFactory.deleteUser(id);
}

public void insert(User user){
userFactory.getUpdate(user);
}

public void update(User user){
userFactory.getUpdate(user);;
}
}

 com.rest.model

User.java :- this is a pojo/model java class this is used to wrap the User properties either user response or request parameters.


package com.rest.model;

import java.io.Serializable;

public class User implements Serializable{

/**
*
*/
private static final long serialVersionUID = 3228632501659659215L;
private int id;
private String name;
private String address;
public User(){

}

public User(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}

}

 com.rest.factory

UserRepositoryFactory.java:- intended of this factory class to provide User data.


package com.rest.factory;

import java.util.HashMap;
import java.util.Map;

import com.rest.model.User;

public class UserRepositoryFactory {

private static Map<Integer, User> users = new HashMap<Integer, User>();

public Map<Integer, User> getListOfUsers() {
User u1 = new User(101, "Ajay Kumar", "New Delhi");
User u2 = new User(102, "Rahul Kumar", "Goa");
User u3 = new User(103, "Santosh Kumar", "Delhi");
users.put(u1.getId(), u1);
users.put(u2.getId(), u2);
users.put(u3.getId(), u3);
return users;
}

public User getUser(Integer id) {
return users.get(id);
}

public User deleteUser(Integer id) {
return users.remove(id);
}

public void getUpdate(User user) {
if (users.containsKey(user.getId())) {
// update user here
users.put(user.getId(), user);
} else {
// add user
users.put(user.getId(), user);
}
}

private UserRepositoryFactory() {
}

private static UserRepositoryFactory userRepository = new UserRepositoryFactory();

public static UserRepositoryFactory getInstance() {
if (userRepository == null) {
synchronized (UserRepositoryFactory.class) {
userRepository = new UserRepositoryFactory();
}
}
return userRepository;
}
}

Web-description file ( 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"
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>RESTfulExample1</display-name>

<servlet>
<servlet-name>REST</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
com.jersey.jaxb,com.fasterxml.jackson.jaxrs.json,com.rest.service
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>REST</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>

GET method:-

  • /rest/user : – Fetch all users
  • /rest/user/101 – Fetch User which id is 101

GET-User

POST method :-

  • /rest/user :- Add User
    • Method:Post
    • Content-Type:application/json
    • JSON Request Parameter : { “id”: 107, “name”: “Rahul Kumar”, “address”: “Goa” }
    • Return Response : Response Status OK

POST-User

PUT method :-

  • /rest/user :- Update User
    • Method:PUT
    • Content-Type:application/json
    • JSON Request Parameter : { “id”: 107, “name”: “Any name”, “address”: “Any City” }
    • Return Response : Response Status OK

PUT-User

DELETE method :-

  • /rest/user/101 :- Delete User which user id is 101
    • Method:DELETE
    • Return Response : Response Status OK

DELETE-User-BY-ID

Below step’s are done using RESTful tools to fire rest services

 Download Complete source code from here

 

RESTful Service in Java

Posted on Updated on

RESTful Service in Java.

Table of Contents:-

  1. What is RESTful service in Java ?
  2. How to implement it in Web Application ?

 

What is RESTful service in Java ?

Representation state transfer(REST) is architecture style that specifies constraints i.e Uniform resource identifier(URI). REST architecture style represents data,functionality as resources that are accessed by URI. REST create a bridge between Client/Server architecture and communicate over stateless HTTP protocol and Client/Server exchange representation  resources by using standardized interface and protocol.

URL ( Uniform Resource Locator ) formation :-

URL : <Protocol> ://< Hostname> :< port>/<Context-name>/<URL>

http://localhost:8080/RESTfulExample1/rest/user/102

RESTful ( JAX-RS) annotation summary :-

  • @path : – It’s used to represents an URI path template which the resource response it.
  • @consume :- It’s used to specify MIME media type representation of a resource can consume that were sent by client.
  • @produce :- it’s used to specify MIME media type representation of a resource can produce that send back to client like “application/json”,”application/text”.
  • @ParamPath :- The @PathParam annotation is a type of parameter that you can extract for use in your resource class.URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation.
  • @QueryParam :- The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters.
  • @Context :- @Context can be used to obtain contextual Java types related to the request or response.

How to convert an Object into Response Type (“JSON/Text/Xml”):-

Using javax.ws.rs.core.Response , contract between a returned instance and the runtime when an application needs to provide metadata to the runtime.

@GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response getUsers(){
 return Response.ok().entity(userRepo.getAllUsers()).build();
 }

HTTP methods :-

  • GET : – it’s used to read a specified resource.
  • POST :- it’s used to create a specified resource.
  • PUT :-  it’s used to update a specified resources
  • DELETE :-it’s used to delete a specified resources
  • HEAD :- Same as GET but returns only HTTP headers and no document body

Key Points :-

  • It’s not a protocol.
  • It’s a architecture style that represent a resources that are accessed by URI.
  • Communication over HTTP is stateless.
  • It’s scalable,reliable and portable by nature.

Example with source code below :

  1. RESTful example with Tomcat and Maven.

Importants of hashcode and equals method in Java

Posted on Updated on

Importants of hashcode and equals method in Java

These two is core part of Collection in Java and most frequently asked question in interview. In this article we will discuss all related points.

hashcode and equals methods are two fundamental topics from java.lang.Object class which is used to compare two Object using equality and calculate the memory address of Object using hashcode function.  primarily uses of these two function in Collection in java like HashMap,Hashtable,etc.

Default implementation of these two methods in java.lang.Object class :-

hashcode method :- it’s a native method means implemented directly in ‘native code’ in JVM that return distinct integer value for distinct Objects. Typically it’s converted internal memory address of Object into integer. Ideally a hashcode method represent an Object so distinct Object having distict hashcode values.

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

public native int hashCode();

equals method:- Default implementation is comparing two Object by reference and return true if Objects reference are same otherwise false.

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used inequals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.
public boolean equals(Object obj) {
return (this == obj);
}

 Contract Implementation of these methods and their uses:-

In general, contract of overridden implementation of these methods give us a consistent behaviours of same Object every time.It is not mandatory to implement but recommended to implement these methods when Object to be used in Collection part.

Key Points :-

    • Two objects are equals according to equals() must return same hashcode for each of Object but in opposite two Objects having same hashcode may not be equals by equals().
    • Invalid or unimplemented of these two overridden methods of Object class may cause serious issues in our application.
    • If hashcode() return same hash value for Objects then internally a LinkedList chain would be created against that key and maintains Key/Value Pairs in Entry Object.

Internal implementation of static class Entry.Java in HashMap

static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;

        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }

Internal implementation of put() in HashMap

 
    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

Example :-

import java.util.HashMap;
import java.util.Map;

class Employee {
	private long id;
	private String name;
	private String address;
	public Employee(long id,String name,String address){
		this.id=id;
		this.name = name;
		this.address = address;
	}
        /**
         * Getter/Setter ....
         */ 
 
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((address == null) ? 0 : address.hashCode());
		result = prime * result + (int) (id ^ (id >>> 32));
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	
}

Here, Three distinct Employee Object is created, each of them has different properties and stored into HashMap. During this discussion we will see what will happen if hashcode() is not implemented.
Main Class here :-


public static void main(String args[]){
Map<Employee,Employee> map = new HashMap<Employee,Employee>();
Employee e1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3 = new Employee(1003, "Wasim Akram","Delhi");

map.put(e1, e1);
map.put(e2, e2);
map.put(e3, e3);
}

case 1 : if hashcode() is not override in Employee class then


map.containsKey(new Employee(1001, "Ajay Kumar","Delhi"));// false
map.containsKey(new Employee(1002, "Santosh Kumar","New Delhi")); // false
map.containsKey(new Employee(1003, "Wasim Akram","Delhi")); // false
map.containsKey(e1) // true
map.containsKey(e2) // true
map.containsKey(e3) // true

case 2 : if hashcode() is override in Employee class then


map.containsKey(new Employee(1001, "Ajay Kumar","Delhi"));// true
map.containsKey(new Employee(1002, "Santosh Kumar","New Delhi")); // true
map.containsKey(new Employee(1003, "Wasim Akram","Delhi")); // true
map.containsKey(e1) // true
map.containsKey(e2) // true
map.containsKey(e3) // true

case 3 : if equals() is not override in Employee class then


Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");
		
System.out.println(e1.equals(e1_1)); // false
System.out.println(e2.equals(e2_2)); // false
System.out.println(e3.equals(e3_3)); // false

case 4 : if equals() is override in Employee class then


Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");
		
System.out.println(e1.equals(e1_1)); // true
System.out.println(e2.equals(e2_2)); // true
System.out.println(e3.equals(e3_3)); // true

case 5 : if hashcode() is override but equals() is not in Employee class then


Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");	
System.out.println(e1.equals(e1_1)); // false
System.out.println(e2.equals(e2_2)); // false
System.out.println(e3.equals(e3_3)); // false

case 6 : if hashcode() returns fixed value but equals() is not override in Employee class then

@Override
 public int hashCode() {
 return 31;
}
Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");	
System.out.println(map.get(e3_3)); // null
System.out.println(map.get(e3)); // Employee [id=1003, name=Wasim Akram, address=Delhi]

case 7 : if hashcode() returns fixed value and equals() is override in Employee class then

@Override

//Employee.Java 
public int hashCode() {
 return 31;
}
@Override
public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
}

//Main.Java Class	
Employee e1_1 = new Employee(1001, "Ajay Kumar","Delhi");
Employee e2_2 = new Employee(1002, "Santosh Kumar","New Delhi");
Employee e3_3 = new Employee(1003, "Wasim Akram","Delhi");	
System.out.println(map.get(e3_3)); // // Employee [id=1003, name=Wasim Akram, address=Delhi]

System.out.println(map.get(e3)); // Employee [id=1003, name=Wasim Akram, address=Delhi]

 

Interview Question :-

What is hashcode and equals methods ?
hashcode() is a native method of java.lang.Object class this is a technique to calculate the memory address of object into integer value. Ideally, hashcode assign each Object as key to unique bucket in Map.

equals method is used to compare between two Objects and it return true if Objects are equals according to their implementation otherwise return false. It is used to search an Object into bucket of Map implementation.

Why it’s important to override these methods.

As we discussed below, each object has their hashcode which represent Object identity. Also it guarantee then same hash value will be generated consistently every time for same Object by override this method.so it’s important to implemented in our Bean class. Whenever we use this object as Key in Map implementation then a bucket is assigned to Entry<Key,Value> object by calculated hash code of key Object otherwise default implementation of native hashcode() from java.lang.Object Class will be applied which produce inconsistent behaviours in Java compiler.

In the same way, default implementation of equals() methods return false every time for every mutable Object by equality, just because it’s compare objects reference by default not by Object content.

What is hashing technique ?

It’s a technique to compute hash value of Object, Once the hash value is computed then we can insert into hashtable at designated position or bucket. In Java using hashcode() map each Object into unique slot.

What happened if hashcode() is not overridden ?

If we don’t implement hashcode method then default implementation of Object class is used to store and retrieve Object value from Hashtable,HashMap and HashSet, subsequently result would be incorrect. Hence it’s recommended to override these two method.

Two Objects which are equals according to equals() then what their hash value ?

if two Objects are equals according to equals() then hashcode() produce same hash value.

What is hash Collision?

Often it’s not possible if implemented hashcode() is perfect but when two objects hash point to same slot or bucket then it will happen therefore internally a linked list chain will be created that store the Entry Object.

Difference between ‘==’ and equals() method.

‘==’ is a Java operator which is used to compare two operands reference or values.
equals() is a method from java.lang.Object class with check object content.

Difference between equals() and compareTo() ?

  • equals() methods came from java.lang.Object class while compareTo() came from java.lang.comparable interface.
  • equals() return false if it’s compare with Null reference while compareTo return NullPointerException.
System.out.println(e1.equals(null)); // false
System.out.println("Say Hello".compareTo(null)); // Exception in thread "main" //java.lang.NullPointerException
//at java.lang.String.compareTo(Unknown Source)
  • compareTo() only work on those Object that implements Comparable interface.
  • equals() method returns boolean value while compareTo() return integer value.

 

 

What is transient variable in Java

Posted on Updated on

What is transient variable in Java

transient is a keyword in Java, which means variable is marked transient to indicate that they are not part of persistent state while Object is being saved into File system or DB.

Today we are moving toward annotation base programming rather than manual configuration and sometime we declared properties in Pojo class in which we marked few of perperties as transient then that properties only useful at application level not DB or File System.Hence we can control fields being saved during Serialization process using transient keywork.

Below example of Weather.Java indicate that temperature field value is not saved into File System or dB. Only city field value would be saved.


public class Weather {
private String city;
private transient String temperature;
--------
--------
}

Similarly, if you are familiar with MondoDB or Hibernate Annotation base Pojo class, Same way we can control the fields from being persistence state.

LoginModel.Java :- Mongodb pojo Java Class

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "Login")
public class LoginModel {
 
 @Id
 private String id;
 private String userName;
 private String password;
@Transient
private String sessionId;
-------------
-------------
 Below are complete code of transient-

Weather.Java is a Serialized Java class.

import java.io.Serializable;

public class Weather implements Serializable {
 /**
 * 
 */
 private static final long serialVersionUID = 2983365916512327738L;
 private String city;
 private transient String temperature;

 public Weather(String city, String temperature) {
 this.city = city;
 this.temperature = temperature;
 }

 public String getCity() {
 return city;
 }

 public void setCity(String city) {
 this.city = city;
 }

 public String getTemperature() {
 return temperature;
 }

 public void setTemperature(String temperature) {
 this.temperature = temperature;
 }

 @Override
 public String toString() {
 StringBuilder builder = new StringBuilder();
 builder.append("Weather [city=").append(city).append(", temperature=")
 .append(temperature).append("]");
 return builder.toString();
 }

}

 WeatherSerializationService .java : read or write Object as serialization form


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


public class WeatherSerializationService {
	
	private static final String FILE_NAME="weather.sar";
	
	public static void main(String args[]){
		Weather weather = new Weather("Delhi","42'C");
		WeatherSerializationService weatherService = new WeatherSerializationService();
		System.out.println("Save Serializated Object "+weather);
		weatherService.save(weather);
		
		Weather readWeather = weatherService.retrive();
                if( null == readWeather ){
                    System.out.println(" Unable to read Serialization Object - Weather ");
                }
		System.out.println("Read Serializated Object "+readWeather);
		
	}
	public void save(Weather weather){
		FileOutputStream fileOutputStream = null;
		ObjectOutput objectOut = null;
		try {
			fileOutputStream = new FileOutputStream(FILE_NAME);
			objectOut = new ObjectOutputStream(fileOutputStream);
			objectOut.writeObject(weather);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null == objectOut ) return;
                                if(null == fileOutputStream ) return;
				objectOut.close();
				fileOutputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	public Weather retrive(){
		ObjectInput objectInput = null;
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(FILE_NAME);
			objectInput = new ObjectInputStream(inputStream);
			return (Weather)objectInput.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null == objectInput ) return null;
				if(null == inputStream ) return null;
				
				objectInput.close();
				inputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

}

Output here :-

Save Serializated Object Weather [city=Delhi, temperature=42’C]
Read Serializated Object Weather [city=Delhi, temperature=null]

 

What is Serialization in Java

Posted on Updated on

What is Serialization in Java

Java provides a mechanism  to convert Object into bit of Stream which includes Object data and information also Type and it’s values. Java provide automatic Serialization which required class must be implementing java.io.serialization interface.

Process of serialization is also called marshalling and in opposite reconstructing a serialization Object by extracting all fields from byte code is called as De-Serialization or unmarshalling.

Serialization is an interface that belong to java.io package which is also called as Marker class.

Marker Class :- A class that has no method and fields within it is called Marker Class. Java provides few marker class as below :

Searilizable,Cloneable,Remote,ThreadSafe interface

Where it is used :-

  • To transmit object over/across Network.
  • To buffer or in memory File system store.
  • RMI call in distributed environment.
  • Component base programming like CORBA,COM

read here about Why SerialVerisonUID is important

Key Points :-

  • transient/static type can not be serialized.
  • To extract or deserialization from series of bytes into Object may be claused in different JVM compiler if serialVersionUID is not implemented.
  • Serialization/Deserialization is a recursive process which may be cause performance footprint.

 

Example :-

  1. How to Serializated multple Object

 

How to Serialized multiple Object in Java

Posted on Updated on

 

HostPersistor.Java


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.bean.HostInfo;

public class HostPersistor {

    static Map HostInfoMap = new Hashtable();
    public static void write(HostInfo obj) {

        FileOutputStream fout = null;
        ObjectOutputStream objout = null;
        try {
            File file = new File("HOST_SESSION_HISTORY.ser");
            if (!file.exists()) {
                file.createNewFile();
            }
            fout = new FileOutputStream(file);

            if (!HostInfoMap.containsKey(obj)) {
                HostInfoMap.put(obj.getIpaddress(),obj);
                objout = new ObjectOutputStream(fout);
                for (Map.Entry info : HostInfoMap.entrySet()) {
                    objout.writeObject(info.getValue());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (objout != null)
                    objout.close();
                if (fout != null)
                    fout.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    
    private static Set readObject() {

        FileInputStream fin = null;
        ObjectInputStream objin = null;
        try {
            File file = new File("HOST_SESSION_HISTORY.ser");
            objin = new ObjectInputStream(new FileInputStream(file));
            while (true) {
                try {
                    HostInfo info = (HostInfo) objin.readObject();
                    HostInfoMap.put(info.getIpaddress(),info);
                } catch (Exception e) {
                    break;
                }

            }
        } catch (IOException e) {

        } finally {
            try {
                if (objin != null)
                    objin.close();
                if (fin != null)
                    fin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return HostInfoMap.keySet();
    }

    public static Set getHostInfos() {
        return readObject();
    }

    public static List getHosts(){
        
        List list = new ArrayList();
        list.addAll(getHostInfos());
        Collections.sort(list);
        return list;
        
    }
    

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

        
        HostInfo info1 = new HostInfo("xxxx", "xx", "xxx", 22);
        HostInfo info2 = new HostInfo("aaaa", "aaaa", "aaa", 22);
        HostInfo info3 = new HostInfo("yyyyy", "yyy", "yyyy", 22);
        
        write(info1);
        write(info2);
        write(info3);
        
        for(String info : getHostInfos()){
            
            System.out.println(info);
            
        }
        
        
        //System.out.println(getHosts());
    }


    public static Map getHostInfoMap() {
        return HostInfoMap;
    }


    public static void setHostInfoMap(Map hostInfoMap) {
        HostInfoMap = hostInfoMap;
    }

}

HostInfo.Java bean which describe host information.


import java.io.Serializable;
import java.util.Stack;

/**
 * @author ajaykumar.gupta
 *
 */

public final class HostInfo implements Serializable,Comparable {

    private static final long serialVersionUID = 6243919138889562890L;

    private String ipaddress;
    private String username;
    private String password;
    private String pwd;
    private Stack cmdList = new Stack();

    private int port;
    

    public HostInfo(String ipaddress, String username, String password, int port) {

        this.ipaddress = ipaddress;
        this.username = username;
        this.password = password;
        this.port = port;
        
        cmdList.add(this.username+"@"+this.ipaddress);

    }

    public String getIpaddress() {
        return ipaddress;
    }

    public void setIpaddress(String ipaddress) {
        this.ipaddress = ipaddress;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Stack getCmdList() {
        return cmdList;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("HostInfo [ipaddress=");
        builder.append(ipaddress);
        builder.append(", username=");
        builder.append(username);
        builder.append(", password=");
        builder.append(password);
        builder.append(", port=");
        builder.append(port);
        builder.append(", pwd=");
        builder.append(pwd);
        builder.append(", cmdList=");
        builder.append(cmdList);
        builder.append("]");
        return builder.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((ipaddress == null) ? 0 : ipaddress.hashCode());
        result = prime * result + port;
        result = prime * result
                + ((username == null) ? 0 : username.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        HostInfo other = (HostInfo) obj;
        if (ipaddress == null) {
            if (other.ipaddress != null)
                return false;
        } else if (!ipaddress.equals(other.ipaddress))
            return false;
        if (port != other.port)
            return false;
        if (username == null) {
            if (other.username != null)
                return false;
        } else if (!username.equals(other.username))
            return false;
        return true;
    }

    @Override
    public int compareTo(HostInfo o) {
        return this.ipaddress.compareTo(o.ipaddress);
    }
    
    
    

}


 

Why SerialVerisonUID is important

Posted on Updated on

Why SerialVerisonUID is important

SerialVersionUID provides a version of Serialization class which is generated SerialVersionUID number base on class details. During deserialization process, it’s verified that sender and receiver of Serialized object version to be matched.

If  a receiver has loaded Serialized Object that has different SVUID than corresponding sender Object then it will throw an exception InvalidClassException during deserialization process.

It would be recommended to generate SerialVersionUID by eclipse or some tools.

What happened If SerialVerisionUID is not provided in Serialized Class

If SVUID is not declared in serialized Class then at run-time, compiler will calculate default serial version id base on class details. which will be defer on different Compiler specialization so it will be not guaranteed to reconstruct Serialized Object then result is unexcepted or Exception like InvalidClassException.

Therefore, to guarantee consistent SerialVersionUID across different Java compiler, it is recommended to declared explicitly SerialVersionUID in Serialization Class.

In this example we will discuss if SerialVersionUID is not implemented in serialized class then what will be happened.

Weather.Java without SerialVersionUID.


import java.io.Serializable;
public class Weather implements Serializable {

private String city;
private String temperature;

public Weather(String city, String temperature) {
this.city = city;
this.temperature = temperature;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getTemperature() {
return temperature;
}

public void setTemperature(String temperature) {
this.temperature = temperature;
}

@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Weather [city=").append(city).append(", temperature=")
.append(temperature).append("]");
return builder.toString();
}

}

Here We persist a serialize Object into file system then read it. It will compile and run successfully.

because compiler generated a SerialVersionUID base on class meta data which is same through serialization and deserialization process therefore weather object is deserialized successful.


public static void main(String args[]) throws IOException, ClassNotFoundException{
Weather weather = new Weather("Delhi","42'C");

FileOutputStream fileToWrite = new FileOutputStream(new File("Weather.out"));
ObjectOutputStream objectToWrite = new ObjectOutputStream(fileToWrite);
objectToWrite.writeObject(weather);

FileInputStream fileToRead = new FileInputStream(new File("Weather.out"));
ObjectInputStream objectToRead = new ObjectInputStream(fileToRead);

System.out.println(objectToRead.readObject());

}

 

Output here :-
Weather [city=Delhi, temperature=42’C]

But suppose if serialized class “Weather” has been changed either it’s properties or SerialVersionUID then at run time compiler will load Serialize class “Weather” and calculate SVUID base on JVM compiler specification  and verify with serialized stream class object “Weather.out”. In this case compiler will found two different SVUID which cause incompatible and then generate exception as below.

Exception in thread “main” java.io.InvalidClassException: Weather; local class incompatible: stream classdesc serialVersionUID = -8353808581004792491, local class serialVersionUID = -5609001311146668266

 Add one property in Weather.java file.
private String location;

then again try to de-serialized or read the serialized Object as below :-

FileInputStream fileToRead = new FileInputStream(new File("Weather.out"));
 ObjectInputStream objectToRead = new ObjectInputStream(fileToRead);
 
 System.out.println(objectToRead.readObject());

output here :-

Exception in thread "main" java.io.InvalidClassException: Weather; local class incompatible: stream classdesc serialVersionUID = -8353808581004792491, local class serialVersionUID = -5609001311146668266
 at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
 at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
 at java.io.ObjectInputStream.readClassDesc(Unknown Source)
 at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
 at java.io.ObjectInputStream.readObject0(Unknown Source)
 at java.io.ObjectInputStream.readObject(Unknown Source)
 at Weather.main(Weather.java:55)