Wednesday, March 18, 2009

Getting started with Ant

Each one of us has used Ant knowingly or unknowingly, while building our projects. But, most of us are not aware of its existence. Thanks to IDEs like Eclipse & NetBeans !!

But, I feel that one must know how things happen. How a series of commands are executed when you build your project and how you can control and alter this flow.

This entry is not meant to give you insight into the build process but it is meant to introduce the tool (Ant) to beginners like me. We will go through installation and normal usage of Ant Tool.

So, lets get started :-)

What is ANT ?

Ant is a Java-based build tool used for automating the build process.
Ant is written in Java and that's what makes it platform-independent. This also means that you lose out on doing certain things (issuing certain OS-specific commands in build.xml) that could be done fastly in a OS-dependent manner.
ANT is an acronym for "Another Neat Tool". :-)
It accepts input in form of XML files (like build.xml) and can be used to perform repeatitive task in an efficient manner.

Installing ANT

Download the binary distribution from here.
Now, all you have to do to install ant and run from command line is to set following environment variables:
  • ANT_HOME : Set this variable to the path where you have unzipped the downloaded binary distribution
  • PATH : Append the ANT_HOME/bin to the already existing PATH value. This is needed so that we can run ant from command line.
  • JAVA_HOME : Set this variable(if not already set) to the path where JDK is installed
And Bingo !! you are done with installation. It's time to test whether we have installed Ant correctly or not

Test Your Installation

To test whether you have successfully installed Ant or not, type
>ant
on command line and press enter

It will give an error like
Buildfile: build.xml doesn't exist!
Build failed
because right now there is no build.xml file existing in the current directory. Ant tool makes use of build.xml to automate the build process.

Congratulations !!
You have successfully installed ANT if you can see this error message. :-)

What is build.xml ?

It is nothing but a normal XML file that is used to automate the build process. It contains certain commands that are executed in a defined/prescribed manner. You can think of it as writing a Shell Script which will be executed by Ant tool. Actually it's more like a make-file that we have in Linux/Unix environment.

A normal build.xml file would consist of following sections, in that order:
  1. Clean - It removes all the previously deployed files of the same application, if any.
  2. Init - Creating the directories and subdirectories according to your choice
  3. Compile - Used to compile the *.java files & servlets or jsp's with the help of libraries
  4. Copy - It copies the compiled class files and servlets in their appropriate locations
  5. Create-war - Finally, we create a .war file of our application and copy it to your server's deplyoment directory so that you can run the application.
All these steps are not neccessary and it depends entirely on you that what you wanna keep in your build.xml.
A look at a simple build.xml would simply what seems so tough right now. :-)


BUILD.XML


Lets see what it really means:

1. Root Element



First line tells us that it is a XML file.
Then comes the root element, project. Rest of the code for this project will come in between project tags. It has 3 attributes:
  1. name (optional) - Name of the project
  2. default (required) - The default target to use when no target is specified
  3. basedir (optional) - This tells the basedir for all the paths mentioned in the in this script. If it is missing, then parent directory of this build script will be used as basedir

2. User-defined variables



These 2 lines declare user-defined variables which are used later in the file.
src holds the location of the current directory as given by '.'
build holds the location "basedir/build" where basedir was defined in project name above.
Remember all the paths mentioned are relative to basedir

So, property tag is used to give name-value pairs, but same effect could have been achieved by mentioning these name-value pairs in an external file (named build.properties) and using them in build.xml as they are used now.


3. Clean your earlier deployment



Target tag is like a function which you can call again to perform a reusable task.
These lines are pretty simple to understand.
The echo tag will echo/display whats written to the output console, and the delete command will delete the build directory

${build} is way to evaluate the build variable that we have defined above using property tag

4. Initialization - Creating Directory Structure for deployment



Here, we just create a directory using mkdir command.
The thing to note here is the depends attribute of target tag. This attribute is used throughout build.xml to create a chain of targets, to give a sequential flow i.e. it helps in specifying the dependencies of one module over another and tells us how the targets will be called.


5. Compiling source files and copying them to destination folder



This function compiles the source files present in src directory and stores the resulting .class files in build directory.
I have deliberately not added more steps like creating a war file and deploying it on server, because that would make this entry long and complicated un-neccessarily. Time to run what we have done so far.

Running this script

To run this script, create a folder and name it Test and copy this build.xml file in it. And to test whether your script works or not, create any correct java file in this Test folder, which we will compile.

Your directory structure should look like this.

Test
|
|------ build.xml
|
|-------HelloWorld.java


To run your build script, go to Test Folder, and type ant

C:\Users\Agraj\Desktop\Test>ant

If everything goes correct, it will give output

Buildfile: build.xml

clean:
[echo] Deleting build
[delete] Deleting directory C:\Users\Agraj\Desktop\Test\build

init:
[echo] Creating new directory: build
[mkdir] Created dir: C:\Users\Agraj\Desktop\Test\build

compile:
[echo] Compiling source files present in . to build
[javac] Compiling 1 source file to C:\Users\Agraj\Desktop\Test\build

BUILD SUCCESSFUL
Total time: 2 seconds

For starters, it doesn't and shouldn't work right away :-)
I said shouldn't because if it does, then perhaps you won't enjoy and learn more about Ant.

Having said that, the problem that occurs most commonly is that Ant tool is unable to parse the build.xml file correctly. This is so because even a space or tab inserted in xml file can cause Ant to fail. You can get to know about the extra spaces/tabs using vi editor on linux/unix machines, but it can be pretty frustating on windows to look out for such an error

Although, most of us will never change the build.xml while development but still it helps a lot when you know what happens when you build your project and you don't feel alien to the environment :-)

Random Notes :
  • Make sure that your CLASSPATH variable doesn't have any single quotes or double quotes ( ' or " ) in it even if there is a space in the path because, the presence of them will make ANT to fail.
  • Also make sure that there is no ending forward or backward slash ( / or \ ) in your CLASSPATH
  • For more on Ant, please refer to FAQ section here
  • For detailed installation from source or for setting optional parameters/preferences, one can go to the docs/manual/index.html page of the installation directory
Any comments, suggestions and corrections are welcome and required !!

2 comments:

Charles Lucier said...

Thanks for sharing this! I was browsing looking for a simple example on how to run ant.

Charles Lucier said...

Thanks for sharing! I was looking for a simple example with ant.