Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Creating Standard Ant Targets and What They Should Do

In every project that you do, and in just about every build file that you encounter, certain targets keep popping up. It helps to give these targets standard names so that everyone understands what the task does. Let's think about what you need to do in most projects. You need to set properties, create directories, compile, test, report on the tests, jar, perhaps war (if it's a Web app), generate JavaDocs, and deploy. You can name the corresponding targets accordingly. Here is a short list of common target names and what they do:

  • init sets properties for the entire build

  • prepare creates a build directory, test results directory, and so on

  • fetch fetches your source code updates from a source code repository

  • compile compiles, obviously

  • test executes JUnit tests and generates reports

  • jar creates a JAR file

  • war creates a WAR file

  • docs generates JavaDocs documentation

  • deploy copies or FTPs the JAR/WAR/EAR to a deployment machine

Steve Loughran, in "Ant In Anger," also suggests the following targets:

  • build performs an incremental build

  • publish to "output the source and binaries to any distribution site"

  • all performs an entire build from start to finish

  • main performs a default build; generally just a build and test

  • init-debug is called from init to set up properties for a debug build

  • init-release is called from init to set up properties for a release build

  • staging moves the complete project to a pre-production area

Let's discuss each of these targets and what they do.

Setting Properties with the init Target

The init target's duty is to set properties and not much else. So, it will basically be a bunch of <property> tags that set up all the properties you'll use in any target in your build file. Or, it could contain one statement that looks like Listing 3.6.

Listing 3.6 Loading Properties from a File

<target name="init">
  <loadproperties srcFile="build.properties"/>

As you can see, the <loadproperties> tag takes a .properties file and loads it up as Ant properties. This is equivalent to you setting them all in individual <property> statements. Chapter 4, "Built-in Tasks," has more information about this.

Another important thing to do in init is to set up a path-like structure that will be used as your class path. I cover this topic later in this chapter, but Listing 3.7 gives an example.

Listing 3.7 Building a Path-Like Structure

<target name="init">
  <loadproperties srcFile="build.properties"/>
  <path id="classpath">
    <pathelement path="${oro.jar}"/>
    <fileset dir="${struts.dir}">
      <include name="*.jar"/>
  <property name="classpath" refid="classpath"/>

If you heed Mr. Loughran's suggestion to have init targets set up things differently depending on whether you are doing a debug or release build, you would define init-debug and init-release targets. Each of these will either directly set properties that they need, or will load a different properties file. To determine which one will be called, you can make use of command-line properties and the unless and if attributes of Ant targets. Listing 3.8 shows an example of this.

Listing 3.8 Using Discrete init Targets for Debug and Release Builds

<target name="init">
  <property name="name" value="chapter3"/>

<target name="init-debug" unless="release.build">
  <loadproperties srcFile="debug.properties"/>

<target name="init-release" if="release.build">
  <loadproperties srcFile="release.properties"/>

<target name="prepare" depends="init, init-debug, init-release">
  <!-- other tasks -->

Notice the presence of an unless attribute in init-debug and an if attribute in init-release. These attributes conditionally execute a target if a certain property has been defined or unless a certain property has been defined. Here, if you execute Ant with -Drelease.build=true on the command line, init-release will be executed; otherwise, init-debug will be run. By putting both targets in the prepare target's depends attribute, the proper target will be called based on the presence or absence of the release.build property.

The listing also has an init target that could set up properties that will be useful regardless of the type of build being conducted.


In "Ant In Anger," Mr. Loughran suggests that to do this, you should define the two init-xxx targets, and then use the <antcall> task to execute them. This obviously worked in a previous version of Ant, but in the current releases, any properties set in a target that is executed via <antcall> will be visible only inside the target that is being called with <antcall>. This is definitely not what you want.

Preparing the Environment with the prepare Target

The prepare target doesn't generally do much, but it's important nonetheless. You'll typically want to create your ${build.dir} and any subdirectories under it in the prepare target. If you'll be using the <record> task, this would be a good place to start it recording. <record> is covered in Chapter 5. Listing 3.9 shows a typical prepare target, turning on a recorder at the same time.

Listing 3.9 A Typical prepare Target

<target name="prepare" depends="init">
  <mkdir dir="${build.dir}"/>
  <record name="${name}.log" action="start"/>

Fetching Source Code from a Repository with the fetch Target

If you're on a project with more than a person or two, you'll most certainly store your source code in a repository of some sort, such as CVS or SourceSafe. You'll need a target to get the latest code updates from the repository so that you can ensure your code integrates with that of the rest of the team. The fetch target accomplishes this. You probably don't want to call this target every time you do a build because of the time it takes to get updates, but you do want it to be available when you need it. Listing 3.10 shows an example of getting source updates from CVS.

Listing 3.10 Fetching Code Updates with the fetch Target

<target name="fetch" depends="prepare">
  <cvspass cvsroot="${cvsroot}" password="${repo.pass}"/>
  <cvs cvsRoot="${cvsroot}" command="update -P -d" failonerror="true"/>

Compiling Your Classes with the compile Target

After you've set up the build directory it's time to compile your Java classes. The <javac> task makes building Java applications so much easier than doing it by hand. You generally don't need anything in this target other than <javac> itself. Listing 3.11 shows this.

Listing 3.11 A Typical compile Target

<target name="compile" depends="prepare">
  <javac srcdir="${src.dir}"

Testing and Reporting with the test Target

Unit testing and reporting on those tests are important steps that are too often left out of a development cycle. Ant automates everything but writing the tests themselves, so you really should try to utilize it. Putting both the <junit> and <junitreport> tasks in the same target is a good idea so that you don't forget to generate the reports from the raw output of <junit>. Listing 3.12 shows these two tasks in a test target.

Listing 3.12 A Typical test Target

<target name="test" depends="compile">
  <junit failureproperty="testsFailed">
      <pathelement path="${classpath}"/>
      <pathelement path="${build.dir.classes}"/>
    <formatter type="xml"/>
    <test name="chapter3.test.TestAll"

  <junitreport todir="${reports.dir}">
    <fileset dir="${reports.dir}">
      <include name="**/TEST-*.xml"/>
    <report format="frames" todir="${reports.dir.html}"/>

Creating a JAR File with the jar Target

Depending on what you're building, you might need to create a JAR file that contains your compiled classes. a JAR file can be easily created using the built-in <jar> task. Listing 3.13 shows a typical jar target.

Listing 3.13 A Typical jar Target

<target name="jar" depends="test" unless="testsFailed">
  <jar destfile="${build.dir}/${name}.jar"
    basedir="${build.dir}" includes="**/*.class"/>

The <jar> task here builds a JAR file with all .class files it finds under ${build.dir}. Also note that the target will not execute if the testsFailed property is present. This property is set by <junit> if any tests failed. This is a great way to conditionally execute targets.

Building a Web Archive with the war Target

If you're building a Web application, you'll most likely need to create a Web archive, or WAR file, out of it. A WAR file is just a JAR file with some special directories and file placement requirements. The <war> task is an extension of the <jar> task that makes creating WARs a simple matter. Listing 3.14 shows a sample war target.

Listing 3.14 Building a Web Archive with the war Target

<target name="war" depends="jar" unless="testsFailed">
  <war destfile="${name}.war" webxml="${etc.dir}/web.xml">
    <fileset dir="${src.dir}/jsp" includes="**/*.jsp"/>
    <classes dir="${build.dir}/web" includes="**/*.class"/>
    <lib dir="${struts.dir}" includes="*.jar"/>
    <webinf dir="${etc.dir}" includes="*.xml"

Generating Documentation with the docs Target

Because Java provides javaDoc, it is incumbent upon you as a developer to add JavaDoc comments to your code. The javaDoc tool takes these comments and creates excellent API documentation. Unfortunately, the options necessary to really tweak the generated documentation are lengthy and cumbersome. The built-in <javadoc> task makes it a piece of cake to generate JavaDocs exactly as you want them. Just look at Listing 3.15 for an example.

Listing 3.15 Generating JavaDocs

<target name="docs" depends="test" unless="testsFailed">
  <javadoc packagenames="com.mycompany.*" sourcepath="${src.dir}"
    classpath="${classpath}" destdir="${doc.api.dir}"
    author="true" version="true" use="true"
    windowtitle="MyProject Documentation">
    <bottom><![CDATA[<em>Copyright &copy; 2002</em></div>]]></bottom>
    <link href="http://java.sun.com/products/jdk/1.3/docs/api"/>

Notice that the docs target has an unless attribute. If there is a defined property called testsFailed, the documentation will not be generated because you generally don't want API documentation for broken code.

Deploying What You've Built with the deploy Target

After you've built a JAR or WAR file and generated your test reports and your JavaDocs, it's time to drop the JAR or WAR file somewhere for deployment. In the section in Chapter 8 called "Deploying What We've Built," you'll see an example of deploying to another box using FTP. Listing 3.16 is an example of a deploy target that uses the <copy> task to put the JAR file in a QA directory.

Listing 3.16 Deploying the Project

<target name="deploy" depends="jar" unless="testsFailed">
  <copy file="${name}.jar" todir="${qa.dir}"/>


Again, notice that this target depends on a previous target, and won't execute if any unit tests failed.

Turning again to "Ant In Anger," here are some examples for the targets that Mr. Loughran suggests. Notice that each of these targets makes extensive use of the antcall task to delegate work to other targets.

Performing an Incremental Build with the build Target

The build target could call the compile, jar, and/or war targets. Basically, it calls whatever it takes to do a build based on what you currently have on your system. However, it would not fetch source updates from your source control system. Listing 3.17 is an example.

Listing 3.17 Building the Project

<target name="build" depends="prepare">
  <antcall target="compile"/>
  <antcall target="jar"/>

Building and Testing with the main Target

A target called main would perform a build and test, generally, and not much else. It would not fetch source code from a repository, nor would it deploy anything. Listing 3.18 shows this.

Listing 3.18 Building and Testing with the main Target

<target name="main" depends="prepare">
  <antcall target="build"/>
  <antcall target="test"/>

Doing Everything with the all Target

A target named all does just what its name implies: calls all the relevant targets to get the project built. This would be a start-to-finish build, including removing all artifacts from previous builds, fetching source, building, testing, generating documentation, and deploying. You could leverage your existing main target by calling it instead of listing the compile and test steps directly. Listing 3.19 shows one possible implementation of this target.

Listing 3.19 Doing It All with the all Target

<target name="all" depends="prepare">
  <antcall target="clean"/>
  <antcall target="fetch"/>
  <antcall target="main"/>
  <antcall target="deploy"/>

If you use an all target, you should have an unless attribute on each target called by antcall to stop a build if a previous target doesn't complete successfully.

Publishing and Staging with the publish and staging Targets

Mr. Loughran recommends two additional targets: publish and staging. His concept of the staging target is essentially the same as the deploy target we've already discussed, in which our built and tested project is moved to a QA directory or machine. He differentiates the two targets by saying that the staging target is used for this purpose, whereas the deploy target actually moves the project into production. If you have a QA group, I think they will probably be the ones to move the final product into production, so having two different targets doesn't seem all that useful to me.

The publish target would essentially perform a build and test, and then zip the sources, binaries, and support files, and copy/FTP them to your distribution sites. This seems most useful for open source projects, such as Ant, in which you want to distribute binary versions of your product along with the source code.

This concludes our discussion of standard names for targets that you'll see in almost every build file.

  • + Share This
  • 🔖 Save To Your Account