Monday, June 19, 2017

Singleton Class in Java

Here is the example of complete singleton class which implements Cloenable and Serializable as well.

Read inline java comments for more details

package com.nitesh;

import java.io.Serializable;
/**
 * This class returns singleton Object and tries to handle all possible cases to avoid
 * creating multiple instance of MySingleton Class
 * Following given steps 
 * 1) Created INSTANCE of same class by instantiating class & this INSTANCE should be with private & static modifier
 * 2) Provide public static method that returns same INSTANCE of class every time
 * 3) Create private constructor so that no-one create object from outside of class
 * 4) Providing private constructor helps to suppress creating objects either by new operator/keyword or refection API & newInstance() method
 * 5) Implementing Serializable interface, and override readResolve() method and return same INSTANCE
 * 6) Implementing Cloneable interface and overridden clone() method and throw CloneNotSupportedException();
 *  @author Nitesh.Gupta
 *
 */
public class MySingleton implements Cloneable, Serializable {

private static final long serialVersionUID = 1L;
/**
* Creating a INSTANCE of same class by instantiating class & this INSTANCE should be with private & static modifier
* and with EAGER Loading (creating object using new operator)
*/
private static MySingleton instance = new MySingleton();
/**
* Private constructor to avoid creating instance from outside class.
* Moreover, checking object reference if someone tries to create object using reflection.
*/
private MySingleton() {
if (instance == null) {
throw new IllegalStateException();
}
}
/**
* Static method for returning single object of MySingleton Object 
* @return Object of MySingleton
*/
public static MySingleton getInstance() {
return instance;
}
/**
* ReadResolve method to avoid creating new instance in case of De-serialization 
* @return same object
*/
public Object readResolve() {
return getInstance();
}
/**
* Overriding clone method throwing CloneNotSupportedException exception if 
* someone tries to clone this class
*/
@Override
protected Object clone() throws CloneNotSupportedException {

throw new CloneNotSupportedException();

}
}

Java Thread Example

In this example, Five Threads are being invoked which takes input as Integer and prepare table. Also, Used some of methods like Sleep and isInterrupted to understand its uses.

package test;
/**
 * MyThread2 class which creates thread by extending Thread Class
 * @author Nitesh.Gupta
 */
public class MyThread2 extends Thread {
/**
* Initializing count with 1
*/
private int count=1;
/**
* MyThread constructor which takes an input and assign it to class level variable
* @param count
*/
MyThread2 (int count){
this.count = count;
}
/**
* Run method which gets executed as soon as thread.run called.
*/
@Override
public void run() {
calculateTable();
}
/**
* Helper method for calucalting table
*/
private void calculateTable() {
System.out.println("Thread started:::"+Thread.currentThread().getName());
for (int i=1; i<=10 ; i++){
int counting = i * count;
System.out.println("Table of " + i + " Prepared by Thread "+this.getId() +" Name "+this.getName());
System.out.println("Count of " + count + "*" + i + "=" +counting);
}
}
public static void main (String str[]) throws InterruptedException{
for (int k=1; k<5 font="" k="">
Thread.sleep(1000);
MyThread2 t1 = new MyThread2(k);
t1.start();
//IsInterrupted method to check if thread is interrupted in between or not
if (t1.isInterrupted()){
throw new InterruptedException();
}
}
}
}

Friday, March 17, 2017

Swagger 2 Configurations for documenting Spring web REST services with and without Security settings


Swagger is a specification and complete framework implementation for describing, producing, consuming, and visualizing RESTful web services. The goal of Swagger is to enable client and documentation systems to update at the same pace as the server. The documentation of methods, parameters, and models are tightly integrated into the server code, allowing APIs to always stay in sync.

Part 1 - Swagger Configuration without Authentication 


Step 1 - Adding Maven dependency in Pom.xml

Pom.xml












It will download all required jars for documentation and respective Swagger UI.

Step 2 - Integration of Swagger2 in project


a) Use the EnableSwagger2 annotation on your MVCconfiguration file
b) Add Resource Handlers for Swagger UI in Mvc Configuration file








c) Write your Swagger Configuration file (SwaggerConfig.java) and give reference in main configuration file 




d) If your project implements Spring security then you will have to by pass the security for swagger ui components

1) Add swgger related url patterns in web ignoring list. 



2) Authorize Swaggar related URL patterns.
@Overrideprotected void configure(HttpSecurity http) throws Exception {

  http.authorizeRequests()    
 .antMatchers("/webjars/**","/configuration/**","/swagger-resources/**","/v2/api-docs/**", "/swagger-ui.html").access("permitAll") // Allow all users to access these urls. 
}

After doing all configuration start the server and verify if you are able see swagger ui by hitting below url

http://localhost:8080/test/swagger-ui.html

It should list all your exposed services which are annotated with @RestController. you can also change this by setting Request Handler Selector.

Part 2 - Swagger Configuration with Authentication - 

To achieve security, you need to do few more steps top of what we did in part 1 of this blog 

1) Set Security Settings in SwaggerConfig




2) Updating Security Config.java



Write custom filter and add into HttpSecurity

3) Custom Filter for authenticating user. However, you can write your own implementation and authenticate request coming from SWAGGER UI.





























Wednesday, September 2, 2015

RDBMS vs NoSQL

Nice article. So rather writing it from scratch. I thought sharing this with everyone. RDBMS vs NoSQL

Thursday, August 27, 2015

Composition vs Inheritance in OOPS

Composition - Having a Has-A relationship and simply uses instance variable that are references of other objects.
Inheritance - Having IS-A relationship and simply access state and behaviour of other object by inheriting it. 

Ex. Hyundai is-A Car (Inheritance) Has-A Engine (Composition)


 Properties
Inheritance
Composition
Flexibility
When you use Inheritance, you have to define which class you are extending in code; it cannot be changed at runtime. 
Composition you just define a Type which you want to use, which can hold its different implementation.
Code Reuse
Inheritance you can only extend one class, which means you code can only reuse just one class, not more than one. 
If you want to leverage functionalities from multiple classes, you must use Composition.
Unit Testing
When you design your class using Inheritance, you must need parent class in order to test child class. There is no way you can provide mock implementation of parent class.
When you design classes using Composition they are easier to test because you can supply mock implementation of the classes you are using
Final Classes
You cannot inherit final classes, hence you cannot reuse code of final class
Composition allows code reuse even from final classes
Encapsulation
Inheritance breaks encapsulation because in case of Inheritance, sub class is dependent upon super class behaviour. If parent classes changes its behaviour than child class is also get affected. If classes are not properly documented and child class has not used the super class in a way it should be used, any change in super class can break functionality in sub class.
Composition doesn't break encapsulation.If main class changes its behaviour then calling class doesn't get affected. 

  • Don't use inheritance just to get code reuse If all you really want is to reuse code and there is no is-a relationship in sight, use composition.
  • Don't use inheritance just to get at polymorphism If all you really want is polymorphism, but there is no natural is-a relationship, use composition with interfaces.

Wednesday, August 5, 2015

Singleton object creation

1 ) Singleton with eager loading

import java.io.Serializable;
import java.lang.reflect.Constructor;

public class SingletonTest implements Serializable {

private static final long serialVersionUID = 5287483952638645154L;
private final static SingletonTest INSTANCE = new SingletonTest();

private SingletonTest() {
if (INSTANCE != null) {
throw new IllegalStateException("Inside SingletonTest(): SingletonTest " + "instance already created.");
}
System.out.println("Inside SingletonTest(): Singleton instance is being created.");
}

public static SingletonTest getInstance() {
return INSTANCE;
}

@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

// This method is called immediately after an object of this class is
// deserialized.
protected Object readResolve() {
// Instead of the object we’re on, return the class variable singleton
return INSTANCE;
}
}

To test this use given main method

public static void main(String[] args) {
//System.out.println(SingletonEnum.INSTANCE);
try {
System.out.println("Inside main(): Getting the singleton instance using getInstance()...");
System.out.println(SingletonTest.getInstance());
Class clazz = SingletonTest.class;
Constructor cons = clazz.getDeclaredConstructor();
cons.setAccessible(true);
SingletonTest s2 = cons.newInstance();
System.out.println(s2);

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

2) Singleton with Lazy Loading
package com;

public class SingletonLazy {
private SingletonLazy() {
}
private static SingletonLazy INSTANCE = null;
public static SingletonLazy getInstance() {
if (INSTANCE == null) {
synchronized (SingletonLazy.class) {
if (INSTANCE == null) {
INSTANCE = new SingletonLazy();
}
}
}
return INSTANCE;
}
}

3) Singleton with Enum
public enum SingletonEnum {
INSTANCE;

private SingletonEnum() {
System.out.println("Here");
}
}

How to create Immutable Class in java

The following rules define a simple strategy for creating immutable objects. Not all classes documented as "immutable" follow these rules. This does not necessarily mean the creators of these classes were sloppy — they may have good reason for believing that instances of their classes never change after construction. However, such strategies require sophisticated analysis and are not for beginners.
1.    Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
2.    Make all fields final and private.
3.    Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
4.    If the instance fields include references to mutable objects, don't allow those objects to be changed:
o    Don't provide methods that modify the mutable objects.
o    Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.


You can still create immutable object by violating few rules, like String has its hash code in non-final field, but it’s always guaranteed to be same. No matter how many times you calculate it, because it’s calculated from final fields, which is guaranteed to be same. This required a deep knowledge of Java memory model, and can create subtle race conditions if not addressed properly. In next section we will see simple example of writing immutable class in Java. By the way, if your Immutable class has lots of optional and mandatory fields, then you can also use Builder design pattern to make a class Immutable in Java.

How to create immutable object