Home > Guides > Programming > Java

Toggle Open Guide Table of ContentsGuide Contents

Close Table of ContentsGuide Contents

Close Table of Contents

Building Java Applications with Ant

Last updated Jan 26, 2007.

When you need to build your Java projects, you have several options in build tools, but probably the most prevalent tool on the web is Apache Ant. This introduction to Ant will help you setup your own projects as well as help you understand any of the hundreds of open source projects that rely on Ant.

Ant Defined

Apache defines Ant as follows:

"Apache Ant is a Java-based build tool. In theory, it is kind of like make, without make’s wrinkles."

They further emphasize that Ant was created because Ant's original author was not satisfied with the limitations of existing build tools when developing software across multiple platforms. Existing build tools were inherently shell-based and provided substantial capabilities for extension, but because they were shell-based, they were too tightly coupled with the operating system in which they were run. This means that building software targeted at multiple platforms requires separate build tools for each deployment platform.

They continue,

"Ant is different. Instead of a model where it is extended with shell-based commands, Ant is extended using Java classes. Instead of writing shell commands, the configuration files are XML-based, calling out a target tree where various tasks get executed. Each task is run by an object that implements a particular Task interface."

In short, Ant is an extensible XML-based build tool that runs in a Java Virtual Machine, which permits it to run seamlessly on any platform with a supported JVM. And any functionality that is missing from Ant can be built through a Java-based extensible interface, which will greatly aid us when integrating performance testing into our builds.

Building a Java application with Ant

An Ant build scripts is an XML document, typically named build.xml. This XML build script contains a single project that represents your application and a set of one or more targets that Ant will perform. A target may tell Ant to compile your source code or build a JAR file. Common build targets are shown in table 1.

Table 1. Common Build Targets

Target

Description

init

Initializes the build environment

compile

Compiles source code

dist

Create distribution files such as JAR and WAR files

clean

Clean up the build environment by deleting all compiled source code and distribution files

test (or tests)

Execute unit tests

Targets are hierarchical in the sense that one target can depend on the successful completion of other targets. For example, the "dist" target probably depends on the "compile" target, which in turn depends on the "init" target. After all, you really want your source code compiled before you build a JAR file that contains it.

Listing 2-1 shows a sample build script.

Listing 2-1. Sample build script

<project name="MyProject" default="dist" basedir=".">

 <description>
   Project Description
 </description>

 <!-- set global properties for this build -->
 <property name="src" location="src"/>
 <property name="build" location="build"/>
 <property name="dist" location="dist"/>

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

 <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="dist" depends="compile"
    description="generate the distribution" >
  <!-- Create the distribution directory -->
  <mkdir dir="${dist}/lib"/>

  <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file -->
  <jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/>
 </target>

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

Listing 2-1 can be broken down into the following sections:

  1. Description: the <description> tag contains a description of your project for your own use
  2. Build script initialization: your build script will undoubtedly need initialization parameters. In this case we define the directory location for the source code, the directory where compiled source code is built, and the directory where our final distributable files, such as JAR, WAR, and EAR files, are to be stored. In addition to specifying locations, properties can specify "value" attributes.
  3. Init target: the "init" target is used to initialize the build environment. In this case the build script obtains the timestamp when the build starts (for consistent naming and labeling) and then creates the build directory.
  4. Compile target: the "compile" target is dependent on the "init" target, which means that the "init" target will be executed prior to starting the "compile" target. It uses the <javac> Ant task to compile all source files found in the source directory to the build directory. Later we will refine this to include only the source files that we identify.
  5. Dist target: the "dist" target is dependent on the "compile" target, which means that both the "compile" and "init" targets will be executed prior to the start of the "dist" target. The "dist" target creates a "lib" folder in the distribution directory and then uses the <jar> Ant task to build a JAR file in the distribution's lib folder containing all files in the build directory. Again we will refine this later to include filters to only archive specified files.
  6. Clean target: each build script that you write should have a "clean" target to cleanup then entire environment so that all source files will be compiled and all archives will be rebuilt on the next build. In this case we simply delete the build and distribution directories.

Ant can be considered a pluggable framework, and through the mechanisms of Ant tasks, you can plug in additional functionality. The Ant manual can be accessed online through the following website:

http://ant.apache.org/manual/

If you navigate to "Ant Tasks" and then choose "Overview of Ant Tasks" you will see a list and a description of all Ant tasks. The left navigation pane allows you to quickly navigate to the core tasks and to optional tasks. The core tasks provide you with all that you need to build your projects while the optional tasks include external tasks (functionality not built into Ant) such as JUnit integration.

Table 2 lists some of the more interesting Ant tasks that you should be familiar with.

Table 2. Common Ant Tasks

Task

Description

Javac

Compiles a Java source tree; intelligently scans through a source tree looking to compile Java files that have no corresponding .class file or where the class file is older than the .java file. A javac node is a fileset node that can specify a set include and exclude patterns to customize the file list to be compiled (more on this below).

Jar

Creates a Java Archive (JAR) containing a set of files. This node too is a fileset so that you have more fine-grained control over the files to be included in the JAR

War

This is an extension of the Jar task with specific knowledge of the Web Archive directory structure. Specifically it defines an attribute named "webxml" that specifies the web.xml file for the archive, a "lib" nested element that specifies all files that should be stored in the WEB-INF/lib folder, a "classes" nested element that specifies all files that should be stored in the WEB-INF/classes folder, a "webinf" nested element that specifies all files that should be stored in the WEB-INF folder, and finally a "metainf" nested element that specifies all files that should be stored in the META-INF folder.

Ear

This is an extension of the Jar task with specific knowledge of the Enterprise Archive directory structure. Specifically it defines an "appxml" attribute that references the enterprise application's application.xml file and a "metainf" nested element that specifies all files that should be stored in the META-INF folder.

Javadoc

This task is used to generate code documentation with the javadoc tool. Your code should have specific Javadoc comments defined in it to expose the purpose of classes, methods, and public attributes. This task provides fine-grained control over the behavior of the javadoc tool, so I encourage you to read more in the Ant manual.

Java

This task is used to execute a Java class within the Ant JVM or fork a new JVM if specified. Thus through this task you can execute any Java application and you can send it input, such as the location of build directories and so forth.

Ant

This task is used to execute Ant on a specified build file. Most commonly this task is used to build subprojects.

Mail

This task is used to send SMTP emails. Most commonly this is used to notify team members when a build completes, but it can also be used to distribute files because it can send attachments such as build log files and the final distributable files.

Get

Gets a file from a URL, including support for the following URL schemas: http, ftp, and jar. This is useful if you need to obtain certain files maintained on a server somewhere. For example, at my company we have certain native components that require that Microsoft Visual Studio be installed to build. Rather than require all developers to install Visual Studio, the compiled files are built on the server and retrieved by Ant during the build.

Additionally there are a set of helper tasks that perform common operations that you will need, these include: Copy, Delete, Mkdir, Move, Unjar, Tar, Untar, Unwar, Zip, Unzip, GZip, and GUnzip. Again, refer to the Ant manual for more details on each of these tasks. And for those of you using CVS, there are a set of CVS tasks built into Ant's core: Cvs, CvsChangeLog, CvsVersion, CVSPass, and CvsTagDiff.

Summary

Apache Ant is a Java-based build tool driven by an XML build script that has gained mass acceptance across the Internet and open source projects. By building your projects using Ant you can seamlessly build on any operating system and your fellow developers can use any IDE. Furthermore, its extensible architecture allows you to do anything with Ant that it does not do out of the box.

Discussions

Read and display the table in the document
Posted Nov 12, 2008 06:01 AM by StrongHead
1 Replies
Correction
Posted Nov 4, 2008 06:09 PM by youssef.mohammed
1 Replies
Instead of synchronising getInstance
Posted Nov 3, 2008 05:42 AM by grahamkelly
1 Replies

Make a New Comment

You must log in in order to post a comment.

Related Resources

Dustin SullivanIf You Are New to Java Programming...
By Dustin SullivanJune 2, 20092 Comments

We recently sat down with several top Java developers to talk about that state of the language as we approach this year's JavaOne.  As we were wrapping up, we threw one last question at them out of curiosity, and we thought you'd like to see what some of them said.

Steven HainesOracle Buys Sun of $7.4B
By Steven HainesApril 20, 2009 No Comments

In a stunning turn of events, Oracle steps in and buys Sun amist the breakdown of IBM's attempt to acquire Sun.

Steven HainesIBM in talks to buy Sun Microsystems for at least $6.5B
By Steven HainesMarch 18, 2009 No Comments

Reuters reported this morning that IBM is in talks to buy Sun Microsystems, which could "bolster their computer server products against rivals such as Hewlett-Packard Co."

See More Blogs

Informit Network