Tuesday, 25 November 2014

Install Intellij Idea in Ubuntu


Whichever IDE you use installing it is very easy in Ubuntu. In this post I will show how can we configure Intellij IDEA. Installing Eclipse is also similar. You can see short summary of it in 

Downloading and Installing

  1. Download latest Intellij IDEA from their official site. For me its 'ideaIC-14.0.1.tar.gz'.
  2. Extract the compressed archive to some suitable folder. I will install it in a folder called firefox in my user directory -

    aniket@aniket-Compaq-610:~$ cd firefox/
    aniket@aniket-Compaq-610:~/firefox$ tar xzvf ideaIC-14.0.1.tar.gz
  3. That's pretty much it for downloading and installing part. You can run the IDE by executing idea.sh script file inside the bin folder.

    aniket@aniket-Compaq-610:~/firefox$ cd idea-IC-139.225.3/
    aniket@aniket-Compaq-610:~/firefox/idea-IC-139.225.3$ ./bin/idea.

Creating launcher for your application

Procedure is same for creating launcher for your executable. I will demonstrate it for IDEA.

aniket@aniket-Compaq-610:~$ cd /usr/share/application/
aniket@aniket-Compaq-610:/usr/share/applications$ sudo gedit idea.desktop

Now add the following lines to it

[Desktop Entry]
Name=IntelliJ IDEA
Comment=IntelliJ IDEA IDE

Above configuration is with respect to my executable path. Change the enteries accordingly. Save the file and run it to launch the application.

Note : Did you notice we put out idea.desktop in '/usr/share/applications' folder. By doing this it will also be accessible from unity search dashboard.

If you remember we had done similar thing for Eclipse. We downloaded the archive file and then created the launcher.

Related Links

Saturday, 22 November 2014

How to install Google chrome on Ubuntu ?


As we all know Firefox is by default the browser that comes with Ubuntu. However there are many users who prefer Chrome over Firefox. So in this post I am going to show how do we do that.

Installing Google Chrome

  • Method 1  : Download package and install
    1. Navigate to https://www.google.com/intl/en-US/chrome/browser/ using any browser  (Eg. Firefox)
    2. You will see download option. Click on it. The download site will automatically detect your operating system and provide download options accordingly.
    3. Select which package you need. Use .deb package for debian based systems and .rmp for fedora and similar distributions. Also choose 32/64 bit based on your system configuration. You can use uname -a command to see the details.

    4. After you download it  use dpkg command to install the package. For fedora you will have to use yum command.

       sudo dpkg -i google-chrome-stable_current_i386.deb

    5. If there are any error simply run

      sudo apt-get -f install

      and re run the command in step 4.

    6.  And chrome should be installed on your system.
  •  Method 2 : For command line Guys/Girls

    1. cd /Downloads
    2. wget https://dl.google.com/linux/direct/google-chrome-stable_current_i386.deb
    3. sudo dpkg -i google-chrome-stable_current_i386.deb
    4. If there are error in step 3 run sudo apt-get -f install and re run step 3.
Note : -f option in apt-get is essentially to fix missing dependencies.

Note : Google chrome is not the same as Chromium browser that you find in Ubuntu repositories (Ubuntu Software center). For starters Chromium is open source while Google chrome is not. For more details you can read the Wiki about Chromium browser. Chromium is the open-source web browser project from which Google Chrome draws its source code.

Related Links

Sunday, 16 November 2014

Generating MD5 hash in Java


Heard of MD5 hashing algorithm ?  MD5 stands for Message Digest algorithm 5 which is a cryptographic algorithm invented by Ronald Rivest in 1991 for calculating hash values. So MD5 is a widely used hashing algorithm in many companies and firms. (MD5 Wiki)

How did I get here you ask ? 

I was trying to understand how passwords are stored in database. For example you create a website where users can login you will need to store user credentials - username and password for instance. Now how would you store the password ? Plain text ? Don't guess... answer is NO! It is a major security flaw. Anyone can get the passwords once they get into the file system you are using to store the passwords. Then store in encrypted ? Better idea then storing as raw text but again not recommended. Once someone knows the encryption method you have used all your sensitive data is gone. Infact developers developing the product should not know what passwords users have. And answer to all of it is hash the password string and store it which is exactly why we are looking at MD5 algorithm in this post. Well... natural question to follow is how is password verified when user logs in again? Again the hash of user entered password is generated and compared against the save hash value.

Infact you can use MD5 checksum to verify integrity of your files after transferring it over the network. In linux you can use md5sum command to calculate the checksum value. 

  • Hash is 128 bit or 16 byte or 32 hex characters.

If checksum is same after transferring your file over the network then your files is transferred correctly. If it's not the same that mean your file is corrupted.

To the Code

 Java code to generate MD5 hash is as follows - 

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5HashDemo {
    public static void main(String args[]) throws IOException 
        String password = "password";
        try {
            System.out.println("MD5 hash generated : " + getMD5Hash(password));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Could not generate MD5 hash for password");
    public static String getMD5Hash(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException
        byte[] passwordBytes = password.getBytes("UTF-8");
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] md5Bytes = md.digest(passwordBytes);
        StringBuffer hexStringBuffer = new StringBuffer();
        for (int i=0;i<md5Bytes.length;i++) {
            String hexString=Integer.toHexString(md5Bytes[i] & 0xff);
        return hexStringBuffer.toString();


Output : 
MD5 hash generated : 5f4dcc3b5aa765d61d8327deb882cf99

Above is just plain raw method to generate MD5 hash but we need not code from scratch. We have libraries that help us do that. You can use commons-codec library which apache provides. Then you can get the hash by simply executing -


Even Spring framework provides such a method.

Note :  See how I have used "UTF-8" encoding in getBytes() method? It is a good idea to do so unless you are using a specific encoding throughout your application. If not provided system encoding is picked up by default which may vary from system to system.

Lets now come to million dollar question....

Is it possible to decrypt md5 hashes?

Answer is No! If we could then why bother for hashing we could go for good encryption only. So we cannot get the original string from the hash unless you use Rainbow tables do some kind of brute forcing technique to guess.  But even using that it is almost impossible to get the original string back.

Also if you use Salt to generate the hash then even above techniques won't work. Using salt gives different hashes every time for same String input. But note using salt will not work in case of passwords for obvious reasons (you will not be able to compare it then)

Related Links

Saturday, 15 November 2014

Creating a simple JSON parser for parsing various similar response types.


Many a times it so happens that a particular service or APIs return a set of similar resources. So how do we handle it in a client that uses these APIs or services. One way is that you check the incoming response against all the exhaustive possible list of responses . One would match and you will have your result. But that's very bad programming. So many if-else statements. Plus so much computing time wastage. Surely not a way to go for production code. In this post I will show how can write a simple parser that parses such requests.

Assumption and Understanding of task

Before we go to the code let me explain the problem which we are going to solve with the parser. Assume there is a Service or an API that returns an Animal. For example you want a pet you may ask for Dog or a Cat. If you want to participate in horse racing you may ask for a Horse or a Hen for poultry etc. Point is we have to build a client that can parse the incoming requests. So if someone asks for a Dog we should parse the response for a Dog and prove it is indeed a Dog.

For simplicity of code and understanding I am just going to work with Class Dog and Class Cat. To differentiate between them I am adding bark() method in Dog class and drink() method in Cat class.
Also we have a super class called Animal. Both Dog and Cat class extend Animal Class. We will leverage the concept of polymorphism

Also I am assuming that the response we get has a basic structure 

     "type":type of animal

It may have additional attributes depending on the type of animal. For Cat and Dog I have added another attribute called isPet. What will be more important is the type which is common to all the responses.

To the Code

As usual I am using Eclipse with Ivy dependency manager. We need GSON library to handle json data. My Ivy file looks like -

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        <dependency org="com.google.code.gson" name="gson" rev="2.2.4"/>

Next lets create our model classes. We will have three model classes - Animal, Dog and Cat. Overall my project structure looks like follows -


package opensourceForGeeks.models;

public class Animal {
    private String type;

    public String getType() {
        return type;

    public void setType(String type) {
        this.type = type;



package opensourceForGeeks.models;

public class Dog extends Animal {
    boolean isPet;
    public boolean isPet() {
        return isPet;

    public void setPet(boolean isPet) {
        this.isPet = isPet;

    public void bark()
        System.out.println("Dog is barking...");



package opensourceForGeeks.models;

public class Cat extends Animal {
    boolean isPet;
    public boolean isPet() {
        return isPet;

    public void setPet(boolean isPet) {
        this.isPet = isPet;

    public void drink()
        System.out.println("Cat is drinking milk...");

Next lets write our actual parser logic - JsonParser.java

package opensourceForGeeks.parser;

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;

import opensourceForGeeks.models.Animal;
import opensourceForGeeks.models.Cat;
import opensourceForGeeks.models.Dog;

public class JsonParser {
    private static final Map<String, Class> ANIMAL_MAPPING = new HashMap<String, Class>();
    private static final Gson gson = new Gson();
        ANIMAL_MAPPING.put("dog", Dog.class);
        ANIMAL_MAPPING.put("cat", Cat.class);
    public Animal parseAnimal(String jsonString)
            Animal animal = gson.fromJson(jsonString, Animal.class);
            return gson.fromJson(jsonString, ANIMAL_MAPPING.get(animal.getType()));
        catch (Exception ex)
            System.out.println("Exception occured while parsing Animal json string");
            return null;


and finally lets test it - JSONParserTest.java

package opensourceForGeeks.test;

import opensourceForGeeks.models.Cat;
import opensourceForGeeks.models.Dog;

public class JSONParserTest {
     private static final String DOG_JSON = "{\"type\": dog,\"isPet\": true}";
     private static final String CAT_JSON = "{\"type\": cat,\"isPet\": true}";
    public static void main(String args[])
        opensourceForGeeks.parser.JsonParser parser = new opensourceForGeeks.parser.JsonParser();
        ((Dog) parser.parseAnimal(DOG_JSON)).bark();
        ((Cat) parser.parseAnimal(CAT_JSON)).drink();


and the output is as expected - 

Dog is barking...
Cat is drinking milk...

Understanding the logic

What we have done in our JsonParser class is as follows -

  • We first create a map of type(exhaustive list of possible types of Animals) and their model classes.
  • All type of Animals extend Class Animal which has the type that will be common to all the JSON responses.
  • So we first convert the json string into Animal object which in turn provides us the information about what type of Animal it is.
  • Then we use this information to get the model class used to describe that type of Animal and again parse the json String to covert it into that specific type of Animal and finally return it.
  • Yes we have used polymorphism here to make our task easier!

Thursday, 13 November 2014

Difference between Association, Aggregation and Composition in UML, Java and Object Oriented Programming


In Object oriented programming a program is essentially multiple objects interacting with each other. Each interacting object have a relation. This relationship can be categorized as -
  • Association, 
  • Aggregation and 
  • Composition
Note these are not mutually exclusive (We will come to that in a while). But given a relationship between a Class or it's object their interactions can be described with above categories. Also to represent these relationships there are UML diagrams (Wiki) . For example we may have Class diagram or Use case diagram or a timeline diagram. Above classifications are also used in these UML diagrams.

Difference between Association, Aggregation and Composition

When we think of Object oriented nature we always think of Objects, class (objects blueprints) and the relationship between them. Objects are related and interact with each other via methods. In other words object of one class may use services/methods provided by object of another class. This kind of relationship is termed as association.

For example you are related to your parent. In other words you are associated with  associated with your parent. This type of generic relationship is called association.

Aggregation and Composition are subsets of association meaning they are specific cases of association.

  • In both aggregation and composition object of one class "owns" object of another class.
  • But there is a subtle difference. In Composition the object of class that is owned by the object of it's owning class cannot live on it's own(Also called "death relationship"). It will always live as a part of it's owning object where as in Aggregation the dependent object is standalone and can exist even if the object of owning class is dead.
  • So in composition if owning object is garbage collected the owned object will also be which is not the case in aggregation.

Confused? Lets take examples to understand Composition and Aggregation

  • Composition Example :Consider example of a Heart and an Human. This type of relation ship between Human and Heart class is called Composition. Object of Heart class cannot exist without object of Human class and object of Heart has no significance without Human class. To put in simple words Humanclass solely "owns" the Heart class.

  • Aggregation Example :Now consider class Car and class Wheel. Car needs a Wheel object to function. Meaning Car object own Wheel object but we cannot say Wheel object has no significance without Car Object. It can very well be used in a Bike, Truck or different Cars Object.

Summing it up

To sum it up association is a very generic term used to represent when on class used the functionalities provided by another class. We say it's composition if one parent class object owns another child class object and that child class object cannot meaningfully exist without the parent class object. If it can then it is called Aggregation.

Note : For Association you can either use an arrow depicted above or a simple line. In Argo UML (Wiki) tool which I use we can choose from either. For example above association diagram for Parent-Child can be

Related Links

t> UA-39527780-1 back to top