Category Archives: Java

Java 8 Stream API

Why Streams

  • If you are looping collection to run specific operation, streams is the solution
  • Process computations on large collections with less code, in parallel and efficiently

Streams

  • Stream is like pipeline of sequence of elements from a source (e.g. collections) that supports aggregate operations (e.g. filter, map, reduce, find, sorted, match)
  • Most of Stream operations returns Stream. Therefore multiple operations can be chained
  • Stream library uses internal iteration during on demand computation

Example

Extract even numbers; times 2 each; and order in descending order
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
List<Integer> computedNumbers = numbers.stream()
		.filter(n -> {
			return n % 2 == 0;
			})
		.map(n -> {
			System.out.println("mapping " + n);
			return n * 2;
			})
		.sorted((a, b) -> b.compareTo(a))
		.collect(Collectors.toList());
System.out.println(computedNumbers);

Output
mapping 2
mapping 4
mapping 6
mapping 8
[16, 12, 8, 4]
  • stream() makes pipeline
  • .filter(Predicate<?>) extracts according to Lambda expression and returns Stream
  • .sorted(Predicate<?>) sorts according to Comparator provided as Lambda expression
  • Finally, used collect to retrieve as List. It is one of terminal operation used to close Stream pipeline

Resources

Lambda Expressions in Java 8

Functional Interface

  • A functional interface is any interface that contains only one abstract method
  • It may contain extra default or static methods

 Lambda Expressions

    • Treat functionality as method argument
    • It adds Functional behaviour to Java
    • It is basically an implementation of single abstract method in functional interface
    • Lambda expressions is preferred over Anonymous classes because later is bulky
    • JDK also has predefined standard Functional Interfaces e.g. Predicate

Example

Java predefined generic Predicate Interface (Functional Interface)

interface Predicate<T> {
    boolean test(T t);
}
  • Below method accepts Functional interface as input (Predicate in this case)
  • It then invokes one and only abstract method defined in the interface (test in this case)
  • Implementation of this abstract method is given by Lambda expression in following section
public static void displayStudentsOnCondition(
    // Predicate is generic interface
    List<Student> students, Predicate<Student> condition) {
    for (Student s : students) {
        // test method is declared in Predicate interface
        if (condition.test(s)) {
            System.out.println(s.toString());
        }
    }
}
  • Lambda expression is passed as parameter
  • Implementation of single abstract method in the functional interface is provided in Lambda expression
  • Arguments provided in the lambda expression are basically arguments to functional interface method (Predicate test in this case)
displayStudentsOnCondition(
    students,
    p -> p.getGender() == Person.Sex.MALE
        && p.getAge() >= 18
        && p.getAge() <= 25
)

Resources

Generics in Java

Generics

  • Introduced in JDK 1.5
  • Provide compile-time type safety
  • Enable developer to declare generic class or method

Some problems solved by Generics

Problem 1 – No compile-time safety

List list = new ArrayList();
list.add("oneness");
Integer i = (Integer)list.get(0); // throws run time ClassCastException
  • Generics provides compile-time safety and avoid run time errors like above
List<String> list = new ArrayList<>();
list.add("oneness");
// compile-time error Cannot cast from String to Integer
Integer i = (Integer) list.get(0);

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

 

What is the difference between an interface and abstract class?

What is the difference between an interface and abstract class?

Similarities

  • You cannot instantiate them
  • They may contain a mix of methods declared with or without an implementation

Differences

Interface abstract class
All fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public Can declare fields that are not static and final, and define public, protected, and private concrete methods
Can implement number of interfaces Can extend only one class, whether or not it is abstract,

Resources:
Abstract Classes Compared to Interfaces

JAX WS - Java API for XML Web Services

JAX WS – Java API for XML Web Services

JAX WS – Java API for XML Web Services

  • Simpler way to develop/deploy Web Services
  • Server & clients communicate using XML
  • Can be invoked by XML-based protocol (e.g. SOAP) & messages (xml) can be transported over HTTP

service endpoint interface or service endpoint implementation (SEI) is a Java interface or class, respectively, that declares the methods that a client can invoke on the service. An interface is not required when building a JAX-WS endpoint. The web service implementation class implicitly defines an SEI.

JAX-WS client programming model 

  1. Dispatch client: work at the XML message level; work without any generated artifacts at the JAX-WS level.
  2. Dynamic Proxy client: invoke a web service based on a service endpoint interface.

wsimport tool

The wsimport tool generates JAX-WS portable artifacts, such as:

  • Service Endpoint Interface (SEI)
  • Service
  • Exception class mapped from wsdl:fault (if any)
  • Async Reponse Bean derived from response wsdl:message (if any)
  • JAXB generated value types (mapped java classes from schema types)

FAQ

  • How to generate JAX-WS artifacts of secure WSDL using wsimport?

Following command will generate the webservice artifacts of the given wsdl and copy into directory (directoryName)

wsimport -keep -d directoryName -verbose -Xnocompile -Xauthfile authFile.txt <WSDL URL>

Content of authFile.txt

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

Resources

  1. JAX WS official site
  2. JAX-WS Release Documentation 2.2.8  (PDF, HTML)
  3. Building Web Services with JAX-WS (javaee 6)
  4. wsimport tool documentation