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

 

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