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!




t> UA-39527780-1 back to top