Friday, July 24, 2015

Getting different objects from Jackson

Hello All, today I want to explain you a special case when we want to get different objects from Jackson Library.

What is Jackson API and how it works?
     It is a standard JSON library for Java (or JVM platform in general), or, as the "best JSON parser for Java". Or simply as "JSON for Java". It is very useful and flexiblt in nature. It takes JSON string in to consideration and changes it to Java object or vice versa.

What is a JSON string?
    JSON is a special format of representing the data in a string format, you can think it as a refined version of XML.

Eg:
    In XML:
        <user>
            <author>Ankur</author>
            <name>Codepool</name>
         </user>
    In JSON:
        user:{
                "author" : "Ankur",
                "name" : "Codepool",
        }
     

Now before going further lets us take a basic example of how Jackson works to and forth?

User.java
public class User {
    private String name;
    private String author;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", author=" + author + "]";
    }
}

ExampleJackson.java
public class ExampleJackson {
    public static void main(String[] args) throws Exception {
        User user = new User();
            user.setName("Ankur");
            user.setAuthor("Codepool");

        //Writing a Java object as a Json String
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(objectMapper.writeValueAsString(user));
        //Output: {"name":"Ankur","author":"Codepool"}

        //Now reading from Json string to Java object
        String jsonString = "{\"name\":\"NewAnkur\", \"author\":\"NewAuthor\" }";
        User newUser = objectMapper.readValue(jsonString, User.class);
        System.out.println(newUser);
        //Output: User [name=NewAnkur, author=NewAuthor]
    }
}

Now let us take a case, where we want to get the object on the basis of data inside the JSON string, that means if the name value is Ankur, I want AnkurUser object and if name value is John, we want the JohnUser object.

For this type of functionality we have the annotations defined in Jackson library, those are :
  • @JsonTypeInfo
  • @JsonSubTypes
  • @JsonSubTypes.Type
Now lets edit the User class in a way like this:

User.java
@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "name", // (A)
    visible = true  // (B)
)
@JsonSubTypes( {
    @JsonSubTypes.Type(name = "ankur", value = AnkurUser.class), //(C)
    @JsonSubTypes.Type(name = "john", value = JohnUser.class)  //(D)
})
abstract class User {
    private String name;
    private String author;
    protected abstract void show();

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", author=" + author + "]";
    }
}

AnkurUser.java
class AnkurUser extends User{

 public AnkurUser(){
   System.out.println("Ankur Created");
  }
  @Override
 protected void show() {
  System.out.println("This is ankur user");
 }

 @Override
  public String toString() {
   return "AnkurUser [name=" + super.getName() + ", author=" + super.getAuthor() + "]";
  }
}

JohnUser.java
class JohnUser extends User {
    public AnkurUser() {
        System.out.println("Ankur Created");
    }
    @Override protected void show() {
        System.out.println("This is john user");
    }
    @Override
    public String toString() {
        return "JohnUser [name=" + super.getName() + ", author=" + super.getAuthor() + "]";
    }
}
Now lets see the usage and output:

ExampleJackson .java
public class ExampleJackson {
    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();

        //Now reading from Json string to Java object
        String jsonString = "{\"name\":\"ankur\", \"author\":\"NewAuthor\" }";
        User newUser = objectMapper.readValue(jsonString, User.class);
        newUser.show();
        /*
        * Output: (E)
        *  Ankur Created
        *  This is ankur user
        */
    }
}

If you notice the equation (C) tells you that the object that is created, is of AnkurUser class and returns you the same, this transition is because of the annotation configuration that we did at the creation of the User class, which says check for the property named name (equation (A)), and if its value is Ankur  create the AnkurUser object and so on, at equation (C) and (D). The equation (B) states that the field is also going to be visible for further calls  normally the field that is used as a deciding factor of the object, is never visible for further manipulations.

Thanks

Wednesday, July 15, 2015

Singleton pattern exposed

Hello all, today I want to focus your focus on one of the most debatable topic that is Singleton Design Pattern.

First of all let me tell you what Design Patter means.

Design Pattern
  1. In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into source or machine code.  Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers. The idea of Design patterns are introduced by four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides in a book titled Design Patterns - Elements of Reusable Object-Oriented Software in  1994,  
For further more information regarding design patterns you can follow this. But anyhow for an information, Design Patterns are divided in 4 categories:
  1. Creational Pattern
  2. Structural Patterns
  3. Behavioral Patterns
  4. J2EE Patterns
Now there are number of patterns in each of these. Singleton pattern comes under Creational Pattern.

The basic idea of Singleton Pattern is that the instance of the class should be unique across a JRE. We can actually think of it as the same object (achieved with some code), and reusing it every time any class wants to use it.

Lets take a look what are the conditions that one must have to follow while creating a Singleton Class:
  1. Private Constructor
        
    This is required to make sure that any other party can't create the object of it
  2. One private instance of itself
        Since we want to have only one object in to existence, only one instance of it is to be created and that too be private in nature.
  3. One public static method to return the private variable
        This is required since the variable is private and constructor is private so in order to get the reference of the variable we must provide a public static method.
Before proceeding further let me tell you the devils that may haunt you if didn't taken care of:
  • Thread Safe Promise
  • Serialization Promise
  • Our class code can't be punctured via Reflections of Java
A very basic example of singleton pattern is this:
public class BasicSingleton {
    private static final BasicSingleton instance = new BasicSingleton();//->(A)
   //private constructor to avoid client applications to use constructor
    private BasicSingleton() {}
    public static BasicSingleton getInstance() {
        return instance;
    }
}


   
  
Now this class's object creation is not possible since the constructor is private in nature and it will restrict its usage from outside world.
For using the BasicSingleton class you have to call the method(static), getInstance() and use it when required:

...BasicSingleton basicSingleton = BasicSingleton.getInstance();
Pros:
  • This approach is pretty straight forward and easy to use 
  • Very useful if object is light in nature. 
Cons:
  • In this object creation is eager in nature. If you see, step marked (A),  you find that the object is being created the time class comes in  existence , this approach makes one unused object even we never uses the object.
  • Also we didn't used any 
Now since we understood the basic nature of the pattern let us take a look what are the different ways one can create the singleton objects:
  1. Eager Creation of the object
  2. Lazy Creation of the object
  3. Static block usage for object creation
  4. Thread safe creation of the object
  5. Reflection for object creation
  6. Enum singleton
  7. Serialization with Singleton
Eager Creation of the object:
    This is by far the simplest of all the ways.

public class SingletonEager {
    private static final SingletonEager instance = new SingletonEager();
    private SingletonEager() {}
    public static SingletonEager getInstance() {
        return instance;
    }
}

  Pros:
   
   
  1. Easy to use.
  2. Useful when the resource to be singletonized is pretty light in nature.
  Cons
  1. Can't do exception handling as the object is created with the declaration
Lazy Creation of the object
    It is also very simple in nature. The only difference is that in this we can actually take exception handling also in the consideration.

public class SingletonLazy {
    private static SingletonLazy instance = null;
    private SingletonLazy() {}
    public static SingletonLazy getInstance() {
        if (instance == null)
            instance = new SingletonLazy();
        return instance;
    }
}
  Pros
  1. Easy to handle and easy to use
  2. Can use the exceptional handling checks as well
  Cons
  1. Not a thread safe option
Static block usage for object creation

public class StaticBlockSingleton {
    private static StaticBlockSingleton instance = null;
    private StaticBlockSingleton() {}
    static {
        try {
            instance = new StaticBlockSingleton();
        }
        catch (Exception ex) {
            //handle the exception if got
        }
    }
}
   Pros
  1. Both eager and static block creates the instance before it being used and its ok if the object is light in nature
  2. Gives you the power of exceptional handling
   Cons
  1. Not a thread safe option
Thread safe creation of the object

public class ThreadSafeSingleton {
    private static ThreadSafeSingleton instance = null;
    private ThreadSafeSingleton() {}
    public static synchronized ThreadSafeSingleton getInstance() {
        if (instance == null) {
            instance = new ThreadSafeSingleton();
        }
        return instance;
    }
}

This method is useful in handling the thread safety of the singleton object but it is quite heavy on performances, which we can avoid via double checking null and synchronizing the block of creation like this:

public class  LightThreadSafeSingleton {
    private static LightThreadSafeSingleton instance = null;
    private LightThreadSafeSingleton() {}
    public static LightThreadSafeSingleton getInstance() {
        if (instance == null) {
            synchronized(LightThreadSafeSingleton.class) {
                if (instance == null) {
instance = new LightThreadSafeSingleton();
                }
            }
        }
    }
}

Reflection for object creation

    What is a Reflection in Java?
        Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.(Source)

    Now with the help of Reflection we can actually see in the classes at Runtime, I am not going to go deep in that because if I do it will take lots of time. Lets take an example where we can actually break the Singleton pattern via Reflection API of Java.

public class ReflectionSingletonTest {
    public static void main(String args[]) {
        ReflectionSingleton_Inner instance1 = ReflectionSingleton_Inner.getInstance();
        ReflectionSingleton_Inner instance2 = null;
        try {
            Constructor[] constructors = ReflectionSingleton_Inner.class.getDeclaredConstructors();
for (Constructor cons : constructors) {
                cons.setAccessible(true);
                instance2 = (ReflectionSingleton_Inner)cons.newInstance();;
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();

        }
        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }
}
class ReflectionSingleton_Inner {
    private static final ReflectionSingleton_Inner instance = new ReflectionSingleton_Inner();
    private ReflectionSingleton_Inner() {}
    public static ReflectionSingleton_Inner getInstance() {
        return instance;
    }
}

This is pretty simple example of using Reflection to break the singleton nature of the code.

Now comes the most awaited portion of the discussion that is the Enum singleton.

Enum Singleton
     Lets take an example :

enum EnumSingleton{
        //this is the instance of the EnumSingleton which is Thread Safe, Reflection Safe and with no Performance issue
INSTANCE;


private EnumSingleton(){}
}

This is basic example lets take a look with one String variable inside the enum;

enum EnumSingleton{
INSTANCE;

private final String privateString; 
private EnumSingleton(){
privateString = "I am private String";
}
public String getPrivateString(){
return privateString;
}

public void displayEnumSingleton(){
System.out.println("I am displayenumsingleton");
}
}

Usage:

public class EnumSingletonTest{
public static void main(String[] args) {
                System.out.println(EnumSingleton.INSTANCE.getPrivateString());
EnumSingleton.INSTANCE.displayEnumSingleton();
}
}

Now the question may arise in your mind that, ok I used the enum to achieve the singleton pattern but we can still use the Reflection API to create the multiple objects of it, right?

Well the answer is no, and here is the code with the output:

public class EnumSingletonTest{
public static void main(String[] args) {
EnumSingleton instance1 = EnumSingleton.INSTANCE;
EnumSingleton instance2 = null;

try{
Constructor[] constructors = EnumSingleton.class.getDeclaredConstructors();
for(Constructor cons : constructors){
cons.setAccessible(true);
instance2 = (EnumSingleton)cons.newInstance();;
}
}catch(Exception ex){
ex.printStackTrace();
}
System.out.println(instance1 == instance2);
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());
}
}

Output
java.lang.IllegalArgumentException: Cannot reflectively create enum objects.

The output clearly says that you can't create the objects of the Enum, which made it Reflection Safe. Also for being thread safe I have already told you that Java itself makes the Enum objects thread safe.

Serialization with Singleton
   Java provides a mechanism, called object serialization where an object can be represented as 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.

let's take an example:

class SerializedSingleton implements Serializable{
private static final SerializedSingleton instance = new SerializedSingleton();
private SerializedSingleton(){}
public static SerializedSingleton getInstance(){
return instance;
}
}

Now the serialization code with the Singleton part:

public class SerializedSingletonMain {
public static void main(String args[]) throws Exception{

SerializedSingleton firstInstance = SerializedSingleton.getInstance();
SerializedSingleton secondInstance = null;
String fileName = "E://dummy.dat";

//Now we will write instanceOne in a file and read it back using Serialization

//Writing an object to a dummy file
ObjectOutput objectOutput = new ObjectOutputStream(new FileOutputStream(fileName));
                objectOutput.writeObject(firstInstance);
                objectOutput.close();

//Reading from the file
ObjectInput objectInput = new ObjectInputStream(new FileInputStream(fileName));
                secondInstance = (SerializedSingleton) objectInput.readObject();
                objectInput.close();

System.out.println(firstInstance == secondInstance);
System.out.println(firstInstance.hashCode());
System.out.println(secondInstance.hashCode());
}
}

The output you get is quite shocking. The hashcodes are different and objects are also different.

To fix this thing we have to code for readResolve in SerializedSingleton Class:

protected Object readResolve(){
return instance;
}

Thanks

Zookeper Installation

Hello friends let us look at the basic installation of the Zookeeper


  1. First download the package from Zookeeper site(link here)
  2. Extract the package anywhere.
  3. tar zxvf zookeeper-3.4.6.tar.gz
  4. cd zookeeper-3.4.6/conf/ 
  5. We are assuming that the data folder is /etc/analytics/data and is present.
  6. tickTime=2000
    dataDir=/etc/analytics/data
    clientPort=2181
    initLimit=5
    syncLimit=2
    server.1=<ip:1>:<start_port>:<end_port>
    #have to specifly all the servers with id (server.<id>) format
  7. Now the id of the current machine is decided by the text file content specified at /etc/analytics/data.  Name of that file is myid with content 1, that's it
  8. Now start the zookeeper process.
  9. To start the server use the following
    - bin/zkServer.sh start
  10. To start the client in order to check the things gone perfectly or not use this:
    - bin/zkCli.sh -server <ip>:2181
  11. To check the installation to be correct or not
  12. Connect to any of the zookeeper client
    [zkshell: 9] create /zk_test my_data
    Created /zk_test
  13. And check whether it is being created in other nodes or not :
    [zkshell: 12] get /zk_testmy_datacZxid = 5ctime = Fri Jun 05 13:57:06 PDT 2009mZxid = 5mtime = Fri Jun 05 13:57:06 PDT 2009pZxid = 5cversion = 0dataVersion = 0aclVersion = 0ephemeralOwner = 0dataLength = 7numChildren = 0
  14. If this is the output then  installation is perfect
Thanks

Gradle installation

Hello friends let us look at the installation of Gradle.

For this tutorial I am just explaining in Windows machine, but the steps are pretty much same for Linux as well.
  1. Download the package from Gradle website (link here)
  2. Then extract it to any folder.
  3. Have to  add the Gradle bin folder in to the Path variable of the environment
  4. For that follow my other post here.
  5. Make a variable name GRADLE_HOME and give its value as the base folder of the extracted package
  6. Then add the %GRADLE_HOME%/bin in to the path variable.
  7. Open a shell and type gradle -v  and if everything is correct it will show you something like this:
Thanks

Installing maven in Windows

Hello friends lets take a look at how to install maven in Windows.

  1. Download the Maven from the Maven website (link)
  2. Extract it to any folder, lets say E:/Maven
  3. It will get extracted as:
  4. Now after this you have to add 1 environment variables named MVN_HOME and attach %MVN_HOME%/bin in the PATH variable.(follow this)
  5. If everything goes well, on opening a new command window and typing mvn --version will return you something like this

Thanks

Checking a number as it is Fibonacci number or not

Hello Friends, today I want to give you a basic information that is very useful in letting know whether the number is a fibonacci number just by simple formula.

Here it goes,

Let us suppose we have to check whether the number n is a fibonacci number or not, then the condition 5n^2 + 4 or 5n^2 - 4 should be a perfect square.

 // A utility function that returns true if x is perfect square  
 bool isPerfectSquare(int x)  
 {  
   int s = sqrt(x);  
   return (s*s == x);  
 }  
 // Returns true if n is a Fibinacci Number, else false  
 bool isFibonacci(int n)  
 {  
   // n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both  
   // is a perferct square  
   return isPerfectSquare(5*n*n + 4) ||  
       isPerfectSquare(5*n*n - 4);  
 }  
 int main()  
 {  
  for (int i = 1; i <= 10; i++)  
    isFibonacci(i)? cout << i << " is a Fibonacci Number \n":  
            cout << i << " is a not Fibonacci Number \n" ;  
  return 0;  
 }  

Now once you pass the number to the function it will tell you whether or not the number is a part of fibonacci series or not.

Thanks

Sorting the array with one loop

Hello Friends, its pretty common question in almost all the interviews that how can you sort the array with one loop, and in first thought it seems pretty difficult to understand but if you think a bit out of the box you came to know that while your loop starts (considering the Bubble sort, that takes 2 loops), you can think of resetting the outer loops variable value and thus making the loop go once again as we want to, here look what I want to say:


 public class SingleLoopSorting {  
      public static void main(String[] args) {  
           int arr[] = {  
                5, 1, 7, 3, 9  
           };  
           for (int i = 1; i < arr.length; i++) {  
                //swapping the values via a = a+b;b=a-b;a=a-b; rule, and resetting the i variable
                if (arr[i] < arr[i - 1]) { 
                     arr[i] = arr[i] + arr[i - 1];  
                     arr[i - 1] = arr[i] - arr[i - 1];  
                     arr[i] = arr[i] - arr[i - 1];  
                     i = 0;  
                }  
           }  
           System.out.print("Sorted Array : ");  
           for (int i = 0; i < arr.length; i++) {  
                System.out.print(arr[i] + " ");  
           }  
      }  
 }  
Link here