Getting started with Apache Ant

What is Apache Ant

Apache Ant is a build automation tool. It helps you to automate all the repetitive tasks like compiling, creating jar files, running JUnit test cases, creating java docs and a lot more, which would be a hectic process if done manually. Although Apache Ant can be used to automate any process, it is commonly used for building Java applications.

Installing and configuring Apache Ant

  • Head on to http://ant.apache.org/ and download the required ANT.
  • Make sure you have JDK installed, and JAVA_HOME is set
  • Set ANT_HOME to your ANT directory (eg: C:\apache-ant-1.9.9)
  • Add ${ANT_HOME}/bin to PATH. (Or %ANT_HOME%\bin  for windows)
  • Type ant -version  in your terminal to see whether your ant is installed correctly.

Creating the first Ant script

Create a directory where we are going to put our first script. create a file named build.xml in it.

Open the terminal (or command prompt) and go to the directory you just created. Type the command ant
If you see the message “My first message!” congratulations, your first ant script just worked!

The first script explained

XML prolog

Since ant scripts are written in XML files, you’ll need to write the XML prolog before anything.

  <?xml version="1.0"?>

Make sure you don’t accidentally insert any whitespace before it, or the script won’t run.

target: 

Targets are similar to functions used in java. They perform a set of tasks and can be invoked using its name. In our example, we have created a target named ‘mytarget’. You could name it anything you want.

project: 

All ant scripts require a project element. In our script, we’ve given the name myfirstscript to our project and set mytarget as default target. That means if you simply type ant command, mytarget will be executed. This target can also be called directly using  ant mytarget command.

Compiling and running Java project

Create source directory inside your project directory and create the HelloWorld.java in it.

Edit the build.xml file to look something like this. Don’t copy paste if you are learning.

This script should compile your HelloWorld.java file and print the “Hello, World! ” message.

Generating java docs

Ant has inbuilt support for generating Javadoc. The code is self-explaining, so I’ll skip for now.

Running JUnit test cases

We’ll better take a step by step approach:

Specify additional directories needed for test files

Now we better declare a classpath which can be referenced later, like while compiling test files.

 

Oh! And you’ll need junit-4.12.jar and hamcrest-core-1.3.jar in your lib/test directory.

Obviously, the next thing will be to compile our test source files

Now we are ready to run test cases

Try out on your own and see how it works! In case you need more reference, get the full source code here.

Leave a Reply

Your email address will not be published. Required fields are marked *