Using ANT for Java Development Builds

24 Nov 2008

Objectives
  • Getting familiar with installation of ANT and setting classpath to be able to run ANT tasks
  • Get a top level view of using ANT to compile and run Java applications
  • Writing a simple ant build script
Software requirements
  • Apache ANT 1.7.0 - http://apache.ant.org
  • Java SDK 1.6 ( Java 1.5 would still work, but I prefer to run the latest stable release )
  • Simple XML editor [optional]. You can possibly use Notepad2 if you are running windows or use Vim if running Linux.

Before we actually dive into the installation and running ANT, let us understand what ant is and then we might have a strong reason on why one should use ANT scripts in their projects.

What is ANT? Why use it?

Apache ANT is one of the most widely used build tool. I am pretty sure most of you have worked with Make files and if Make is the ultimate build tool for any applications on Linux, Ant is the equivalent edition used mostly for Java applications ( and could be used for .NET applications too, but not many really care ). While Makefiles use plain text instructions, Ant uses XML based instructions. These xml files are usually called Ant Scripts, even though they do not have any script as such. It is just a set of tasks that we define, that we ask the ant tool to execute for us, thereby automating almost any process in a software development lifecycle. Ant pre-defines a set of tasks for compiling packages, running Java programs, creating JAR or WAR files, running Unit tests and a lot more. Ant is used across the industry, for its simplicity, portability and especially the power it brings to automation. You can integrate Ant with most of the popular IDE like Eclipse and Netbeans. Infact Netbeans generates an Ant script and it is executed whenever you build or run a file or a project. In the second tutorial, we look at how to integrate Ant with Eclipse and Netbeans.

Apart from the sheer simplicity that it brings into development process, to be practical, it adds value to your resume. As already mentioned, Ant is used scross the industry and as a prospective developer, you are required to be able to write Ant scripts. Coming back to the non-practical view, Ant scripts is the best way you can automate your process. Consider a simple Client-Server Program where you are required to first compile the programs, start the server, then start the client and each time you do that, even if you use IDE, you are supposed to do some amount of work. But with ant, you can automate the entire process. After the tutorial 2, you would still use IDE but would use Ant scripts to build and run your code. You would use IDE for debugging purposes, unless someone comes up with a tutorial on how to use Command line debugger that ships with JDK. Ok, enough of the theory, lets get started with some practical stuff!

Installing ANT
  1. Download Ant toolkit from http://mirrors.kahuki.com/apache/ant/binaries/apache-ant-1.7.0-bin.zip
  2. Extract the archive on to your local file system. Usually I place all my development tools in a special folder in D: drive called "development". This helps me quickly find any development tool, whenever needed.
  3. Now you need to add Ant to your command prompt path. I assume you are using Windows (for setting classpath on Linux, please visit my blog entry *here).
  4. If you path is set, then you can just type the command "ant" in any command prompt window and the command prompt would be able to locate your ant executable. To set the classpath on Windows,
    1. Right click on My Computer. Go to Properties and select the Advanced tab page. (In Vista, you right click on Computer, Go to Properties and then go to Advanced tab)
    2. Click on Environment variables. You get a new dialog window (image shown below). There are two types of variables, User and System Variables. We would now add a System Variable. To do that, first click New … button and create a new variable called "ANT_HOME". In the variable value, you give the path to the directory of Ant. In my case, it is "D:\Development\Apache-Ant-1.7.0". Click ok and now you see a new ANT_HOME variable set.
    3. Scroll down the list to locate "Path" variable. Select the variable and then click on Edit.. button. Now in the variable value textbox, append the statement "%ANT_HOME%\bin". A variable can have multiple values in which case, we seperate them using ";". The new value should look something like "previous values;%ANT_HOME%\bin". Take a look at the image shown below.

image

  1. Now test to see if you have correctly set your path. To do this, go to command prompt and type "ant". If everything works fine, you should see a message which says "build.xml does not exist!". This also should tell you that, default script file that ant looks for is a build.xml (in case of make it is Makefile)

Assuming, Ant is setup and ready to use, we would now write a simple "Hello" program in Java. The program takes in a command line argument and prints a message along with the argument passed.

Sample Java Program
package truebuddi.learning.ant;

import java.lang.*;

public class
HelloAntWorld
{
public static void main(String[] args)
{
if(args.length<1)
{
System.out.println("Invalid number of arguments. Program terminating ... ");
return;
//or System.exit(-1);
}

//if the execution reaches here, argument have been passed accurately.
System.out.println("Welcome to Ant world! I hope you executed the program via Ant");
String message = String.format("Arguments you passed : %s",args[0]);
//Looks like C format specifiers ! Yes it is!
System.out.println(message);
// print the message.
}
}



Save the file at a location like "D:\projectFolder\src\truebuddi\learning\ant\HelloAntWorld.java" (The section in bold should match with your package statement. I would then place my ant build file at "D:\projectFolder\build.xml". My directory structure looks like shown below.



image



Writing your first ant script


Now let us write a simple ant script that has two tasks - first to compile the program and the second to run the program. The complete Ant script looks something like shown below. Reference: http://ant.apache.org/manual/index.html



<!-- default=compile implies, the default task that is run when ant executes this script is the compile task -->
<
project name="LearningAnt" default="compile" basedir="."
>
<
description
>
First Ant build script to compile and run truebuddi.learning.ant.HelloWorld program
</description
>
<!--
set global properties for this build
-->
<
property name="src" location="src"
/>
<
property name="build" location="build"
/>

<
target name="init"
>
<!--
Create the build directory structure used by compile
-->
<
mkdir dir="${build}"
/>
</
target
>

<!--
depends="init" implies that before compile is actually run, init is executed
-->
<
target name="compile" depends="init" description="compile the source "
>
<!--
Compile the java code from ${src} into ${build}
-->
<
javac srcdir="${src}" destdir="${build}"
/>
</
target
>

<
target name="execute" depends="compile" description="Run the program"
>
<
java classname="truebuddi.learning.ant.HelloAntWorld"
>
<
arg value="I am running this from Ant!"
/>
<
classpath
>
<
pathelement location="build"
/>
</
classpath
>
</
java
>
</
target
>

<
target name="clean" description="clean up"
>
<!--
Delete the ${build} and ${dist} directory trees
-->
<
delete dir="${build}"
/>
<
delete dir="${dist}"
/>
</
target
>

</
project
>




  • Important points

    • Please take a look at default="compile" and depends="xxxx" attributes in the script. Read the comments.


    • javac is used as a tag which is a pre-defined ant task. It executes the java compiler on the code in the "src" folder and copies the output to build folder. Right now in this example, we do not use external libraries and if used we would have had them within classpath tags in the ant file. It would be evident in the future tutorials. For now, we just let the ant know that our classpath would have 'build' directory.


    • There are four target operations that ant can execute - init, compile, execute and clean.





Running the ant script


Having saved the above xml as "build.xml" in the project root folder, go to command prompt and navigate to the root. Run the following commands

1. To compile the program, run "ant". Since the default target is compile, the program would compile and you get output something like shown below.



image



2. To run the program, run the command "ant execute".



image



[Optional] The program could be executed as "java -classpath buddi truebuddi.learning.ant.HelloAntWorld message"



I hope this tutorial would get you started with using Ant to compile and run Java Programs. I have even shown you on how to set classpath in ant scripts, how to pass arguments to Java programs, shown you the ant tasks like java, javac, mkdir ,etc.