- Java Reference Guide
- Overview
- Table of Contents
- J2SE: Standard Java
- Java Windows NT Services
- Advanced J2SE
- J2SE 1.5.0: "Tiger"
- Java SE 6
- Core Computer Science Principles in Java (Data Structures)
- Annotations
- Java Generics
- Java New I/O
- Java Sound
- Java Applets
- JavaFX
- Java SE Threading
- Resource Management Using Semaphores
- Java Atomic Operations
- JavaTemplate Pages
- Executing Templates with the JtpExecutor
- Java Cryptography Extensions (JCE)
- Java Database Connectivity (JDBC) API
- Jakarta Commons - Net Class Library
- Jakarta Commons HttpClient
- Apache POI
- Regular Expressions
- JavaMail
- Cool Tools
- Building an Really Simple Syndication (RSS) Java App
- Logging with Log4J
- Inside Swing
- Swing Components
- SwingX
- Swing Styled Documents
- Web Rendering in Java Swing Applications
- Java Look-and-Feel Graphics Repository
- Java Media Framework
- Quicktime for Java
- Media in Java Review 2008
- Graphs and Charts
- Holiday Special: Electronic Greeting Card
- Media Framework: Presenter Application
- Standard Widget Toolkit
- JFace
- Java Performance Tuning
- J2EE Performance Tuning
- Caches and Pools
- Java Caching System
- Java Compression and Decompression
- Obfuscating Java Applications
- Continuous Integration
- Load Testing
- Tomcat Clustering
- Enterprise Java Testing
- Automated Unit Testing with JUnit and Ant
- Unit Testing: Tips From The Trenches
- Custom Ant Tasks
- Extensible Markup Language (XML)
- Java Web Technologies
- Web Frameworks
- Struts 2
- Wicket
- JavaServer Faces
- Distributed Programming / RMI
- Servlet Filters
- Building a Robust Java Server
- J2EE: Enterprise Java
- Spring
- Java Design Patterns
- XDoclet
- Hibernate
- Project Backup
- J2EE Project: Hands-On
- Enterprise Java Beans (EJB) 3.0
- Disaster Recovery
- Java Management Extensions (JMX)
- Service-Oriented Architecture
- Web Services
- RESTful Web Services New
- Project: Building a Web Photo Gallery
- J2ME: Micro Java
- Specialized J2ME
- Optional Packages
- Other Java Technologies
- Derivatives and Competitors
- Java, Engineered for Integration
- Additional Resources
- The World of Java Tools
- Building Java Applications with Ant
- Managing Java Build Lifecycles with Maven
- Source Control with Subversion
- Inversion of Control and Dependency Injection
- Certification
- Roadmap: Becoming an Enterprise Java Developer
- Roadmap: Becoming an Enterprise Java Developer in 2007
- The Business of Enterprise Software
- JavaOne 2006
- JavaOne 2007
- JavaOne 2008 Wrap-Up
- JavaOne 2009 Wrap-Up
- How to Survive in a Turbulent Job Market
- How to Hire the Best Talent
- Cloud Computing
- Enterprise Java in 2008 and Beyond
- Predictions for 2018
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:
- Description: the <description> tag contains a description of your project for your own use
- 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.
- 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.
- 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.
- 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.
- 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:
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. |
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.




Account Sign In
View your cart