Sunday 30 November 2014

Starting a new Process programmatically from Java

Background

In this post we will see how we can run any process from java programmatically. In specific I will show how can we compile a java file from a Java process. We can very well use Runtime.getRuntime().exec() method to start the process but in this post I am going to demonstrate using ProcessBuilder class.

Code

    public static void executeJavacCommand() throws IOException {

        List<String> paramsExecute = new ArrayList<String>();
        paramsExecute.add("C:\\Program Files\\Java\\jdk1.6.0_31\\bin\\javac.exe");
        paramsExecute.add("-cp");
        paramsExecute.add(".");
        paramsExecute.add("HelloWorld.java");
        ProcessBuilder pBuilder = new ProcessBuilder(paramsExecute);
        Process process = pBuilder.start();
        Reader reader = new InputStreamReader(process.getErrorStream());
        int ch;
        while((ch = reader.read())!= -1)
            System.out.print((char)ch);
        reader.close();

    }

Note1 : In above code I am only printing the error stream of the process but you can manipulate the output stream as well as provide input stream to the process.
Note 2:  You can also see my previous post on how to get the java executable paths. You can programmatically derive those and use it in above code.


Related Links

Finding Java home programatically from Java program

Background

There might be various scenarios in which you might need to get the path of java executable. For example to lets say start java program from withing Java code. In this post we will see how can we achieve that. I will demonstrate a method to find the JAVA_HOME that is usually the JDK directory. Once you have that it is easy to get executable. For eg javac will be in JAVA_HOME/bin/javac.exe

Code

public class JavaHomeTest{

    public static void main(String args[]) throws IOException {
        System.out.println(getJDKDir());
    }

    public static String getJDKDir() {
        File javaHome = new File( System.getProperty( "java.home" ) ).getParentFile();
        File jdkDirectory = null;
        if( javaHome.getName().contains( "jdk" ) ) { 
            //happens in IntelliJ
            jdkDirectory = javaHome;
        } else { 
            //General Scenario - eclipse / command line
            File[] childDirs = javaHome.listFiles();
            for(File file : childDirs) {
                if(file.getName().contains("jdk")) {
                    jdkDirectory = file;
                    break;
                }
            }
            
        }
        return jdkDirectory.getAbsolutePath();
    }

}


Output : 

I am running Windows. The output that I get is 'C:\Program Files (x86)\Java\jdk1.7.0_55'. Code is same for Linux as well. You will get your Java directory.

Saturday 29 November 2014

How to delete a directory in Java

Background

Well lately I have written a lot of code for file manipulation, I/O etc. So let me take this post to show how can we create or delete directories. Well Java provides APIs for them so it should be pretty straightforward to understand. Important point to look forward is that if you are deleting a directory and it has more files in it then the directory will not get deleted unless all it's children are deleted recursively.  Note File as a Java object can represent either a file or a directory. You can use File 's class isDirectory() method Eg.

        File file = new File("C:\\Users\\athakur\\Downloads");
        if(file.isDirectory()) {
            System.out.println("File is a directory");
        }


Now lets get to creating and deleting directories/files.



Creating a File

To create a file we can use createNewFile() method. Eg - 

        File file = new File("C:\\Users\\athakur\\Downloads\\abc.txt");
        if(!file.exists()) {
            file.createNewFile();
        }

Creating a Directory

To create a directory first create a File object and then call mkdir() on it. Eg -

        File file = new File("C:\\Users\\athakur\\Downloads\\Movies");
        if(!file.exists()) {
            file.mkdir();
        }

Deleting a file/directory

To delete a file or a directory we have to use delete() method. As stated in introductory paragraph if directory has data that data needs to be deleted first. "rm -rf *" does not work in java :).

    public void deleteDirectory(String path) {
        
        File file  = new File(path);
        if(file.isDirectory()){
            String[] childFiles = file.list();
            if(childFiles == null) {
                //Directory is empty. Proceed for deletion
                file.delete();
            }
            else {
                //Directory has other files.
                //Need to delete them first
                for (String childFilePath :  childFiles) {
                    //recursive delete the files
                    deleteDirectory(childFilePath);
                }
            }
            
        }
        else {
            //it is a simple file. Proceed for deletion
            file.delete();
        }
        
    }


Above method will delete complete directory.

Tuesday 25 November 2014

Install Intellij Idea in Ubuntu

Background

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.
    sh

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
Exec=/home/aniket/firefox/idea-IC-139.225.3/bin/idea.sh
Icon=/home/aniket/firefox/idea-IC-139.225.3/bin/idea.png
Terminal=false
StartupNotify=true
Type=Application
Categories=Development;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 ?

Background

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

Background

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");
            e.printStackTrace();
        }
        
    }
    
    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);
                if(hexString.length()==1) 
                {
                hexStringBuffer.append('0');
                }
            hexStringBuffer.append(hexString);
        }
        
        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 -

org.apache.commons.codec.digest.DigestUtils.md5Hex(password);

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.

Background

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"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="OpenSourceForGeeks"
        module="JsonParser"
        status="integration">
    </info>
    
    <dependencies>
        <dependency org="com.google.code.gson" name="gson" rev="2.2.4"/>
    </dependencies>
</ivy-module>

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



Animal.java

package opensourceForGeeks.models;

public class Animal {
    
    private String type;

    public String getType() {
        return type;
    }

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

}

Dog.java

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...");
    }

}

Cat.java

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();
    
    static
    {
        ANIMAL_MAPPING.put("dog", Dog.class);
        ANIMAL_MAPPING.put("cat", Cat.class);
    }
    
    public Animal parseAnimal(String jsonString)
    {
        try
        {
            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

Background

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 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

Sunday 9 November 2014

Strategy Design pattern in Java

Background

In my previous post on Introduction to Design Patterns  we saw there are various types of Design patterns. They are mainly categorized into three types - 
  1. Creational
  2. Structural
  3. Behavioral
 In this post we will lean about Strategy Design pattern. This design pattern comes under behavioral type. This design patterns lets you  
  • define family of algorithms or class behaviors that can change at runtime depending on the context involved. To put it in other words 
  • it lets you choose your strategy from a list of predefined ones depending on what would suit your current runtime context.

Class Diagram




 Above class diagram represents the program that I will be using to demonstrate Strategy pattern. Points to note here -

  1. Both concrete type of Strategies i.e AdditionStrategy and SubtractionStrategy implement the interface Strategy that has a common method performOperation() that each implementing class implement.
  2. Also note the composition relationship between Strategy class and Calculator class. It simply means Calculator class owns Strategy class and that Strategy class cannot exist meaningfully without Calculator class.

To the Code

Lets first write own interface class - 

 Strategy.java

/**
 * 
 * @author athakur
 *
 */
public interface Strategy {
    
    public int performOperation(int a, int b);

}


Now lets write our concrete classes that implement above class -

AdditionStrategy.java


/**
 * 
 * @author athakur
 *
 */
public class AdditionStrategy implements Strategy {

    @Override
    public int performOperation(int a, int b) {
        // TODO Auto-generated method stub
        return a+b;
    }

}

SubtractionStrategy.java

/**
 * 
 * @author athakur
 *
 */
public class SubtractionStrategy implements Strategy {

    @Override
    public int performOperation(int a, int b) {
        // TODO Auto-generated method stub
        return a-b;
    }

}

and finally our Calculator class - Calculator.java


/**
 * 
 * @author athakur
 *
 */
public class Calculator {
    
    Strategy strategy;

    public Strategy getStrategy() {
        return strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
    
    public int calculate(int a, int b) {
        return strategy.performOperation(a, b);
    }

}

Now lets test our code. Create a class Test.java

/**

 * 

 * @author athakur

 *

 */

public class Test {

    public static void main(String args[]) {

        Calculator calc = new Calculator();

        calc.setStrategy(new AdditionStrategy());

        System.out.println("Additition : " + calc.calculate(5, 2));

        calc.setStrategy(new SubtractionStrategy());

        System.out.println("Subtraction : " + calc.calculate(5, 2));

    }

}

and the output will be as expected - 

Additition : 7
Subtraction : 3

Understanding the pattern via code

 See how we could change the operation using a particular strategy depending on the requirement. Calculator here is own context. When we needed addition we use the Addition Strategy and when we needed Subtraction we used the Subtraction strategy. Note how the context or the Calculator remains the same but the strategy used changes. We are simply using different strategies depending on the requirement at runtime. This type of design is called Strategy pattern.

To sum up -

In Strategy pattern, objects representing various strategies are created and a context object behavior changes depending on these strategies at runtime.

Related Links

t> UA-39527780-1 back to top