Saturday, 29 June 2013

ANT - Step By Step Build Procedure

Build Tools - Build tools are used to automate the repetitive tasks. This can be for example compiling source code, running software test and creating files and documentation for software deployment. Build tools are run from command prompt. Examples of Build tools are - Apache ANT, Maven etc.

ANT - Another Neat Tool, this is what it Stands for. Its a Java build and deployment tool written using plain XML.

Installing Apache ANT

Before starting working with ANT, you need to setup ANT in your system. Since I am using Windows operating system so I will concentrate over that only.
1. Get latest Apache ANT version from http://ant.apache.org .
2. Unzip the zip file to a location of your choice lets say C:\Ant.
3. Set up the environment variables ANT_HOME and JAVA_HOME as highlighted in the image below.















4.Now to verify whether ANT has been successfully installed or not, go to command prompt and type
   c:\>ant -versionApache
 Ant(TM) version 1.9.0 compiled on March 5 2013

 If you don't see the above output then something has gone wrong with the installation.

Step By Step creation of build.XML file. I have seggregated it into steps to have better understanding.

1. Every build.xml file starts with <project > tag. Here, default attribute will identify which target is to be    called while processing the build.xml and basedir is pointing to root directory.

<?xml version="1.0"?>
    <project name="Ant Build" basedir="." default="execute">


2. Define all the properties which would be needed. These properties will be used in the further steps. To make ANT script generic I have defined all the properties so that I can change these properties to build another java code in future. Moreover, we can have a separate build.properties files where we can define these properties as key value pair. 

 <property name="project" value="SAXParserImplementation"/>
 <property name="src.dir" value="src/parser"/>
 <property name="build.dir" value="build/class"/>
 <property name="jar.dir" value="jar"/>
 <property name="config.dir" value="config"/>
 <property name="parameters" value="D:/test.xml"/>
 <property name="jarFileName" value="SAXParser.jar"/>
 <property name="className" value="parser.SAXParserImplementation"/>
 <property name="includeFileList" value="SAXParserImplementation.java"/>

build.properties
src.dir=src/parser
build.dir=build/class


And, in the build.xml define <property file="build.properties"/>. No need to mention any other property. You can move all your properties to build.properties.

3. Our default target is execute, this target will execute the java code using java command. I have placed the test.xml inside the config folder and passed this as an argument to my java code. You can refer SAX Parser code from post.

<target name="execute" description="Executing Java Code" depends="compress">
   <echo>Executing Project - ${project}...</echo>
   <echo>Output...</echo>
   <java classpath="${build.dir}" classname="${className}">
      <arg line="${config.dir}/test.xml"/>
   </java>
</target>

But before executing it, it goes to compress target since this is dependent on it.

4. compress target will create a Jar file by using jar command and place it inside the jar.dir which I have already defined in the properties.

<target name="compress" description="Create a Jar file" depends="compile">
   <echo>Creating Jar file...</echo>
       <jar destfile="${jar.dir}/${jarFileName}" basedir="${build.dir}"/>
</target>

But before executing it, it goes to compile target.

5. compile target is used to create the class files which will take the java code from src.dir and compiled it to build.dir. The includes attribute defines which all files need to be compiled. Since in my project, number of java files were there in the folder. But I wanted to compile only SAXParserImplementation.java, so I defined it in that attribute. You can define more java classes also as a comma separated list.

<target name="compile" description="Create a class file" depends="init">
   <echo>Compiling Java file...</echo>
   <javac srcdir="${src.dir}" destdir="${build.dir}" target="1.6" debug="true" includes="${includeFileList}"/>
</target>

Again we can see that this target is dependent on init. So it will process init first.

6. init target is used to create and copy operation.

<target name="init" description="Make directory" depends="clean">
   <echo>Creating Build/Jar Directory...</echo>
   <mkdir dir="${build.dir}"/>
   <mkdir dir="${jar.dir}"/>
   <mkdir dir="${config.dir}"/>
   <copy file="${parameters}"        todir="${config.dir}"/>
</target>

But this is dependent on clean, so clean will be executed first.

7. clean target is used for deleting the directories.

<target name="clean" description="Delete Directories">
   <echo>Deleting Directories...</echo>
   <delete dir="${build.dir}"/>
   <delete dir="${jar.dir}"/>
   <delete dir="${config.dir}"/>
</target>

Now start in reverse order from 7 to 1, you can easily understand what we are doing. Summarizing all the steps - clean all the directories --> create new directories --> compile your code --> create Jar out of it --> Execute it to get the output.

<?xml version="1.0"?>
<project name="Ant Build" basedir="." default="execute">
 <!--<property file="build.properties"/>-->
 <property name="project" value="SAXParserImplementation"/>
 <property name="src.dir" value="src/parser"/>
 <property name="build.dir" value="build/class"/>
 <property name="jar.dir" value="jar"/>
 <property name="config.dir" value="config"/>
 <property name="parameters" value="D:/test.xml"/>
 <property name="jarFileName" value="SAXParser.jar"/>
 <property name="className" value="parser.SAXParserImplementation"/>
 <property name="includeFileList" value="SAXParserImplementation.java"/>
 
 <target name="clean" description="Delete Directories">
  <echo>Deleting Directories...</echo>
   <delete dir="${build.dir}"/>
   <delete dir="${jar.dir}"/>
   <delete dir="${config.dir}"/>
 </target>
 
 <target name="init" description="Make directory" depends="clean">
  <echo>Creating Build/Jar Directory...</echo>
  <mkdir dir="${build.dir}"/>
  <mkdir dir="${jar.dir}"/>
  <mkdir dir="${config.dir}"/>
  <copy file="${parameters}" todir="${config.dir}"/>
 </target>
  
 <target name="compile" description="Create a class file" depends="init">
  <echo>Compiling Java file...</echo>
  <javac srcdir="${src.dir}" destdir="${build.dir}" target="1.6" debug="true" includes="${includeFileList}"/>
 </target>
 
 <target name="compress" description="Create a Jar file" depends="compile">
  <echo>Creating Jar file...</echo>
  <jar destfile="${jar.dir}/${jarFileName}" basedir="${build.dir}"/>
 </target>
 
 <target name="execute" description="Executing Java Code" depends="compress">
  <echo>Executing Project - ${project}...</echo>
  <echo>Output...</echo>
  <java classpath="${build.dir}" classname="${className}">
   <arg line="${config.dir}/test.xml"/>
  </java>
 </target>
</project>

Running the Ant Project

Copy build.xml and build.properties file(if any) to the location from where it can target the src folder as you have defined in the properties. To run it, go to command prompt and go to the directory where you have placed build.xml. Run ant command and here you go... 


Saturday, 22 June 2013

Marshalling and Unmarshalling using JAXB

JAXB stands for Java Architecture for XML Binding. JAXB provides API to access and process a XML document. We can read or write XML files using JAXB. In this post, I am going to use JAXB annotation to convert Java Object to/ from XML file. 

Before writing this post I read about marshalling and unmarshalling and found that Marshalling and Serialization in  Java are loosely synonyms. Infact Serialization is part of Marshalling. Term Marshalling is used when we talk about passing objects to remote Objects(RMI). In Marshalling Object is serialized(Member data is Serialized) + codebase is attached. CodesBase is information that tells the receiver of Object where the implementation of this object can be found. Any program that thinks it might ever pass an object to another program that may not have seen it before must set the codebase, so that the receiver can know where to download the code from, if it doesn't have the code available locally. The receiver will, upon deserializing the object, fetch the codebase from it and load the code from that location.

Marshalling - Convert a Java Object into an XML.

Unmarshalling - Convert an XML content into a Java Object


Class JAXBExample for Marshalling and UnMarshalling


public class JAXBExample
{
 private JAXBContext jaxbContext;

 public static void main(String args[])
 {
  JAXBExample jaxb = new JAXBExample();
  Employee employee = new Employee("1002", "Ankit", 200000, "Bangalore",
    9876);
  jaxb.convertToXML(employee);
  jaxb.convertToObject();
 }

 /**
  * Marshallling
  * 
  * @param employee
  */
 private void convertToXML(Employee employee)
 {
  try
  {
   jaxbContext = JAXBContext.newInstance(Employee.class);
   // Obtain marshaller from JaxbContext
   Marshaller marshaller = jaxbContext.createMarshaller();
   marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
   marshaller.marshal(employee, System.out);
  } catch (JAXBException e)
  {
   e.printStackTrace();
  }
 }

 /**
  * Unmarshalling
  */
 private void convertToObject()
 {
  Unmarshaller jaxbUnmarshaller;
  try
  {
   jaxbUnmarshaller = jaxbContext.createUnmarshaller();
   Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new File(
     "D:\\test.xml"));
   System.out.println("\n"+"Employee Details:");
   System.out.println("Id:" + employee.getId() + "\n" + "Name:"
     + employee.getName() + "\n" + "Salary:"
     + employee.getSalary() + "\n" + "Address:"
     + employee.getAddress() + "\n" + "Contact:"
     + employee.getContact());
  } catch (JAXBException e)
  {
   e.printStackTrace();
  }
 }
}



Annotated Class Employee




@XmlRootElement
class Employee
{
 private String id;
 private String name;
 private int salary;
 private String address;
 private int contact;

 Employee()
 {

 }

 Employee(String id, String name, int salary, String address, int contact)
 {
  this.id = id;
  this.name = name;
  this.salary = salary;
  this.address = address;
  this.contact = contact;
 }

 public String getId()
 {
  return id;
 }

 @XmlAttribute
 public void setId(String id)
 {
  this.id = id;
 }

 public String getName()
 {
  return name;
 }

 @XmlElement
 public void setName(String name)
 {
  this.name = name;
 }

 public int getSalary()
 {
  return salary;
 }

 @XmlElement
 public void setSalary(int salary)
 {
  this.salary = salary;
 }

 public String getAddress()
 {
  return address;
 }

 @XmlElement
 public void setAddress(String address)
 {
  this.address = address;
 }

 public int getContact()
 {
  return contact;
 }

 @XmlElement
 public void setContact(int contact)
 {
  this.contact = contact;
 }
}



XML



<?xml version="1.0"?>
<employee id="1002">
 <name>Ankit</name>
 <salary>200000</salary>
 <address>Bangalore</address>
 <contact>9876</contact>
</employee>


Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee id="1002">
    <address>Bangalore</address>
    <contact>9876</contact>
    <name>Ankit</name>
    <salary>200000</salary>
</employee>

Employee Details:
Id:1002
Name:Ankit
Salary:200000
Address:Bangalore
Contact:9876

Saturday, 15 June 2013

SAX (Simple API for XML) Parser in Java

In my last post, I discussed about DOM parser. In this post, I am going to discuss about SAX parser which I found far more better and simple than DOM parser. As I said before - Simple API for XML (SAX), an event-driven, serial-access mechanism for accessing XML documents. This protocol is frequently used by servlets and network-oriented programs that need to transmit and receive XML documents, because it is the fastest and least memory-intensive mechanism that is currently available for dealing with XML documents.

The most important interface is ContentHandler. This interface requires a number of methods that the SAX parser invokes in response to various parsing events. The major event-handling methods are:

1.  startDocument
2.  endDocument 
3.  startElement
4.  endElement

The easiest way to implement this interface is to extend the DefaultHandler class, defined in the org.xml.sax.helpers package. That class provides do-nothing methods for all the ContentHandler events.

Since it’s an event based parsing it contains default handler for handling the events whenever SAX parser parses the xml document and it finds the Start tag and end tag, it calls corresponding handler method.
Lets take an example to understand the implementation of SAX parser:

XML

<?xml version="1.0"?>
<company name="Google">
	<employee id="1001">
		<name>Ankit Pandoh</name>
		<salary>100000</salary>
		<address>Bangalore</address>
		<contact>99999</contact>
	</employee>
	<employee id="1002">
		<name>Sumit Malhotra</name>
		<salary>200000</salary>
		<address>Delhi</address>
		<contact>95338</contact>
	</employee>
</company>

Class SAXParserImplementation




package parser;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParserImplementation extends DefaultHandler
{
	private String xmlFile;
	private Employee employee;
	private String text;
	List<Employee> employees = new ArrayList<Employee>();

	public static void main(String args[])
	{
		String xmlFile = args[0];
		SAXParserImplementation parser = new SAXParserImplementation(xmlFile);
		parser.displayEmployee();
	}

	SAXParserImplementation(String xml)
	{
		this.xmlFile = xml;
		try
		{
			// tell the parser to parse the input file and notify the handler.
			this.getParser().parse(xmlFile, this);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private SAXParser getParser()
	{
		// Get Parser Factory to create a SAXParser
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = null;
		try
		{
			// Get parser instance using factory
			parser = factory.newSAXParser();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return parser;
	}

	/**
	 * Whenever the parser encounters the beginning of new element, it will call
	 * this method and empty the text buffer.
	 */
	public void startElement(String uri, String localName, String qName,
			Attributes attributes)
	{
		text = "";
		if ("company".equalsIgnoreCase(qName))
		{
			String company = attributes.getValue("name");
			System.out.println("Company Name : " + company);
		}
		if ("employee".equalsIgnoreCase(qName))
		{
			employee = new Employee();
			employee.setId(attributes.getValue("id"));
		}
	}

	/**
	 * This method will be called at the end of each element.
	 */
	public void endElement(String uri, String localName, String qName)
	{
		if ("employee".equalsIgnoreCase(qName))
		{
			employees.add(employee);
		}
		if ("name".equalsIgnoreCase(qName))
		{
			employee.setName(text);
		} else if ("salary".equalsIgnoreCase(qName))
		{
			employee.setSalary(Integer.parseInt(text));
		} else if ("address".equalsIgnoreCase(qName))
		{
			employee.setAddress(text);
		} else if ("contact".equalsIgnoreCase(qName))
		{
			employee.setContact(Integer.parseInt(text));
		}
	}

	/**
	 * When the parser encounters plain text (not XML elements), it calls(this
	 * method, which accumulates them in a string buffer
	 */
	public void characters(char[] buffer, int start, int length)
	{
		text = new String(buffer, start, length);
	}

	private void displayEmployee()
	{
		int i = 1;
		for (Employee employee : employees)
		{
			System.out.println("Details of Employee " + i + ":");
			System.out.println("ID :" + employee.getId());
			System.out.println("Name :" + employee.getName());
			System.out.println("Salary :" + employee.getSalary());
			System.out.println("Address :" + employee.getAddress());
			System.out.println("Contact :" + employee.getContact());
			i++;
			System.out.println();
		}
	}

	// Inner class Employee
	class Employee
	{
		private String id;
		private String name;
		private int salary;
		private String address;
		private int contact;

		public String getId()
		{
			return id;
		}

		public void setId(String id)
		{
			this.id = id;
		}

		public String getName()
		{
			return name;
		}

		public void setName(String name)
		{
			this.name = name;
		}

		public int getSalary()
		{
			return salary;
		}

		public void setSalary(int salary)
		{
			this.salary = salary;
		}

		public String getAddress()
		{
			return address;
		}

		public void setAddress(String address)
		{
			this.address = address;
		}

		public int getContact()
		{
			return contact;
		}

		public void setContact(int contact)
		{
			this.contact = contact;
		}
	}
}

Output

Company Name : Google
Details of Employee 1:
ID :1001
Name :Ankit Pandoh
Salary :100000
Address :Bangalore
Contact :99999

Details of Employee 2:
ID :1002
Name :Sumit Malhotra
Salary :200000
Address :Delhi
Contact :95338

Sunday, 9 June 2013

DOM (Data Object Model) Parser in Java

There are few ways to parse XML in java :

1. DOM Parser - A DOM is a standard tree structure, where each node contains one of the components from an XML structure. The two most common types of nodes are element nodes and text nodes. Using DOM functions lets you create nodes, remove nodes, change their contents, and traverse the node hierarchy.

2. SAX Parser - Simple API for XML (SAX), an event-driven, serial-access mechanism for accessing XML documents. This protocol is frequently used by servlets and network-oriented programs that need to transmit and receive XML documents, because it is the fastest and least memory-intensive mechanism that is currently available for dealing with XML documents.

With the DOM, the XML is broken down into three main pieces, called entities:

1. Elements (sometimes called tags)
2. Attributes
3. The data (also called values) that the elements and attributes describe

In this post I will demonstrate how to parse an XML file by using DOM parser technique.

Create a sample XML file


<?xml version="1.0"?>
<company name="IT">
 <employee id="1001">
  <name>Ankit Pandoh</name>
  <salary>100000</salary>
  <address>Bangalore</address>
  <contact>99999</contact>
 </employee>
 <employee id="1002">
  <name>Sumit Malhotra</name>
  <salary>200000</salary>
  <address>Delhi</address>
  <contact>95338</contact>
 </employee>
</company>

Create a class XMLParser to parse and display list of Employees

package parser;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class XMLParser
{
 Document dom;
 String xmlFile;
 List<Employee> employees = new ArrayList<Employee>();

 public static void main(String[] args)
 {
  XMLParser parser = new XMLParser(args[0]);
  parser.parseXML();
  parser.displayEmployee();
 }

 XMLParser(String xmlFile)
 {
  this.xmlFile = xmlFile;
  this.dom = getDomParser(this.xmlFile);
 }

 /**
  * obtain an instance of a factory that can give us a document builder.
  * obtain a new instance of document builder. obtain document object model
  * from the document builder
  */
 private Document getDomParser(String xmlFile)
 {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  try
  {
   DocumentBuilder docBuilder = factory.newDocumentBuilder();
   dom = docBuilder.parse(xmlFile);
  } catch (Exception e)
  {
   System.out.println(e.getMessage());
  }
  return dom;
 }

 private void parseXML()
 {
  NodeList employeeNode = dom.getElementsByTagName("employee");
  for (int i = 0; i < employeeNode.getLength(); i++)
  {
   Employee employee = getEmployee((Element) employeeNode.item(i));
   employee.setId(((Element) employeeNode.item(i)).getAttribute("id"));
   employees.add(employee);
  }
 }

 private Employee getEmployee(Element employeeNode)
 {
  String name = getTextValue(employeeNode, "name");
  int salary = getIntValue(employeeNode, "salary");
  String address = getTextValue(employeeNode, "address");
  int contact = getIntValue(employeeNode, "contact");
  return new Employee(name, salary, address, contact);
 }

 private String getTextValue(Element employeeNode, String tagName)
 {
  String textValue = null;
  NodeList textNode = employeeNode.getElementsByTagName(tagName);
  if (textNode != null && textNode.getLength() > 0)
  {
   textValue = textNode.item(0).getFirstChild().getNodeValue();
  }
  return textValue;
 }

 private int getIntValue(Element emp, String tagName)
 {
  int textValue = Integer.parseInt(getTextValue(emp, tagName));
  return textValue;
 }

 private void displayEmployee()
 {
  int i = 1;
  for (Employee employee : employees)
  {
   System.out.println("Details of Employee " + i + ":");
   System.out.println("ID :" + employee.getId());
   System.out.println("Name :" + employee.getName());
   System.out.println("Salary :" + employee.getSalary());
   System.out.println("Address :" + employee.getAddress());
   System.out.println("Contact :" + employee.getContact());
   i++;
   System.out.println();
  }
 }

 class Employee
 {
  private String id;
  private String name;
  private int salary;
  private String address;
  private int contact;

  Employee(String name, int salary, String address, int contact)
  {
   this.name = name;
   this.salary = salary;
   this.address = address;
   this.contact = contact;
  }

  public String getId()
  {
   return id;
  }

  public void setId(String id)
  {
   this.id = id;
  }

  public String getName()
  {
   return name;
  }

  public void setName(String name)
  {
   this.name = name;
  }

  public int getSalary()
  {
   return salary;
  }

  public void setSalary(int salary)
  {
   this.salary = salary;
  }

  public String getAddress()
  {
   return address;
  }

  public void setAddress(String address)
  {
   this.address = address;
  }

  public int getContact()
  {
   return contact;
  }

  public void setContact(int contact)
  {
   this.contact = contact;
  }
 }
}

Now, I am going to explain each and every step in detail:

1. Obtain an instance of a factory that can give us a document builder.
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

2. Obtain a new instance of document builder.
    DocumentBuilder docBuilder = factory.newDocumentBuilder();

3. Obtain document object model from the document builder.
    dom = docBuilder.parse(xmlFile)

4. Invoke parseXML(). Get List of EmployeeNodes
    NodeList employeeNode = dom.getElementsByTagName("employee")

5. As we can see there are two employee tags in our XML, we will pass one node at a time to    getEmployee(Element employeeNode) method which in turn calls the getTextValue(employeeNode, "name") mehod .

6. private String getTextValue(Element employeeNode, String tagName)
   {
String textValue = null;
NodeList textNode = employeeNode.getElementsByTagName(tagName);
if (textNode != null && textNode.getLength() > 0)
{
textValue = textNode.item(0).getFirstChild().getNodeValue();
}
return textValue;
   } 
In this method, we will get the list of element having tagName which is passed from the  getTextValue() method. Here this is "name". getFirstChild() will look for the next element tag which is "name" in this case and returns its value.

7. getEmployee() method will return the new Employee object which gets added to the List<Employee>

8. Invoke displayEmployee() to display list of employees object.

9. I have created a Inner class Employee in this case. This can be done separately also.

Output:

Details of Employee 1:
ID :1001
Name :Ankit Pandoh
Salary :100000
Address :Bangalore
Contact :99999

Details of Employee 2:
ID :1002
Name :Sumit Malhotra
Salary :200000
Address :Delhi
Contact :95338