Java Object Serialization

Java Object Serialization

Introduction

  • Mechanism where an object can be converted to a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object
  • Object can be serialized and stored in a file, later it can be deserialized to form an object
  • It is JVM independent. An object can be serialized in one platform and deserialized in other platform

Purpose of Serialization

Communication: Object can be serialized and transmitted to other machine over the network. it can be deserialized on other machine.

Persistence: If you want to store the state of a particular operation in a database, it can be easily serialized to a byte array, and stored in the database for later retrieval.

Cross JVM Synchronization: Serialization works across different JVMs that may be running on different architectures.

Conditions for a class to be serializable

  • The class must implement the java.io.Serializable interface or inherit that implementation from its object hierarchy
  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Transiet

A field marked as transient is not serializable. It is typically used for fields that would be irrelevant when the object is unserialized, or fields that would be less-than-safe to store e.g. passwords, decrypted data etc.

serialVersionUID

  • The serialization runtime 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 with respect to 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 own 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;
  • If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java Object Serialization Specification.
  • However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.

Serialization Example

Serializable class – implementing  java.io.Serializable interface

package manvirbasra.com.serialization;

import java.io.Serializable;

public class Person implements Serializable {

	private static final long serialVersionUID = 6653705525140553845L;
	public String name;
	public String address;
	public transient int SIN;

}

Serialization Example

package manvirbasra.com.serialization;

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

public class SerializationExample {

	public static void main(String[] args) {
		Person p = new Person();
		p.name = "Manvir Basra";
		p.address = "Wall Street";
		p.SIN = 987654321;

		FileOutputStream fileOut = null;
		ObjectOutputStream out = null;
		try {
			fileOut = new FileOutputStream("/Users/manvirbasra/Desktop/temp/Person.ser");
			out = new ObjectOutputStream(fileOut);
                        //Serialization occurs at this line
			out.writeObject(p);
			System.out.println("Object serialized to file");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				fileOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

}

De Serialization Example

package manvirbasra.com.serialization;

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

public class DeSerializationExample {

	public static void main(String[] args) {
		Person p = null;
		try {
			FileInputStream fileIn = new FileInputStream("/Users/manvirbasra/Desktop/temp/Person.ser");
			ObjectInputStream in = new ObjectInputStream(fileIn);
                        //De Serialization occurs at this line
			p = (Person) in.readObject();
			in.close();
			fileIn.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("Person class not found");
			e.printStackTrace();
		}

		System.out.println("Deserialized class...");
		System.out.println("Name: " + p.name);
		System.out.println("Address: " + p.address);
		System.out.println("SIN: " + p.SIN);

	}

}

FAQ

1. Can child class be Serializable if parent class is not Serializable?

 

Resources

 

Elastic Search

 ElasticSearch

  • Open  Source Distributed and Highly Available Search Engine (multitenant)
  • Built in Java
  • Distributed RESTful search engine
  • REST/JSON based and has native Java API
  • Document oriented and schema free (no need for upfront schema)
  • Built on top of Lucene
  • capable of full text search, filters, highlight, sorting, pagination, suggestions
  • Extensible ecosystem – Can create custom plugins to extend functionality (e.g. aggregation functions, analyzers) , has clients for many languages (java, python, javascript), integrate with Kibana (graphical overview of data) , Logstash, hadoop

Terminology

  1. NRT (Near Realtime) – There is slight delay (~1s) when document is indexed and becomes searchable
  2. Cluster – collection of nodes. Each cluster has unique name (default-elasticsearch)
  3. Node – single server part of cluster, has unique name
  4. Index – collection of documents with similar characteristics (fields)
  5. Type – logical category of index. Type is defined for documents which has similar fields. e.g. in blog – post data, comment data, user data
  6. Document – basic unit of information that can be indexed – json format
  7. Shards (Sharding – Data partitioning) – subdivide index to multiple pieces called shards. Each shard is independent index and can be hosted on any node in the cluster. Split logical data over several machines  – write scalability – control data flows
  8. Replica shard (Data duplication) – copy of shard for failover & scaling purposes (search can be executes in all replicas in parallel) – read scalability – removing single point of failure (SPOF)

Concept – Distributed

  1. first screen – shard and replica contract setup during index creation
  2. On firing second node, it will look like second screen – green background are primary shards where data get indexed first and then to replica shards
  3. On firing third node, it will look like third screen

Screen 1

distributed

Screen 2

distributed-2

Screen 3

distributed-3

Advanced Concepts

Resources

  1. https://www.elastic.co/ [Blog]
  2. Elastic Search
  3. Elastic Search Reference
  4. Github elastic search
  5. Elastic Search Guide [ Elastic Search Definite Guide]
  6. Elastic Search Java API
  7. Book – Elastic search definite guide
  8. Plugins  [Writing Custom plugins]
  9. Luke

JUnit – Unit testing framework for Java

JUnit

  • Unit testing framework for Java
  • package org.junit for JUnit 4 and later

JUnit 4 Usage and Idioms

Links

JUnit 5 Links

Servlets and JSP

Why Servlets?

Servlets play the role of a helper app in the web server. It is preferred because of performance where server has to launch a heavy-weight process for each and every request for that resource.

Servlets

  • Servlets should be deployed to Web Container (Servlet Container e.g. Tomcat)

Web Container (Servlet Container)

  • Responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights

Servlet Lifecycle

  • There is single instance of Servlet per JVM instance. The classes are loaded and servlet object is created during container boot up which lives during the whole JVM lifecycle
  • init method is called by container to initialize servlet instance. ServletConfig can be passed to customize servlet at run time. init method can be used to costly operations e.g. create JDBC connection or anything that need to be performed one time.
  • For every request, container creates new HTTPServletRequest/HTTPServletResponse (in case of HTTPServlet) and every request do have separate thread
  • service method is responsible for calling doGet/doPost methods (HTTPServlet)
  • destroy method is called when servlet object is destroyed

Servlet API

  • Servlet API contained in the Java package hierarchy javax.servlet
  • The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements

Resources

Spring Framework

Spring Framework

  • Lightweight ( Spring apps do not require JEE application server)
  • Spring serves as Container for application objects (serves as lifecycle manager)
  • Open Source Application Framework (provides framework classes to simplify working with lower-level technologies)
  • Inversion of Control Container for Java platform

Spring Framework Modules

Spring Framework Modules

  1. Spring Core Container
  2. Aspect Oriented Programming (AOP)
  3. Authentication and Authorization
  4. Convention over Configuration
  5. Data Access
  6. Inversion of Control Container
  7. Messaging
  8. Model View Controller (MVC)
  9. Remote Access Framework
  10. Transaction Management
  11. Remote Management
  12. Testing

Core Container

Consist of spring-core, spring-beans, spring-context, spring-context-support and spring-expression

Resources

Design Patterns

Design Patterns

Factory Pattern

Problem

  • Client does not know which class to instantiate when there are multiple implementations available (in case of interface/abstract class)

Solution

  • Client passes information about object
  • Based on client information, Factory instantiates specific class (concrete) and returns the object

Example

  • There is Pizza abstract class
  • CheesePizza extends Pizza
  • VeggiePizza extends Pizza
  • PizzaFactory has method Pizza createPizza(String type). If client enters “cheese”, factory will return instance of CheesePizza

AbstractFactoryPattern

Abstract Factory Pattern
Image src Youtube

Gang of Four

Factory

  • Creates various instances based upon input

Singleton

  • Creates at most one instance

Façade

  • Provides a simplified interface to complex logic

Iterator

  • Process all elements in a collection without knowing the elements’ type
Iterator Pattern

Benefits

  • Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
  • Use the Iterator pattern to process all elements in a collection without regards to the elements’ type
  • Polymorphic traversal (iteration)
  • This pattern supports the Single Responsibility principle and facilitate high cohesion, which is a measure of how closely a class or module supports a single purpose or responsibility.

    Liabilities

    Structure

    Structure of the Iterator Pattern

    Resources

Observer Pattern

Summary

  • Also known as Publisher Subscriber
Singleton Pattern

Summary

  • Ensures that there is one and only one instance of a class in existence at any point in time

Solution

  • Singleton class itself is responsible for creating its own instance, no other class should be allowed

Java Implementation

  • Instance variable – private static final instance = DefaultConstructor()
  • Mark constructor private
  • Define public static getInstance() method to return instance

Building Dojo Toolkit

Basics

  • Build system for JavaScript resources and CSS files
  • Dojo build refers to concept to the concepts of minification, optimization, concatenation and “dead-code” removal.

Building Dojo Toolkit Involves

  1. Consolidates multiple modules into a single JavaScript file (Layer)
  2. Interns standalone template strings into Javascript files
  3. Minify the size of layers by removing white spaces, line breaks, comments and shortening variable names
  4. Copy build files to standalone directory (server deployable ready)

Resources

How to enable HTTP raw log monitor in JBoss

How to enable HTTP raw log monitor in JBoss?

Steps

  1. Go to <JBOSS_SERVER_DIRECTORY>/deploy/jbossweb.sar/server.xml
  2. Uncomment Access logger<!– Access logger –><Valve className=”org.apache.catalina.valves.AccessLogValve”
    prefix=”localhost_access_log.” suffix=”.log”
    pattern=”common” directory=”${jboss.server.log.dir}”
    resolveHosts=”false” />

Secure wsdl client artifacts using wsimport and jax ws client

Q: How to create client artifacts (value objects and other service class methods etc) of secure resource (WSDL) using wsimport?

Solution: Use following command to generate artifacts in given directory. Make sure to put authFile.txt file at current path.

wsimport -keep -d <DirectoryName> -verbose -Xnocompile -Xauthfile authFile.txt <WSDL_URL>

Content of authFile.txt

http://username:password@hostname/path?WSDL

 


 

Q: How to create JAX WS client where WSDL is secure and API is also secure? 

Solution: There will be authentication at two layers.

1) HTTP Layer
2) Method Layer (API)

Here is the sample.

public class JaxWsClientSample {

	// HTTP Authentication
	static {

		java.net.Authenticator.setDefault(new java.net.Authenticator() {

			@Override
			protected java.net.PasswordAuthentication getPasswordAuthentication() {
				return new java.net.PasswordAuthentication("username",
						"password".toCharArray());
			}
		});
	}

	public static void main(String[] args) {

		// Create service object and get port
		// Note: TestBean_Service is service class that can be found in 
// generated client artifacts and name may be different in your case
		TestBean_Service service = new TestBean_Service();
		TestBean port = service.getTestBeanPort();

		//Use BindingProvider API to provide credentials for API security
		BindingProvider prov = (BindingProvider) port;
		Map<String, Object> reqCtx = prov.getRequestContext();

		// API credentials
		reqCtx.put(BindingProvider.USERNAME_PROPERTY, "username");
		reqCtx.put(BindingProvider.PASSWORD_PROPERTY, "password");
		reqCtx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
				"http://hostname/path/TestBean?");

		// Invoke webservice method through port
		Response response = port.doSomething(request);

	}

}

Resources: