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

Today we are going to look in to one of the most common pattern used in Software Development. That is Singleton Pattern.

Before moving forward let me give you a brief description of what is a Design Pattern and how it is useful in one or more ways?

What is a design pattern?
          In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.- Wiki

Now the statement is quite clear that it is not a rocket science and it is just the way of solving a problem which is common in the market.

Ok, now when we understand the basic idea of the design patterns let us take a look on to its types or in other words categories.

Categories:
          There are 4 categories under which the design patterns are divided. These are as follows:
  1. Creational Patterns
  2. Structural Patterns
  3. Behavioral Patterns
  4. Concurrency Patterns
I will not go in the inside of these because it would be a totally new and big topic to discuss but just want to give you an idea that Singleton Pattern is one of these patterns and comes under Creational Pattern.

Now we got the info regarding the patterns and their categories. Let us now take the info regarding the Singleton pattern as a particular.

Singleton Pattern:
          In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

Ok, so if you need an object to be instantiated once, per JVM per Application  we use singleton pattern to achieve this.


The above diagram shows a basic idea of how singleton works.

Now there are many ways of creating singleton objects. 
  1. Eager Initialization, without static block and so no exceptional handling.
  2. Eager Initialization, with static block and so with/without exception handling.
  3. Lazy initialization
  4. Thread safe initialization
Some of the points that we have to take care about are:
  1. Reflection can break the nature of Singleton object.
At last we will look in to the Enum style of creating the singleton.
  1. Enum Singleton
Lets see  each one of the above style 1 by 1.
  1. Eager Initialization, without static block and so no exceptional handling.
             
    It is pretty basic and easy to use.

    Example:
    public class  SingletonClass{
    public static final String singleton = "I am singleton";
    }

  2. This is very easy to use and also easy to understand but as you can see it is eager in nature which means we have to create the object beforehand that means the object is in memory even if we don't want to use it.

  3. Eager Initialization, with static block and so with/without exception handling.
             
    This way is same as the previous one as in this also we create the object beforehand but the only difference is that the object is created in a static block which gives us the opportunity to use exceptional handling if we want to.

    Example:
    public class  SingletonClass{
    public static String singleton;
    static{
    try{singleton = "I am singleton";}
    catch(Exception ex){System.out.println("You can handle exception here");}
    }
    }

    This is great when we know the creating the object beforehand not make any big impact on the system but in real world scenario mostly the database connection template(in case of Spring) and hibernate template are used in a singleton manner which are very heavy objects in nature and so creating them beforehand is not a good way.

  4. Lazy initialization.
             
    This is useful to make sure that the object is created only when it is needed by any class in a JVM per application

    Example:
    public class SingletonClass {
    private static SingletonClass instance;
    private SingletonClass(){} // (3.A)
    public static SingletonClass getInstance(){
    if(instance == null){ // (3.B)
    instance = new SingletonClass();
    }
    return instance;
        }
    }

    If you look on to this example at equation (3.A) you find that we have made the constructor private in nature thus restricting the creation of the object for the class, also in equation (3.B) we have checked for nullness of the object which makes sure that only one object is created for this class.

  5. Thread safe initialization.
             
    Thread safe initialization is very important for a singleton pattern to work correctly. If you look on to equation (3.B) you will find out that this is the place that will make the things messy as it may be the chance that 2 threads of  the application enters this code and tries to create to different objects of the instance which in turn breaks the overall meaning of the pattern. Now in order to achieve thread safe initialization we have 2 modes:
    • Either go for synchronization block
    • Either go for double check

      Synchronization Block:
                
      public class SingletonClass {
      private static SingletonClass instance;
      private SingletonClass(){} // (4.A)
      public static synchronized SingletonClass getInstance(){//(4.B)
      if(instance == null){ // (4.C)
      instance = new SingletonClass();
      }
      return instance;
          }
      }

      If you look at equation 4.B, the synchronized keyword makes sure that only 1 thread has the access to this function and will create only 1 instance of the instance but the problem here is the efficiency, as if you see the overall speed of the check will be affected greatly since only 1 thread has the access to the function.

      Double Check:     
      public static Singleton getInstance(){//(4.D)
          if(instance == null){
              synchronized (Singleton.class) {//(4.E)
                  if(instance == null){
                      instance = new Singleton();
                  }
              }
          }
          return instance;
      }

      In this example equation 4.D makes sure that multiple threads can access the function and thus not affecting the efficiency and equation 4.E will place the lock on the block and recheck of the condition, this is good to achieve the thread safe creation of  the object but it is still the overhead.
Using reflection to break singleton pattern from above styles.
          The reflection is an API provided by Java that gives you the functionality to manipulate the objects in the run time. Reflection is commonly used by programs which require the ability to examine or modify the run time behavior of applications running in the Java virtual machine.

Here I am presenting the code example that can break the functionality of the Singleton pattern and thus ruins everything of singleton pattern.

Example

class Singleton {
public static final Singleton INSTANCE = new Singleton();
}
public class EnumSingletonTest{
public static void main(String[] args) {
Singleton ins1 = Singleton.INSTANCE;
Singleton ins2 = null;
try{
Constructor[] constructors = Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
                                //Below code will destroy the singleton pattern
                                constructor.setAccessible(true);
                                ins2 = (Singleton) constructor.newInstance();
                                break;
                        }
        System.out.println(ins1.hashCode());
        System.out.println(ins2.hashCode());
}catch(Exception ex){
System.out.println("Hello");
}
}
}
Output:
360637413
1034148457

The output clearly showing that both the objects are different and unique and not the same which is the promise of the singleton pattern.

Now lets look on to the Enum style of creating the singleton objects:
  1. Enum Singleton.
              
    This is something that I have created the page. This is the best way of creating the singleton object and also not worrying about the  thread safe creation and eager creation. The enum singleton pattern is by default thread safe in nature and is also easy to use.


    Example:
    enum EnumSingleton {
    INSTANCE;
    private final String var1;
    private EnumSingleton(){
    var1 = "I am initialised now you can use me";
    System.out.println("I am private constructor");
    }
    public String getVar1() {
    return var1;
    }
    }
    public class EnumSingletonTest{
    public static void main(String[] args) {
    System.out.println(EnumSingleton.INSTANCE.getVar1());
    }
    }

    One more point to be noted that Enum singleton also restricts creation of new object by the use of Reflections. If we tries to use it, the program throws an Exception.java.lang.IllegalArgumentException: Cannot reflectively create enum objects

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, len=arr.length; i < len; 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

Monday, July 13, 2015

Unprotected key file while ssh the remote host.

Hello Friends, you all may have faced the unusual error like this:


This error is basically self explanatory, and tells you that the public key(.pem) file what you are using to login to the remote server is actually not protected from the world, on the basis of the permissions(linux permissions).

If you do the ls -l, command in the directory where your pem file is situated you will find that the listing tells you that the file is not protected from the outside world. The file permission for the pem file should exactly be 400.

So just do change the file permissions of the pem file using the chmod command like this:

  • chmod 400 filename.pem
This will change the file permission and will let you use the file to do the login.

Thanks

Creating the jar file from POM

Hello Friends, today we are going to see how to create a jar file with the use of Maven.

Here I am providing you the basic setup of creating the jar file from Maven(POM).

Open your pom.xml file and attach the following code in the field named <build>.

<build>
  <plugins>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <mainClass>Name of the main class, with full package details</mainClass>
          </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
    </plugin>
  </plugins>
</build>


Now when you have to package the project use this:

  • clean compile assembly:single


This will generate the jar in the target folder if using the Eclipse IDE.

Thanks.