Monday, June 27, 2016

Parsing XMLs with DOM Parser

DOM parsers are the simpler of the two parsers, the other being SAX parser. Its is programmetically less complicated but is also less efficient compared to sax. The DOM parser loads the whole document into the main memory and then parses the whole document all at once as opposed to parsing on encountering in SAX parser. The obvious drawback to loading the full file in memoory is that the efficiency of parsing reduces with the increase in size of the document. Not to mention, documents that don't fit in the memory cannot be parsed.

To understand DOM parser, we take an example xml file and parse it using DOM. Lets consider the following xml -

testXML.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<first>
    <second atName="one">
        <number id="one">1</number>
        <number id="two">2</number>
    </second>
    
    <second atName="two"> 
        <number id="one">1</number>
        <number id="two">2</number>
    </second>
</first>

Our goal is to parse this whole document and output the same using DOM parser. Before beginning with the example lets look into some helper classes and basic methods -

DocumentBuilder - It defines the API to generate the DOM document tree from an XML. Its usually created by using the DocumentBuilderFactory.newInstance().

Node - It is an interface which represents a node in the DOM tree.

Attr - This is the interface which represents the attributes of a node.

NamedNodeMap - This represents the list of attributes that a node holds.

In our example, the main() method first generates the DOM tree and the processNode() method traverses this tree printing the nodes as it encounters them.

DomParser.java


public class DomParser {

    public static void main(String[] args) {
        try {
            File file = new File("src/testXML.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();

            String tab = "";

            System.out.println("Staring Parsing...");

            //Process root Node
            Node root = doc.getDocumentElement();
            System.out.println(root.getNodeName());
            processNode(root, "\t" + tab);

            System.out.println("Parsing Complete...");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void processNode(Node node, String tab) {
        try {
            NodeList children = node.getChildNodes();

            for (int i = 0; i < children.getLength(); i++) {
                Node ele = children.item(i);

                //Printing the node name or the text value in case of a Text node
                if (ele.getNodeName().equals("#text")) {
                    System.out.print(" " + ele.getNodeValue());
                } else {
                    System.out.print(tab + ele.getNodeName());
                }

                //Printing attributes of the current node.
                if (ele.hasAttributes()) {
                    NamedNodeMap attrs = ele.getAttributes();
                    for (int j = 0; j < attrs.getLength(); j++) {
                        Attr attribute = (Attr) attrs.item(j);
                        System.out.print(" " + attribute.getName() + "=" + attribute.getValue());
                    }
                }

                //Process children 
                processNode(ele, "\t" + tab);
            }

        } catch (DOMException e) {
            e.printStackTrace();
        }

    }

}

The text nodes appear with a "#text" in them. This nodes accordingly dealt with. The method processNode()is recursively called as it traverses through the whole tree. The output for the above program is as follows -

Output


Staring Parsing...
first
 
     second atName=one 
          number id=one 1 
          number id=two 2 
     
    
     second atName=two  
          number id=one 1 
          number id=two 2 
     
Parsing Complete...


The DOM parser is not a very efficient parser, but for small documents, it can be very useful.

Friday, June 17, 2016

Design Patterns - Factory Pattern (with Reflection API)

Factory design patterns are probably the most used design pattens in almost any kind of framework. Its part of the creational pattern as it provides a structured ways to generate objects.

To understand factory pattern, lets take an example where we develop code to print the different country codes. All the countries implement the interface called Country. The interface is as follows -

Country.java


package factory;

public interface Country {

    public void printCountryCode();
}

We consider three countries for this example - India, Germnay and Japan. Each country has a class of its own which implents the Country interface and its method printCountryCode(). The classes are given below.

India.java


package country;

import factory.Country;

public class India implements Country {

    @Override
    public void printCountryCode() {
        System.out.println("+91");
    }

}

Germany.java


package country;

import factory.Country;

public class Germany implements Country {

    @Override
    public void printCountryCode() {
        System.out.println("+49");
    }

}

Japan.java


package country;

import factory.Country;

public class Japan implements Country {

    @Override
    public void printCountryCode() {
        System.out.println("+81");
    }

}

Each class has its own version of the method printCountryCode().

Now we create a Factory class which essentially generates these classes at runtime, depending upon when its needed, and executes the printCountryCode() method. In our example, we print the country code for all the countries.


package factory;

import country.Germany;
import country.India;
import country.Japan;

public class CountryFactory {

    public static void main(String[] args) {
        Country india = getCountry("India");
        india.printCountryCode();    //Prints +91

        Country germany = getCountry("Germany");
        germany.printCountryCode();     //Prints +49
 
        Country japan = getCountry("Japan");
        japan.printCountryCode();    //Prints +81
    }

    public static Country getCountry(String name) {
        if (name.equals("India")) {
            return new India();
        } else if (name.equals("Germany")) {
            return new Germany();
        } else if (name.equals("Japan")) {
            return new Japan();
        }

        return null;
    }
}


 The getCountry() method is responsible for returning the correct class to the Country interface. It takes a parameter which tells it which class to return.

Factory Pattern with Reflection API


Another way to implement the getCountry()method is with the help of the Java reflection API. The following is the implementation of the aforementioned method using reflection api.


package factory;

public class CountryReflectionFactory {

    public static void main(String[] args) {
        Country india = getCountry("country.India");
        india.printCountryCode();   //Prints +91

        Country germany = getCountry("country.Germany");
        germany.printCountryCode(); //Prints +49

        Country japan = getCountry("country.Japan");
        japan.printCountryCode();   //Prints +81
    }

    public static Country getCountry(String pathName) {
        try {
            return (Country) Class.forName(pathName).newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
            ex.printStackTrace();
            return null;
        }
    }
}


In this example, the fully qualified name i.e., the name of the class with the package details, is sent as a parameter to the getCountry()method which in turn uses the Java Reflection API to generate the classes at runtime.

Factory pattern is probably the most used pattern. It is a very useful to keep classes of the same type together by inheriting a common interface. This feature makes it an important tool to gather simlar together classes and bind them to a single framework.



Sunday, June 12, 2016

Design Patterns - Singleton Pattern

Java Singleton patterns are the simplest type of design patterns. They are part of the Creational Patterns. This type of design pattern is used to ensure that only a single instance of an object is running at all times. The easiest way to do this is simply by making the constructor private and allowing the object to be instantiated only through a public static method.

An example of a simple singleton class is as follows -


public class SingletonClass {

    private static SingletonClass singleton;

    private SingletonClass() {
 //private is used to restrict class instantiantion
    }

    public static SingletonClass getInstance() {
        if (singleton == null) {
            singleton = new SingletonClass();
        }

        return singleton;
    }

    public static void releaseInstance() {
        singleton = null;
    }

}

This class is pretty self explanatory. The access modifier of the constructor could also be changed to protected in order to allow the children classes to instantiate the singleton class. A method releaseInstance() is used only to forget the current instance of the class.

Ensuring Singletonness


There are some ways in which this implementation of the singleton pattern may break. We look into the problems and ways to ensure the singletonness.

Thread Safety


Sometimes multithreading can break the functionality of singleton classes. In the following test example the singletonness of the class is not maintained.


@Test
    public void UniqueTest_multithreading() throws InterruptedException {
        SingletonClass s1;
        SingletonClass s2;

        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    SingletonClass s = SingletonClass.getInstance();
                    System.out.println(s.toString()); //Prints different object instances
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Thread t1 = new Thread(run, "First");
        t1.start();
        Thread t2 = new Thread(run, "Second");
        t2.start();

        t1.join();
        t2.join();
    }


 public static SingletonClass getInstance() {
        if (singleton == null) {
            additionalFunctionality();
            singleton = new SingletonClass();
        }

        return singleton;
 }

 private static void additionalFunctionality() {
        if (Thread.currentThread().getName().equals("First")) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
  }



The test essentially creates two threads which individualy call the getInstance() method. Lets say that some additional work is performed for the first thread. In this case, the first thread becomes busy after performing the null check, during which the second thread already intializes the singleton class. After the additional work by the first thread is done, it re-intializes the singleton class. This results in both the threads having two seperate instances of the singleton class.

Solution

A solution for this problem is making the instantiation part of the singleton class synchronized. So, just adding a synchronised block to the getInstance() method will solve this problem.


    public static SingletonClass getInstance() {
        synchronized (SingletonClass.class) {
            if (singleton == null) {
                additionalFunctionality();
                singleton = new SingletonClass();
            }
        }

        return singleton;
    }

Serializing and Deserializing


Another scenario that breaks the singletonness of the class is when the a singleton object is serialized and then deserialized twice. So, the following test would fail.


@Test
    public void UniqueTest_serializable() {
        SingletonClass singleton = SingletonClass.getInstance();

        writeSingletonObjectToDisk(singleton);
        SingletonClass s1 = readSingletonObjectFromDisk();
        SingletonClass s2 = readSingletonObjectFromDisk();
        assertEquals(s1, s2); //Fails
    }

Solution

There is however a very easy solution for this. The addition of the readResolve() method to the singleton class solves this problem.


 private Object readResolve() {
        return SingletonClass.getInstance();
 }

What happens here is that the readResolve() method is executed first before beginning the deserialization procedure. When a valid object is found, the deserialization essentially never takes place.

One thing to keep in mind is that for the singleton class to be able to serialize it should implement the interface java.io.Serializable.


Saturday, June 11, 2016

Deleting files in a folder using Java

To delete the files in a folder using java, the following piece of code can be used.

String path = "Path\\to\\target\\folder\\";

File folder = new File(path);
File[] listOfFiles = folder.listFiles();

//Iterate through the files
for (File f : listOfFiles) {
    f.delete();
}

The folder itself can also be deleted by adding the following line after the for loop.

folder.delete();