How to exclude properties from serialization

How to Exclude properties from serialization?

As discussed in earlier post Serialization is used to convert states or properties of an Object into byte stream so that we can store the object to disk, share it over the internet or we can persist the state of the object into the database. But sometimes you may want to omit some fields of a class or not to be stored without making any changes in your mechanism to writing or storing the states of the object. In simple words, we can How to exclude properties from serialization?

That’s when the keyword “transient
comes into the picture.

If you want any property of a class not to be serialized just marked it as transient.

Let’s understand it with the help of an example. First, we will create a class UserInfo.java.

import java.io.Serializable;

public class UserInfo implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private String userName;
	private String userType;
	private transient String password;
	
	public UserInfo(){
		super();
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserType() {
		return userType;
	}

	public void setUserType(String userType) {
		this.userType = userType;
	}
 
		return password;
	}

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

	@Override
	public String toString() {
		return "UserInfo [userName=" + userName + ", userType=" + userType + ", password=" + password + "]";
	}
	
}

Create another class TestSerialization.java to read and write the state of objects of UserInfo.java class.

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

public class TestSerialization {

	private final String outputFileName = "userinfo.out";

	public void wirteObject() throws IOException {
		UserInfo userInfo = new UserInfo();
		userInfo.setPassword("test123");
		userInfo.setUserName("codersdesks");
		userInfo.setUserType("TEST");

		FileOutputStream fileOutputStream = new FileOutputStream(outputFileName);
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
		objectOutputStream.writeObject(userInfo);
		System.out.println("Before writting userInfo is :"+userInfo);
		System.out.println("Write object completed");
		objectOutputStream.close();

	}

	public void readObject() throws IOException, ClassNotFoundException {
		FileInputStream fileInputStream = new FileInputStream(outputFileName);
		ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
		UserInfo userInfo = (UserInfo) objectInputStream.readObject();
		System.out.println("After reading UserInfo is :"+userInfo);
		
		objectInputStream.close();
	}

	public static void main(String[] args) {
		TestSerialization t = new TestSerialization();
		try {
			t.wirteObject();
			t.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

Once you run the TestSerialization class the output will be like below.

Before writting userInfo is :UserInfo [userName=codersdesks, userType=TEST, password=test123]
Write object completed

After reading UserInfo is :UserInfo [userName=codersdesks, userType=TEST, password=null]

Here we set the password value into the UserInfo object. But as we have marked the password as transient its value is not stored in the output file, that’s why it is appearing as null.

Recommended Read

Serialization with Externalizable Interface
Serialization in Java using Serializable Interface

Happy Learning !!

Importance of SerialVersionUID in java

In this post, we will discuss the use and importance of SerialVersionUID in serialization.

Serialization is the process of converting a Java object states into a byte stream and does stuff like writing it to disk, sending it over the network.

The serializability of a class is enabled by implementing the java.io.Serializable interface in the class. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable.

According to the Java doc, The serialization run time associates with each serializable class a version number called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible for serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender’s class, then deserialization will result in an InvalidClassException. A serializable class can declare its serialVersionUID explicitly by declaring a field named “serialVersionUID” that must be static, final, and of type long:

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

Here, the serialVersionUID denoted the version of the Java class. You can increase it in case of disallowing backward compatibility with the older version.

See how to serialize an object state with java.io.Serializable.

Let’s check the following example to see the importance of serialVersionUID.

First Create a class Car.java like below.

import java.io.Serializable;

public class Car implements Serializable{

	private static final long serialVersionUID = -656492207873974647L;

	private Integer modelNo;
	
	private String modelName;
	
	private String manufacturer;

	
	public Car() {
		super();
	}


	public Car(Integer modelNo, String modelName, String manufacturer) {
		super();
		this.modelNo = modelNo;
		this.modelName = modelName;
		this.manufacturer = manufacturer;
	}


	@Override
	public String toString() {
		return "Car [modelNo=" + modelNo + ", modelName=" + modelName + ", manufacturer=" + manufacturer + "]";
	}
	
}

Create Class WriteCarState.java to write a Car object.

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class WriteCarState {

	ObjectOutputStream objectOutputStream = null;
	FileOutputStream fileOutputStream = null;
	String outPutFileName = "car.out";
	
	public void writeCarSates(){
		try{
			Car car = new Car(10021,"Neno","Tata");
			fileOutputStream = new FileOutputStream(outPutFileName);
			objectOutputStream = new ObjectOutputStream(fileOutputStream);
			objectOutputStream.writeObject(car);
			System.out.println("car object written successfully with following details");
			System.out.println(car);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		 new WriteCarState().writeCarSates();
	}
}

Create Class ReadCarState.java to read Car Object written by the above class.

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class ReadCarState {

	String outPutFileName = "car.out";
	FileInputStream fileInputStream = null;
	ObjectInputStream objectInputStream = null;
	public void readCarStates(){
		try{
	
			fileInputStream = new FileInputStream(outPutFileName);
			objectInputStream = new ObjectInputStream(fileInputStream);
			Car car = (Car) objectInputStream.readObject();
			System.out.println("car object read successful with following details");
			System.out.println(car);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		new ReadCarState().readCarStates();
	}
}

Run WriteCarState.java class, the output will be:

car object written successfully with following details
Car [modelNo=10021, modelName=Neno, manufacturer=Tata]

Run ReadCarState.java class, the output will be:

car object reads successfully with following details
Car [modelNo=10021, modelName=Neno, manufacturer=Tata]

To see the magic of serialVersionUID run WriteCarState.java class again and the output will be:

car object written successfully with following details
Car [modelNo=10021, modelName=Neno, manufacturer=Tata]

Now modify serialVersionUID in Car.java class to -656492207873974646L from -656492207873974647L and run ReadCarState.java.

You will see the output as

java.io.InvalidClassException: Car; local class incompatible: stream classdesc serialVersionUID = -656492207873974647, local class serialVersionUID = -656492207873974646
	at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:617)
	at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1622)
	at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1517)
	at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
	at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
	at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
	at com.core.serialization.ReadCarState.readCarStates(ReadCarState.java:16)
	at com.core.serialization.ReadCarState.main(ReadCarState.java:25)

The Exception trace

java.io.InvalidClassException: Car; local class incompatible: stream classdesc serialVersionUID = -656492207873974647, local class serialVersionUID = -656492207873974646

Clearly says class Car.java written version is incompatible with the version we are trying to read into.

Recommended Read

Serialization with Externalizable Interface
How to exclude properties from serialization
Serialization in Java using Serializable Interface

Happy Learning !!

Serialization in Java using Serializable Interface

Serialization

Serialization in Java or other programming languages is a process to convert the object state into a byte stream so that the byte stream can be converted into a copy of that object.

Serialization in Java

The ability to store and retrieve Java objects is essential to building all but the most transient applications. The key to storing and retrieving objects in a serialized form is representing the state of objects sufficient to reconstruct the object(s). Objects to be saved in the stream may support either the Serializable or the Externalizable interface.

To read and write object state the class either implements Serializable or Externalizable interface.

Serializable Interface

java.io.Serializable

The Serializable interface has no methods or fields and serves only to identify the semantics of being serializable. That’s why its called marker interface.

Advantages of Serialization

  • Save or Persist state of an object.
  • Transmit an object across the network.

Example of Serialization in Java using Serializable Interface.

Create a class User.java

 

import java.io.Serializable;

public class User implements Serializable{

	private static final long serialVersionUID = -1686914925084201531L;

	private int id;
	private String name;
	private String email;

	public User(int id, String name, String email) {
		super();
		this.id = id;
		this.name = name;
		this.email = email;
	}
	public User() {
		super();
	}
	
	public int getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public String getEmail() {
		return email;
	}
	public void setId(int id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", email=" + email + "]";
	}	
}

Notice we have implemented a Serializable interface in User.java class. Now create a class SerilizationExmple.java to write and read the object of the User class.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerilizationExmple {

	static ObjectOutputStream objectOutputStream = null;
	static ObjectInputStream objectInputStream = null;
	static String outPutFileName = "user.out";

	static FileOutputStream out = null;
	static FileInputStream in = null;
	
	public static void main(String[] args) {
		writeObject(); // call this method to write object state.

		readObject(); // call this method to read object 
	}

	static void writeObject() {
		try {
			User user = new User(1, "Test User", "testuser@xyz.com");
			out = new FileOutputStream(outPutFileName);
			objectOutputStream = new ObjectOutputStream(out);
			objectOutputStream.writeObject(user);
                      System.out.println("User object written successfully");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.flush();
					out.close();
				}
				if (objectOutputStream != null) {
					objectOutputStream.flush();
					objectOutputStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	static void readObject() {
		try{
			in = new FileInputStream(outPutFileName);
			objectInputStream = new ObjectInputStream(in);
			User user = (User) objectInputStream.readObject();
			System.out.println("user object read successful following are the details of user");
			System.out.println(user);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try{
				if(in != null){
					in.close();
				} 
				if(objectInputStream != null){
					objectInputStream.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}

once you run the code snippet, the output will be as below:

User object written successfully
user object read successful following are the details of the user
User [id=1, name=Test User, email=testuser@xyz.com]

Also, notice the first line inside the User.java class.

private static final long serialVersionUID = -1686914925084201531L;

For more detail read the Importance of SerialVersionUID in java

As shown in the example serialization helps us in maintaining the object states using java.io.Serializable interface. But while using serialization remember the points mentioned below.

  • If a parent class has implemented a Serializable interface then child class doesn’t need to implement it but inversely it is not true.
  • Static data members are omitted from Serialization.
  • To omit non-static data member use transient keyword.
  • The constructor of an object is never called when an object is deserialized.
  • Associated objects in a class must implement the Serializable interface.

Recommended Read

Importance of serialVersionUID in Java.

Externalizable Interface

Reference

Serialization in java

Happy Learning !!

Recommended books for programmers

1. Clean Code: A Handbook of Agile Software Craftsmanship
Even bad code can function. But if code isn’t clean, it can bring a development organization to its knees. Every year, countless hours and significant resources are lost because of poorly written code. But it doesn’t have to be that way.

Read this book and see the changes it will bring to the way your write code.

Courtesy: Clean Code

An Introduction to JAX RS Annotations

In This tutorial, we will learn about JAX RS annotations specified in JAX-RS specification. Each available annotation is used for a specific task. Let see the list of Available JAX-RS Annotations.

Annotation Package/Import statement Description
@GET import javax.ws.rs.GET; To retrieve a resource
@POST import javax.ws.rs.POST; To create a new resource
@PUT import javax.ws.rs.PUT; To change the state or update a resource
@DELETE import javax.ws.rs.DELETE; To remove or delete a resource
@HEAD import javax.ws.rs.HEAD; To receive the service header information
@Consumes import javax.ws.rs.Consumes; To define the kind of data service will accept to process
@Produces import javax.ws.rs.Produces; To define the kind of data service will produce after processing
@Path import javax.ws.rs.Path; To Define service URI
@PathParam import javax.ws.rs.PathParam; To extract URI path parameters from request URI
@QueryParam import javax.ws.rs.QueryParam; To extract query parameters from request URI
@FormParam import javax.ws.rs.FormParam; To receive post request form data directly by form filed name

Recommended Read

Rest Web Services
Principles of REST Web Services

REST Hello World Example using Jersey

REST Hello World Example:

In this tutorial, we will develop a simple REST Hello world example web service. Here are the prerequisites.

  1. Jersey-bundle 1.19.4
  2. Tomcat 7
  3. Eclipse IDE
  4. JDK 1.7

Maven Dependencies, you can get it from the Maven repository.

<dependency>
	<groupId>com.sun.jersey</groupId>
	<artifactId>jersey-bundle</artifactId>
	<version>1.19.4</version>
</dependency>

Add Servlet mapping in web.xml

<servlet>
	<servlet-name>jersey-serlvet</servlet-name>
	<servlet-class>
	com.sun.jersey.spi.container.servlet.ServletContainer
	</servlet-class>
	<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
	<servlet-name>jersey-serlvet</servlet-name>
	<url-pattern>/service/*</url-pattern>
</servlet-mapping>

URL pattern “/service/*” means every service URI will start with /service followed by @Path annotation value.

Write HelloService.Java class and create a method helloWorld like.

import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/hello")
public class HelloService {
   @GET
   public String helloWorld(){
     return "Hello World";
   }
}

After completing the above activities right click on Project, go to Run As, and click on 1 Run on Server. Once the server started successfully, open any web browser and type http://localhost:8181/RestDemo/service/hello and press enter. You will see the service response below.

Hello World Response

Notice port 8181, by default Tomcat, runs on port 8080, make sure you use the correct one. We are running it in 8181.

You can download the complete Hello World Example Source Code.

Recommended Read:

Rest Web Services
Principles of REST Web ServicesAccess restriction: The type ‘Resource’ is not API

Happy Learning !!

Principles of REST Web Services

REST Web Services

Although the concept of REST Web Services is written more the one and a half-decade ago, it has not been used much until recent times that the REST web services become so popular and everyone started using them. The major gain in its popularity and uses is because REST architecture offers many advantages over its counterpart. Let’s check out some of its key principles.

1. Resources:

As described in the earlier post everything in REST is a resource. The key to writing a REST resource is that it has to be in the form of the directory structure. Every time while developing a REST web service make sure you expose easily understood directory structure URIs. Resources have data associated with them.

Example of Resources

For example, if you want to expose user data through a REST web service, then you can provide user data in two form either individual user data or all users’ data. In that case, the URI should be like http://yourapplication/{api_version}/users/{user_id}. If the client wants all user data he can exclude user_id from your URI and if clients need specific user data they can pass the user_id.

i.e http://yourapplication/v.01/users – for all Users

http://yourapplication/v.01/users/123 – for User having user-id as 123

2. Representations:

Representations mean the response (JSON/XML) returned by the REST web service should represent data objects and their attributes. In JSON there are three types of data that exist.
A) Scalar (String, Number, Boolean, null) – scalar type has a single value.
B) Object – Object consists of an understood key: value pair ( also called its attributes). While the key is a String and the value can have an arbitrary type.
C) Array – Array contains an ordered list of arbitrary types, can also contain a list of Objects as well.

3. Messages:

The key while developing the REST web service is to use the appropriate HTTP verbs (methods). For example GET, POST, PUT, and DELETE. You can read more about HTTP methods here.

4. Stateless:

Stateless servers do not maintain any information about the client or the user. Each request is fully independent of the previous one. The user or client has to pass all the information in every request even if the server can identify the user based on any allocated id.

5. Media Type:

Mention the type of data the REST web service will consume and produce. In other words kind of data that web service will accept and return. The Accept and Content-Type request headers can be used to describe the content being sent or requested within an HTTP request. The client can set Accept to Application/JSON if the web service it is calling will return a response in JSON.

6. HTTP Status Code:

The status code describes the result of the HTTP request. Below is the list of status codes with their meaning.
A) 1XX – Informational
B) 2XX – Success
C) 3XX – Redirection
D) 4XX – Client Error
E) 5XX – Server Error

Recommended Read:

Rest Web Services
REST Hello World Example

Reference:

Representational state transfer

Happy Learning !!