Thursday, March 15, 2012

Getting Started with Apache Ant

Prerequisite: 
  1. Java environment installed (Make sure that environmental variables JAVA_HOME is set to the directory where your JDK is installed and JAVA_HOME  is added to PATH)
Installation:
  1. Download the latest stable version of Ant from the Ant web page http://ant.apache.org/
  2. Unzip the downloaded file into a directory in your local drive.
  3. Set environmental variables JAVA_HOME to your Java environment i.e to the directory where your JDK is installed.
  4. Set the ANT_HOME environment variable to the directory you unzipped Ant to or where you installed Ant.
  5. Add %ANT_HOME%/bin (for Windows) to your PATH
Creating build file:
It is an xml file generally referred by build.xml 
  1. Create a project(create package and test classes to be execute) or open existing project.
  2. Create a file namely 'build.xml' parallel to 'src' directory.
Apache Ant's build file structure:
  1. Build file contains one project and at least one (default) target.
  2. The main components of ant are property, path, target, task etc.
A sample build file is shown below:

//build.xml
  1. <project name="GoogleSearch" default="compile" basedir=".">
  2.     <property name="src.dir" value="src" />
  3.     <property name="lib.dir" value="lib" />
  4.     <property name="build.loc" value="${build}" />
  5.     <property name="classes.dir" value="${build.loc}/classes" />
  6.    
  7.     <path id="classpath">
  8.         <pathelement location="${classes.dir}"/>
  9.         <fileset dir="${lib.dir}" includes="*.jar"/>
  10.     </path>
  11.        
  12.     <target name="compile">
  13.         <javac destdir="${classes.dir}" includeantruntime="false" debug="true" srcdir="${src.dir}">
  14.             <classpath refid="classpath"/>
  15.         </javac>
  16.         <echo> /* Compiled Directory Classes */ </echo>
  17.     </target>
  18. </project>

Run Build file:
We can run an ant file from
  1. IDE(in my case eclipse) by right click on build.xml -> Run as -> Ant Build
  2. Command line by ant <target>  
In first case the default target assigned to ant's project will run and in second case if you 'll run simply ant it 'll run the default target assigned or ant <target> 'll run the specific target you have given in command line.
        In the above sample build.xml, when it 'll run, it 'll execute the 'compile' target of build file which 'll compile all the classes under 'src' directory of the project.

No comments:

Post a Comment