Ant User Manual

by

Version 1.2 - 2000/09/20


Table of Contents


Introduction

Ant is a Java based build tool. In theory it is kind of like make without make's wrinkles.

Why?

Why another build tool when there is already make, gnumake, nmake, jam, and others? Because all of those tools have limitations that its original author couldn't live with when developing software across multiple platforms. Make like tools are inherently shell based. They evaluate a set of dependencies and then execute commands not unlike what you would issue on a shell. This means that you can easily extend these tools by using or writing any program for the OS that you are working on. However, this also means that you limit yourself to the OS, or at least the OS type such as Unix, that you are working on.

Makefiles are inherently evil as well. Anybody who has worked on them for any time has run into the dreaded tab problem. "Is my command not executing because I have a space in front of my tab!!!" said the original author of Ant way too many times. Tools like Jam took care of this to a great degree, but still use yet another format to use and remember.

Ant is different. Instead a model where it is extended with shell based commands, it 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 which implements a particular Task interface.

Granted, this removes some of the expressive power that is inherent by being able to construct a shell command such as `find . -name foo -exec rm {}` but it gives you the ability to be cross platform. To work anywhere and everywhere. And hey, if you really need to execute a shell command, Ant has an exec rule that allows different commands to be executed based on the OS that it is executing on.


Getting Ant

Binary edition

The latest stable version of Ant can be downloaded from http://jakarta.apache.org/builds/ant/release/v1.1/bin/. If you like living on the edge, you can download the latest version from http://jakarta.apache.org/builds/ant/nightly/.

Source edition

If you prefer the source edition, you can download Ant from http://jakarta.apache.org/builds/ant/release/v1.1/src/ (latest stable) or from http://jakarta.apache.org/from-cvs/jakarta-ant/ (current). See the section Building Ant on how to build Ant from the source code.


System Requirements

To build and use ant you must have a JAXP compliant XML parser installed and available on your classpath.

If you do not have a JAXP compliant XML parse installed, you may use the reference implementation available from Sun. It is available from http://java.sun.com/xml. Once installed make sure the "jaxp.jar" and "parser.jar" files are in your classpath.

You will also need the JDK installed on your system, version 1.1 or later.


Building Ant

Go to the directory jakarta-ant.

Make sure the JDK is in you path.

Set the JAVA_HOME environment variable. This should be set to the directory where the JDK is installed. See Installing Ant for examples on how to do this for your operating system.

Run bootstrap.bat (Windows) or bootstrap.sh (UNIX) to build a bootstrap version of Ant.

When finished, use

build.bat -Dant.dist.dir=<directory to install Ant> dist

for Windows, and

build.sh -Dant.dist.dir=<directory to install Ant> dist

for UNIX, to create a binary distribution of Ant. This distribution can be found in the directory you specified.


Installing Ant

The binary distribution of Ant consists of three directories: bin, docs and lib. Only the bin and lib directory are crucial for running Ant. To run Ant, the following must be done:

Windows

Assume Ant is installed in c:\ant\. The following sets up the environment:

set ANT_HOME=c:\ant
set JAVA_HOME=c:\jdk1.2.2
set PATH=%PATH%;%ANT_HOME%\bin

Unix (bash)

Assume Ant is installed in /usr/local/ant. The following sets up the environment:

export ANT_HOME=/usr/local/ant
export JAVA_HOME=/usr/local/jdk-1.2.2
export PATH=${PATH}:${ANT_HOME}/bin

Advanced

There are lots of variants that can be used to run Ant. What you need is at least the following:

The classpath for Ant must contain ant.jar and any jars/classes needed for your chosen JAXP compliant XML parser.

When you need JDK functionality (like a javac task, or a rmic task), then for JDK 1.1, the classes.zip file of the JDK must be added to the classpath; for JDK 1.2 or JDK 1.3, tools.jar must be added. The scripts supplied with ant, in the bin directory, will add tools.jar automatically if the JAVA_HOME environment variable is set.

When you are executing platform specific applications (like the exec task, or the cvs task), the property ant.home must be set to the directory containing a bin directory, which contains the antRun shell script necessary to run execs on Unix.


Running Ant

Running Ant is simple, when you installed it as described in the previous section. Just type ant.

When nothing is specified, Ant looks for a build.xml file in the current directory. When found, it uses that file as a buildfile, otherwise it searches in the parent directory and so on until the root of the filesystem has been reached. To make Ant use another buildfile, use the commandline option -buildfile <file>, where <file> is the buildfile you want to use.

You can also set properties which override properties specified in the buildfile (see the property task). This can be done with the -D<property>=<value> option, where <property> is the name of the property and <value> the value. This can also be used (and is the only way since Java can not access them) to have access to your environment variables, just pass -DMYVAR=%MYVAR% (Windows) or -DMYVAR=$MYVAR (Unix) do Ant, you can access these variables inside your build-file as ${MYVAR}.

Two more options are -quiet which instructs Ant to print less information on the console when running. The option -verbose on the other hand makes Ant print more information on the console.

It is also possible to specify one or more targets that should be executed. When omitted the target that is mentioned in the default attribute of the project is used.

The -projecthelp option gives a list of this projects targets. First those with a description and then those without one.

Commandline option summary:

ant [options] [target [target2 [target3] ...]]
Options:
-help                  print this message
-projecthelp           print project help information
-version               print the version information and exit
-quiet                 be extra quiet
-verbose               be extra verbose
-debug                 print debugging information
-emacs                 produce logging information without adornments
-logfile <file>        use given file for log
-logger <classname>    the class which is to perform logging
-listener <classname>  add an instance of class as a project listener
-buildfile <file>      use given buildfile
-D<property>=<value>   use value for given property

Examples

ant

runs Ant using the build.xml file in the current directory, on the default target.

ant -buildfile test.xml

runs Ant using the test.xml file in the current directory, on the default target.

ant -buildfile test.xml dist

runs Ant using the test.xml file in the current directory, on a target called dist.

ant -buildfile test.xml -Dbuild=build/classes dist

runs Ant using the test.xml file in the current directory, on a target called dist. It also sets the build property to the value build/classes.

Running Ant by hand

When you have installed Ant in the do-it-yourself way, Ant can be started with:

java -Dant.home=c:\ant org.apache.tools.ant.Main [options] [target]

These instructions actually do exactly the same as the ant command. The options and target are the same as when running Ant with the ant command. This example assumes you have set up your classpath to include


Writing a simple buildfile

The buildfile is written in XML. Each buildfile contains one project.

Each element of the buildfile can have an id attribute and can later be referred to by the value supplied to this. The value has to be unique.

Projects

A project has three attributes:

Attribute Description Required
name the name of the project. Yes
default the default target to use when no target is supplied. Yes
basedir the base directory from which all path calculations are done. This attribute might be overridden by setting the "basedir" property on forehand. When this is done, it might be omitted in the project tag. Yes

Each project defines one or more targets. A target is a set of tasks you want to be executed. When starting Ant, you can select which target you want to have executed. When no target is given, the project's default is used.

Targets

A target can depend on other targets. You might have a target for compiling, for instance, and a target for creating a distributable. You can only build a distributable when you have compiled first, so the distribute target depends on the compile target. Ant resolves all these dependencies.

Ant tries to execute the targets in the depends attribute in the order they appear (from left to right). Keep in mind that it is possible that a target can get executed earlier when an earlier target depends on it:

<target name="A"/>
<target name="B" depends="A"/>
<target name="C" depends="B"/>
<target name="D" depends="C,B,A"/>

Suppose we want to execute target D. From its depends attribute, you might think that first target C, then B and then A is executed. Wrong! C depends on B, and B depends on A, so first A is executed, then B, then C, and finally D.

A target gets executed only once. Even when more targets depend on it (see the previous example).

A target has also the ability to perform its execution if (or unless) a property has been set. This allows, for example, better control on the building process depending on the state of the system (java version, OS, command line properties, etc...). To make target sense this property you should add the if (or unless) attribute with the name of the property that the target should react to, for example

<target name="build-module-A" if="module-A-present"/>
<target name="build-own-fake-module-A" unless="module-A-present"/>

If no if and no unless attribute is present, the target will always be executed.

It is a good practice to place your tstamp tasks in a so called initialization target, on which all other targets depend. Make sure that target is always the first one in the depends list of the other targets. In this manual, most initialization targets have the name "init".

The optional description attribute can be used to provide a one line description of this target that is printed by the -projecthelp commandline option.

A target has the following attributes:

Attribute Description Required
name the name of the target. Yes
depends a comma separated list of names of targets on which this target depends. No
if the name of the property that must be set in order for this target to execute. No
unless the name of the property that must not be set in order for this target to execute. No
description a short description of this targets function. No

Tasks

A task is a piece of code that can be executed.

A task can have multiple attributes (or arguments if you prefer). The value of an attribute might contain references to a property. These references will be resolved before the task is executed.

Tasks have a common structure:

<name attribute1="value1" attribute2="value2" ... />

where name is the name of the task, attribute-x the attribute name, and value-x the value of this attribute.

There is a set of built in tasks, but it is also very easy to write your own.

All tasks share a taskname attribute. The value of this attribute will be used in the logging messages generated by Ant.

Properties

A project can have a set of properties. These might be set in the buildfile by the property task, or might be set outside Ant. A property has a name and a value. Properties might be used in in the value of task attributes. This is done by placing the property name between "${" and "}" in the attribute value.

If there is a property called "builddir" with the value "build", then this could be used in an attribute like this: "${builddir}/classes". This is resolved as "build/classes".

Example

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

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

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

  <target name="compile" depends="prepare">
    <!-- Compile the java code from ${src} into ${build} -->
    <javac srcdir="${src}" destdir="${build}" />
  </target>

  <target name="dist" depends="compile">
    <!-- Create the ${dist}/lib 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">
    <!-- Delete the ${build} and ${dist} directory trees -->
    <deltree dir="${build}" />
    <deltree dir="${dist}" />
  </target>
</project>
  

Token Filters

A project can have a set of tokens that might be automatically expanded if found when a file is copied, when the filtering-copy behavior is selected in the tasks that support this. These might be set in the buildfile by the filter task

Since this can be a very harmful behavior, the tokens in the files must be of the form @token@ where token is the token name that is set in the filter task. This token syntax matches the syntax of other build systems that perform such filtering and remains sufficiently orthogonal to most programming and scripting languages, as well with documentation systems.

Note: in case a token with the format @token@ is found in a file but no filter is associated with that token, no changes take place. So, no escaping method is present, but as long as you choose appropriate names for your tokens, this should not cause problems.

PATH like structures

You can specify PATH and CLASSPATH variables using both ":" and ";" as separator characters, Ant will convert it to the correct character of the current operating system.

Wherever PATH like values need to be specified a nested element can be used. This takes the general form of

    <classpath>
      <pathelement path="${classpath}" />
      <pathelement location="lib/helper.jar" />
    </classpath>

The location attribute specifies a single file or directory relative to the project's base directory (or an absolute filename), while the path attribute accepts ":" or ";" separated lists of locations. The path attribute is intended to be used with predefined paths - in any other case multiple elements with location attributes should be preferred.

As a shortcut the surrounding PATH element supports path and location attributes of its own, so

    <classpath>
      <pathelement path="${classpath}" />
    </classpath>

can be abreviated to

    <classpath path="${classpath}" />

In addition, FileSets can be specified via nested <fileset> elements. The order in which the files building up FileSet are added to the PATH like structure is not defined.

    <classpath>
      <pathelement path="${classpath}" />
      <fileset dir="lib">
        <include name="**/*.jar" />
      </fileset;>
      <pathelement location="classes" />
    </classpath>

Builds a PATH which holds the value of ${classpath} followed by all JAR files in the lib directory, followed by the classes directory.

If you want to use the same PATH like structure for several tasks, you can define them with a <path> element at the same level as targets and reference them via their id attribute - see References for an example.

A PATH like structure can include a reference to another PATH like structure via a nested <path> elements.

    <path id="base.path">
      <pathelement path="${classpath}" />
      <fileset dir="lib">
        <include name="**/*.jar" />
      </fileset;>
      <pathelement location="classes" />
    </path>

    <path id="tests.path">
      <path refid="base.path" />
      <pathelement location="testclasses" />
    </path>

Command line arguments

Several tasks take arguments that shall be passed to another process on the command line. To make it easier to specify arguments that contain space characters, nested elements can be used.

Attribute Description Required
value a single command line argument, can contain space characters. Exactly one of these.
line a space delimited list of command line arguments.
file The name of a file as a single command line argument. Will be replaced with the absolute filename of the file by Ant.
path A string that shall be treated as a PATH like string as a single command line argument. You can use ; or : as path separators and Ant will convert it to the platform's local conventions.

Examples

  <arg value="-l -a" />

is a single command line argument containing a space character.

  <arg line="-l -a" />

stands for two separate command line arguments.

  <arg path="/dir;/dir2:\dir3" />

is a single command line argument with value \dir;\dir2;\dir3 on DOS based systems and /dir:/dir2:/dir3 on Unix like systems.

References

The id attribute of the buildfile's elements can be used to refer to them. This can useful if you are going to replicate the same snippet of XML over and over again - using a <classpath> structure more than once for example.

The following example

<project ... >
  <target ... >
    <rmic ...>
      <classpath>
        <pathelement location="lib/" />
        <pathelement path="${java.class.path}/" />
        <pathelement path="${additional.path}" />
      </classpath>
    </rmic>
  </target>

  <target ... >
    <javac ...>
      <classpath>
        <pathelement location="lib/" />
        <pathelement path="${java.class.path}/" />
        <pathelement path="${additional.path}" />
      </classpath>
    </javac>
  </target>
</project>

could be rewritten as

<project ... >
  <path id="project.class.path">
    <pathelement location="lib/" />
    <pathelement path="${java.class.path}/" />
    <pathelement path="${additional.path}" />
  </path>

  <target ... >
    <rmic ...>
      <classpath refid="project.class.path" />
    </rmic>
  </target>

  <target ... >
    <javac ...>
      <classpath refid="project.class.path" />
    </javac>
  </target>
</project>

All tasks that use nested elements for PatternSets, FileSets or PATH like structures accept references to these structures as well.


Directory based tasks

Some tasks use directory trees for the task they perform. For instance, the Javac task which works upon a directory tree with .java files. Sometimes it can be very useful to work on a subset of that directory tree. This section describes how you can select a subset of such a directory tree.

Ant gives you two ways to create a subset, both of which can be used at the same time:

When both inclusion and exclusion are used, only files/directories that match the include patterns, and don't match the exclude patterns are used.

Patterns can be specified inside the buildfile via task attributes or nested elements and via external files. Each line of the external file is taken as pattern that is added to the list of include or exclude patterns.

Patterns

As described earlier, patterns are used for the inclusion and exclusion. These patterns look very much like the patterns used in DOS and UNIX:

'*' matches zero or more characters, '?' matches one character.

Examples:

'*.java' matches '.java', 'x.java' and 'FooBar.java', but not 'FooBar.xml' (does not end with '.java').

'?.java' matches 'x.java', 'A.java', but not '.java' or 'xyz.java' (both don't have one character before '.java').

Combinations of '*'s and '?'s are allowed.

Matching is done per-directory. This means that first the first directory in the pattern is matched against the first directory in the path to match. Then the second directories are matched, and so on. E.g. when we have the pattern '/?abc/*/*.java' and the path '/xabc/foobar/test.java', then first '?abc' is matched with 'xabc', then '*' is matched with 'foobar' and finally '*.java' is matched with 'test.java'. They all match so the path matches the pattern.

Too make things a bit more flexible, we add one extra feature, which makes it possible to match multiple directory levels. This can be used to match a complete directory tree, or a file anywhere in the directory tree. To do this, '**' must be used as the name of a directory. When '**' is used as the name of a directory in the pattern, it matches zero or more directories. For instance: '/test/**' matches all files/directories under '/test/', such as '/test/x.java', or '/test/foo/bar/xyz.html', but not '/xyz.xml'.

There is one "shorthand", if a pattern ends with '/' or '\', then '**' is appended. E.g. "mypackage/test/" is interpreted as were it "mypackage/test/**".

Examples:

**/CVS/* Matches all files in CVS directories, that can be located anywhere in the directory tree.

Matches:

CVS/Repository
org/apache/CVS/Entries
org/apache/jakarta/tools/ant/CVS/Entries

But not:

org/apache/CVS/foo/bar/Entries ('foo/bar/' part does not match)

org/apache/jakarta/** Matches all files in the org/apache/jakarta directory tree.

Matches:

org/apache/jakarta/tools/ant/docs/index.html
org/apache/jakarta/test.xml

But not:

org/apache/xyz.java ('jakarta'/' part is missing)

org/apache/**/CVS/* Matches all files in CVS directories, that are located anywhere in the directory tree under org/apache.

Matches:

org/apache/CVS/Entries
org/apache/jakarta/tools/ant/CVS/Entries

But not:

org/apache/CVS/foo/bar/Entries ('foo/bar/' part does not match)

**/test/** Matches all files which have a directory 'test' in their path, including 'test' as a filename.

When these patterns are used in inclusion and exclusion, you have a powerful way to select just the files you want.

Examples

  <copydir src="${src}"
           dest="${dist}"
           includes="**/images/*"
           excludes="**/*.gif" />

This copies all files in directories called "images", that are located in the directory tree "${src}" to the destination "${dist}", but excludes all "*.gif" files from the copy.

This example can also be expressed using nested elements as

  <copydir src="${src}"
           dest="${dist}">
    <include name="**/images/*"/>
    <exclude name="**/*.gif" />
  </copydir>

Default Excludes

There are a set of definitions which are excluded by default from all directory based tasks. They are:

        "**/*~",
        "**/#*#",
        "**/%*%",
        "**/CVS",
        "**/CVS/*",
        "**/.cvsignore"
If you do not want these default excludes applied, you may disable them with the defaultexcludes="no" attribute.

PatternSets

Patterns can be grouped to sets and later be referenced by their id attribute. They are defined via a patternset element - which can appear nested into a FileSet or a directory based task that constitutes an implicit FileSet. In addition patternsets can be defined at the same level as target - i.e. as children of project

Patterns can be specified by nested <include> or <exclude> elements or the following attributes.

Attribute Description
includes comma separated list of patterns of files that must be included. All files are included when omitted.
includesfile the name of a file. Each line of this file is taken to be an include pattern
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted.
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern

Examples:

<patternset id="non.test.sources" >
  <include name="**/*.java" />
  <exclude name="**/*Test*" />
</patternset>

Builds a set of patterns, that matches all .java files that do not contain the text Test in their name. This set can be referred to via <patternset refid="non.test.sources" /> by tasks that support this feature or by FileSets.

FileSets

FileSets are groups of files. These files can be found in a directory tree starting in a base directory and are matched by patterns taken from a number of PatternSets. FileSets can appear inside task that support this feature or at the same level as target - i.e. as children of project.

PatternSets can be specified as nested <patternset> elements. In addition FileSet holds an implicit PatternSet and supports the nested <include> and <exclude> elements of PatternSet directly as well as PatternSet's attributes.

Attribute Description Required
dir The root of the directory tree of this FileSet. Yes
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No

Examples:

<fileset dir="${server.src}" >
  <patternset id="non.test.sources" >
    <include name="**/*.java" />
    <exclude name="**/*Test*" />
  </patternset>
</fileset>

Groups all files in directory ${server.src} that are Java source files and don't have the text Test in their name.

<fileset dir="${client.src}" >
  <patternset refid="non.test.sources" />
</fileset>

Groups all files in directory ${client.src} using the same patterns as the example before.


Built in tasks


Ant

Description:

Runs Ant on a supplied buildfile. This can be used to build subprojects.

When the antfile attribute is omitted, the file "build.xml" in the supplied directory (dir attribute) is used.

If no target attribute is supplied, the default target of the new project is used.

The properties of the current project will be available in the new project. These properties will override the properties that are set in the new project. (See also the properties task). You can set properties in the new project from the old project by using nested property tags. This allows you to parameterize your subprojects.

Parameters:

Attribute Description Required
antfile the buildfile to use. Defaults to "build.xml". No
dir the directory to use as a basedir for the new Ant project. Defaults to the current directory. No
target the target of the new Ant project that should be executed. No
output Filename to write the ant output to. No

Examples

 <ant antfile="subproject/subbuild.xml" dir="subproject" target="compile" />

 <ant dir="subproject" />

 <ant antfile="subproject/property_based_subbuild.xml">
  <property name="param1" value="version 1.x" />
  <property file="config/subproject/default.properties" />
 </ant>

AntStructure

Description:

Generates a DTD for Ant build files which contains information about all tasks currently known to Ant.

Note that the DTD generated by this task is incomplete, you can always add XML entities using <taskdef>. See here for a way to get around this problem.

This task doesn't know about required attributes, all will be listed as #IMPLIED.

Parameters:

Attribute Description Required
output file to write the DTD to. Yes

Examples

<antstructure output="project.dtd" />

Available

Description

Sets a property if a resource is available at runtime. This resource can be a file resource, a class in classpath or a JVM system resource.

If the resource is present, the property value is set to true by default, otherwise the property is not set. You can set the value to something specific by using the value attribute.

Normally, this task is used to set properties that are useful to avoid target execution depending on system parameters.

Parameters

Attribute Description Required
property the name of the property to set. Yes
value the value to set the property to. Defaults to "true". No
classname the class to look for in classpath. Yes
resource the resource to look for in the JVM
file the file to look for.
classpath the classpath to use when looking up classname. No

Parameters specified as nested elements

classpath

Available's classpath attribute is a PATH like structure and can also be set via a nested classpath element.

Examples

  <available classname="org.whatever.Myclass" property="Myclass.present" />

sets the property Myclass.present to the value "true" if the org.whatever.Myclass is found in Ant's classpath.


Chmod

Description

Changes the permissions of a file or all files inside specified directories. Right now it has effect only under Unix. The permissions are also UNIX style, like the argument for the chmod command.

See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task holds an implicit FileSet and supports all of FileSet's attributes and nested elements directly. More FileSets can be specified using nested <fileset> elements.

Parameters

Attribute Description Required
file the file or single directory of which the permissions must be changed. exactly one of the two or nested <fileset> elements.
dir the directory which holds the files whose permissions must be changed.
perm the new permissions. Yes
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
parallel process all specified files using a single chmod command. Defaults to true. No
type One of file, dir or both. If set to file, only the permissions of plain files are going to be changed. If set to dir, only the directories are considered. No, default is file

Examples

<chmod file="${dist}/start.sh" perm="ugo+rx" />

makes the "start.sh" file readable and executable for anyone on a UNIX system.

    <chmod dir="${dist}/bin" perm="ugo+rx" includes="**/*.sh" />

makes all ".sh" files below ${dist}/bin readable and executable for anyone on a UNIX system.

<chmod perm="g+w" />
  <fileset dir="shared/sources1" >
    <exclude name="**/trial/**" />
  </fileset>
  <fileset refid="other.shared.sources" />
</chmod>

makes all files below shared/sources1 (except those below any directory named trial) writable for members of the same group on a UNIX system. In addition all files belonging to a FileSet with id other.shared.sources get the same permissions.


Copydir

Description

Copies a directory tree from the source to the destination.

It is possible to refine the set of files that are being copied. This can be done with the includes, includesfile, excludes, excludesfile and defaultexcludes attributes. With the includes or includesfile attribute you specify the files you want to have included by using patterns. The exclude or excludesfile attribute is used to specify the files you want to have excluded. This is also done with patterns. And finally with the defaultexcludes attribute, you can specify whether you want to use default exclusions or not. See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes src) as well as the nested <include>, <exclude> and <patternset> elements.

Parameters

Attribute Description Required
src the directory to copy. Yes
dest the directory to copy to. Yes
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
filtering indicates whether token filtering should take place during the copy No
flatten ignore directory structure of source directory, copy all files into a single directory - specified by the dest attribute (default is false). No
forceoverwrite overwrite existing files even if the destination files are newer (default is false). No

Examples

  <copydir src="${src}/resources"
           dest="${dist}"
  />

copies the directory ${src}/resources to ${dist}.

  <copydir src="${src}/resources"
           dest="${dist}"
           includes="**/*.java"
           excludes="**/Test.java"
  />

copies the directory ${src}/resources to ${dist} recursively. All java files are copied, except for files with the name Test.java.

  <copydir src="${src}/resources"
           dest="${dist}"
           includes="**/*.java"
           excludes="mypackage/test/**" />

copies the directory ${src}/resources to ${dist} recursively. All java files are copied, except for the files under the mypackage/test directory.


Copyfile

Description

Copies a file from the source to the destination. The file is only copied if the source file is newer than the destination file, or when the destination file does not exist.

Parameters

Attribute Description Required
src the filename of the file to copy. Yes
dest the filename of the file where to copy to. Yes
filtering indicates whether token filtering should take place during the copy No
forceoverwrite overwrite existing files even if the destination files are newer (default is false). No

Examples

<copyfile src="test.java" dest="subdir/test.java" />

<copyfile src="${src}/index.html" dest="${dist}/help/index.html" />


Cvs

Description

Handles packages/modules retrieved from a CVS repository.

When doing automated builds, the get task should be preferred over the checkout command, because of speed.

Parameters

Attribute Description Required
command the CVS command to execute. No, default "checkout"
cvsRoot the CVSROOT variable. No
dest the directory where the checked out files should be placed. No, default is project's basedir.
package the package/module to check out. No
tag the tag of the package/module to check out. No
date Use the most recent revision no later than the given date No
quiet suppress informational messages. No, default "false"
noexec report only, don't change any files. No, default "false"

Examples

  <cvs cvsRoot=":pserver:anoncvs@jakarta.apache.org:/home/cvspublic"
       package="jakarta-tools"
       dest="${ws.dir}"
  />

checks out the package/module "jakarta-tools" from the CVS repository pointed to by the cvsRoot attribute, and stores the files in "${ws.dir}".

  <cvs dest="${ws.dir}" command="update" />

updates the package/module that has previously been checked out into "${ws.dir}".


Delete

Description

Deletes either a single file or all files in a specified directory and its sub-directories.

It is possible to refine the set of files that are being deleted. This can be done with the includes, includesfile, excludes, excludesfile and defaultexcludes attributes. With the includes or includesfile attribute you specify the files you want to have included in the deletion process by using patterns. The exclude or excludesfile attribute is used to specify the files you want to have excluded from the deletion process. This is also done with patterns. And finally with the defaultexcludes attribute, you can specify whether you want to use default exclusions or not. See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task forms an implicit FileSet and supports all attributes of <fileset> as well as the nested <include>, <exclude> and <patternset> elements.

Parameters

Attribute Description Required
file The file to delete. at least one of the two
dir The directory to delete files from.
includes Comma separated list of patterns of files that must be deleted. All files are in the current directory and any sub-directories are deleted when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes Comma separated list of patterns of files that must be excluded from the deletion list. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes Indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
verbose Show name of each deleted file ("true"/"false"). Default is "false" when omitted. No

Examples

  <delete file="/lib/ant.jar" />

deletes the file /lib/ant.jar.

  <delete dir="lib" />

deletes all files in the /lib directory.

  <delete dir="."
          includes="**/*.bak"
  />

deletes all files with the extension ".bak" from the current directory and any sub-directories.


Deltree

Description

Deletes a directory with all its files and subdirectories.

Parameters

Attribute Description Required
dir the directory to delete. Yes

Examples

  <deltree dir="dist" />

deletes the directory dist, including its files and subdirectories.

  <deltree dir="${dist}" />

deletes the directory ${dist}, including its files and subdirectories.


Echo

Description

Echoes a message to System.out.

Parameters

Attribute Description Required
message the message to echo. Yes, unless data is included in a character section within this element.

Examples

  <echo message="Hello world" />
  
<echo>
This is a longer message stretching over
two lines.
</echo>

Exec

Description

Executes a system command. When the os attribute is specified, then the command is only executed when Ant is run on one of the specified operating systems.

Parameters

Attribute Description Required
command the command to execute with all command line arguments. deprecated, use executable and nested <arg> elements instead. Exactly one of the two.
executable the command to execute without any command line arguments.
dir the directory in which the command should be executed. No
os list of Operating Systems on which the command may be executed. No
output the file to which the output of the command should be redirected. No
timeout Stop the command if it doesn't finish within the specified time (given in milliseconds). No
failonerror Stop the buildprocess if the command exits with a returncode other than 0. No

Examples

<exec dir="${src}" executable="dir" os="windows" output="dir.txt" />

Parameters specified as nested elements

arg

Command line arguments should be specified as nested <arg> elements. See Command line arguments.

env

It is possible to specify environment variables to pass to the system command via nested <env> elements.

Please note that the environment of the current Ant process is not passed to the system command if you specify variables using <env>.

Attribute Description Required
key The name of the environment variable. Yes
value The literal value for the environment variable. Exactly one of these.
path The value for a PATH like environment variable. You can use ; or : as path separators and Ant will convert it to the platform's local conventions.
file The value for the environment variable. Will be replaced by the absolute filename of the file by Ant.
Examples
<exec executable="emacs" >
  <env key="DISPLAY" value=":1.0" />
</exec>

starts emacs on display 1 of the X Window System.

<exec ... >
  <env key="PATH" path="${java.library.path}:${basedir}/bin" />
</exec>

adds ${basedir}/bin to the PATH of the system command.

Note: Although it may work for you to specify arguments using a simple arg-element and seperate them by spaces it may fail if you switch to a newer version of the JDK. JDK < 1.2 will pass these as separate arguments to the program you are calling, JDK >= 1.2 will pass them as a single argument and cause most calls to fail.

Note2: If you are using Ant on Windows and a new DOS-Window pops up for every command which is excuted this may be a problem of the JDK you are using. This problem may occur with all JDK's < 1.2.


ExecOn

Description

Executes a system command. When the os attribute is specified, then the command is only executed when Ant is run on one of the specified operating systems.

The files and/or directories of a number of FileSets are passed as arguments to the system command. At least one nested <fileset> is required.

Parameters

Attribute Description Required
executable the command to execute without any command line arguments. Yes
dir the directory in which the command should be executed. No
os list of Operating Systems on which the command may be executed. No
output the file to which the output of the command should be redirected. No
timeout Stop the command if it doesn't finish within the specified time (given in milliseconds). No
failonerror Stop the buildprocess if the command exits with a returncode other than 0. No
parallel Run the command only once, appending all files as arguments. Defaults to true. If false, command will be executed once for every file. No
type One of file, dir or both. If set to file, only the names of plain files will be sent to the command. If set to dir, only the names of directories are considered. No, default is file

Parameters specified as nested elements

fileset

You can use any number of nested <fileset> elements to define the files for this task and refer to <fileset>s defined elsewhere.

arg

Command line arguments should be specified as nested <arg> elements. See Command line arguments.

env

It is possible to specify environment variables to pass to the system command via nested <env> elements. See the description in the section about exec

Please note that the environment of the current Ant process is not passed to the system command if you specify variables using <env>.

Examples

<execon executable="ls" >
  <arg value="-l" />
  <fileset dir="/tmp">
    <patternset>
      <exclude name="**/*.txt" />
    </patternset>
  </fileset>
  <fileset refid="other.files" />
</execon>

invokes ls -l, adding the absolute filenames of all files below /tmp not ending in .txt and all files of the FileSet with id other.files to the command line.


Fail

Description

Exits the current build (just throwing a BuildException), optionally printing additional information.

Parameters

Attribute Description Required
message A message giving further information on why the build exited No

Examples

  <fail/>

will exit the current build with no further information given.

BUILD FAILED

build.xml:4: No message

  <fail message="Something wrong here."/>

will exit the current build and print something like the following to whereever your output goes:

BUILD FAILED

build.xml:4: Something wrong here.


Filter

Description

Sets a token filter for this project or read multiple token filter from an input file and sets these as filters. Token filters are used by all tasks that perform file copying operations through the Project commodity methods.

Note 1: the token string must not contain the separators chars (@).
Note 2: Either token and value must be given as parameter, or only the filterfile must be given as parameter.

Parameters

Attribute Description Required
token the token string without @ Yes*
value the string that should be put to replace the token when the file is copied Yes*
filterfile The file from which the filters must be read. This file must be a formatted as a property file. Yes*

* see notes 1 and 2 above parameters table.

Examples

  <filter token="year" value="2000" />
  <copydir src="${src.dir}" dest="${dest.dir}"/>

will copy recursively all the files from the src.dir directory into the dest.dir directory replacing all the occurencies of the string @year@ with 2000.

  <filter filterfile="deploy_env.properties" />
will read all property entries from the deploy_env.properties file and set these as filters.

FixCRLF

Description

Adjusts a text file to local.

It is possible to refine the set of files that are being adjusted. This can be done with the includes, includesfile, excludes, excludesfile and defaultexcludes attributes. With the includes or includesfile attribute you specify the files you want to have included by using patterns. The exclude or excludesfile attribute is used to specify the files you want to have excluded. This is also done with patterns. And finally with the defaultexcludes attribute, you can specify whether you want to use default exclusions or not. See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes srcdir) as well as the nested <include>, <exclude> and <patternset> elements.

Parameters

Attribute Description Required
srcDir Where to find the files to be fixed up. Yes
destDir Where to place the corrected files. Defaults to srcDir (replacing the original file) No
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
cr Specifies how carriage return (CR) characters are to be handled. Valid values for this property are:
  • add: ensure that there is a CR before every LF
  • asis: leave CR characters alone
  • remove: remove all CR characters
Default is based on the platform on which you are running this task. For Unix platforms, the default is remove. For DOS based systems (including Windows), the default is add.

Note: Unless this property is specified as "asis", extra CR characters which do not precede a LF will be removed.

No
tab Specifies how tab characters are to be handled. Valid values for this property are:
  • add: convert sequences of spaces which span a tab stop to tabs
  • asis: leave tab and space characters alone
  • remove: convert tabs to spaces
Default for this parameter is "asis".

Note: Unless this property is specified as "asis", extra spaces and tabs after the last non-whitespace character on the line will be removed.

No
tablength The number of characters a TAB stop corresponds to. Must be a positive power of 2, default for this parameter is 8. No
eof Specifies how DOS end of file (control-Z) characters are to be handled. Valid values for this property are:
  • add: ensure that there is an EOF character at the end of the file
  • asis: leave EOF characters alone
  • remove: remove any EOF character found at the end
Default is based on the platform on which you are running this task. For Unix platforms, the default is remove. For DOS based systems (including Windows), the default is asis.
No

Examples

  <fixcrlf srcdir="${src}"
       cr="remove" eof="remove"
       includes="**/*.sh"
  />

Removes carriage return and eof characters from the shell scripts. Tabs and spaces are left as is.

  <fixcrlf srcdir="${src}"
       cr="add"
       includes="**/*.bat"
  />

Ensures that there are carriage return characters prior to evey line feed. Tabs and spaces are left as is. EOF characters are left alone if run on DOS systems, and are removed if run on Unix systems.

  <fixcrlf srcdir="${src}"
       tabs="add"
       includes="**/Makefile"
  />

Adds or removes CR characters to match local OS conventions, and converts spaces to tabs when appropriate. EOF characters are left alone if run on DOS systems, and are removed if run on Unix systems. Many versions of make require tabs prior to commands.

  <fixcrlf srcdir="${src}"
       tabs="remove"
       includes="**/README*"
  />

Adds or removes CR characters to match local OS conventions, and converts all tabs to spaces. EOF characters are left alone if run on DOS systems, and are removed if run on Unix systems. You never know what editor a user will use to browse README's.


GenKey

Description

Generates a key in keystore.

Parameters

Attribute Description Required
alias the alias to add under Yes.
storepass password for keystore integrity. Yes.
keystore keystore location No
storetype keystore type No
keypass password for private key (if different) No
sigalg the algorithm to use in signing No
keyalg the method to use when generating name-value pair No
verbose (true | false) verbose output when signing No
dname The distinguished name for entity Yes if dname element unspecified
validity (integer) indicates how many days certificate is valid No
keysize (integer) indicates the size of key generated No

Alternatively you can specify the distinguished name by creating a sub-element named dname and populating it with param elements that have a name and a value. When using the subelement it is automatically encoded properly and , are replace

The following two examples are identical:

Examples

<genkey alias="apache-group" storepass="secret" dname="CN=Ant Group, OU=Jakarta Division, O=Apache.org, C=US" />

<genkey alias="apache-group" storepass="secret" >
  <dname>
    <param name="CN" value="Ant Group"/>
    <param name="OU" value="Jakarta Division"/>
    <param name="O"  value="Apache.Org"/>
    <param name="C"  value="US"/>
  </dname>
</genkey>

Get

Description

Gets a file from a URL. When the verbose option is "on", this task displays a '.' for every 100 Kb retrieved.

This task should be preferred above the CVS task when doing automated builds. CVS is significantly slower than loading a compressed archive with http/ftp.

The usetimestamps option enables you to control downloads so that the remote file is only fetched if newer than the local copy. If there is no local copy, the download always takes place. When a file is downloaded, the timestamp of the downloaded file is set to the remote timestamp, if the JVM is Java1.2 or later. NB: This timestamp facility only works on downloads using the HTTP protocol.

Parameters

Attribute Description Required
src the URL from which to retrieve a file. Yes
dest the file where to store the retrieved file. Yes
verbose show verbose progress information ("on"/"off"). No
ignoreerrors Log errors but don't treat as fatal. No
usetimestamps conditionally download a file based on the timestamp of the local copy. HTTP only No

Examples

  <get src="http://jakarta.apache.org/" dest="help/index.html" />

Gets the index page of http://jakarta.apache.org/, and stores it in the file help/index.html.

  <get src="http://jakarta.apache.org/builds/tomcat/nightly/ant.zip" 
	dest="optional.jar" 
	verbose="true"
	usetimestamps="true"/>

Gets the nightly ant build from the tomcat distribution, if the local copy is missing or out of date. Uses the verbose option for progress information.


GUnzip

Description

Expands a GZip file.

If dest is a directory the name of the destination file is the same as src (with the ".gz" extension removed if present). If dest is omitted, the parent dir of src is taken. The file is only expanded if the source file is newer than the destination file, or when the destination file does not exist.

Parameters

Attribute Description Required
src the file to expand. Yes
dest the destination file or directory. No

Examples

<gunzip src="test.tar.gz"/>

expands test.tar.gz to test.tar

<gunzip src="test.tar.gz" dest="test2.tar"/>

expands test.tar.gz to test2.tar

<gunzip src="test.tar.gz" dest="subdir"/>

expands test.tar.gz to subdir/test.tar (assuming subdir is a directory).


GZip

Description

GZips a file.

Parameters

Attribute Description Required
src the file to gzip. Yes
zipfile the destination file. Yes

Examples

<gzip src="test.tar" zipfile="test.tar.gz" />


Jar

Description

Jars a set of files.

The basedir attribute is the reference directory from where to jar.

Note that file permissions will not be stored in the resulting jarfile.

It is possible to refine the set of files that are being jarred. This can be done with the includes, includesfile, excludes, excludesfile and defaultexcludes attributes. With the includes or includesfile attribute you specify the files you want to have included by using patterns. The exclude or excludesfile attribute is used to specify the files you want to have excluded. This is also done with patterns. And finally with the defaultexcludes attribute, you can specify whether you want to use default exclusions or not. See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes basedir) as well as the nested <include>, <exclude> and <patternset> elements.

You can also use nested file sets for more flexibility, and specify multiple ones to merge together different trees of files into one JAR. See the Zip task for more details and examples.

If the manifest is omitted, a simple one will be supplied by Ant. You should not include META-INF/MANIFEST.MF in your set of files.

The whenempty parameter controls what happens when no files match. If create (the default), the JAR is created anyway with only a manifest. If skip, the JAR is not created and a warning is issued. If fail, the JAR is not created and the build is halted with an error.

Parameters

Attribute Description Required
jarfile the jar-file to create. Yes
basedir the directory from which to jar the files. No
compress Not only store data but also compress them, defaults to true No
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
manifest the manifest file to use. No
whenempty Behavior to use if no files match. No

Examples

  <jar jarfile="${dist}/lib/app.jar" basedir="${build}/classes" />

jars all files in the ${build}/classes directory in a file called app.jar in the ${dist}/lib directory.

  <jar jarfile="${dist}/lib/app.jar"
       basedir="${build}/classes"
       excludes="**/Test.class"
  />

jars all files in the ${build}/classes directory in a file called app.jar in the ${dist}/lib directory. Files with the name Test.class are excluded.

  <jar jarfile="${dist}/lib/app.jar"
       basedir="${build}/classes"
       includes="mypackage/test/**"
       excludes="**/Test.class"
  />

jars all files in the ${build}/classes directory in a file called app.jar in the ${dist}/lib directory. Only files under the directory mypackage/test are used, and files with the name Test.class are excluded.

  <jar jarfile="${dist}/lib/app.jar">
    <fileset dir="${build}/classes"
             excludes="**/Test.class"
    />
    <fileset dir="${src}/resources"/>
  </jar>

jars all files in the ${build}/classes directory and also in the ${src}/resources directory together in a file called app.jar in the ${dist}/lib directory. Files with the name Test.class are excluded. If there are files such as ${build}/classes/mypackage/MyClass.class and ${src}/resources/mypackage/image.gif, they will appear in the same directory in the JAR (and thus be considered in the same package by Java).


Java

Description

Executes a Java class within the running (Ant) VM or forks another VM if specified.

Be careful that the executed class doesn't call System.exit(), because it will terminate the VM and thus Ant. In case this happens, it's highly suggested that you set the fork attribute so that System.exit() stops the other VM and not the one that is currently running Ant.

Parameters

Attribute Description Required
classname the Java class to execute. Yes
args the arguments for the class that is executed. deprecated, use nested <arg> elements instead. No
classpath the classpath to use. No
classpathref the classpath to use, given as reference to a PATH defined elsewhere. No
fork if enabled triggers the class execution in another VM (disabled by default) No
jvm the command used to invoke the Java Virtual Machine, default is 'java'. The command is resolved by java.lang.Runtime.exec(). Ignored if fork is disabled. No
jvmargs the arguments to pass to the forked VM (ignored if fork is disabled). deprecated, use nested <jvmarg> elements instead. No
maxmemory Max amount of memory to allocate to the forked VM (ignored if fork is disabled) No
failonerror Stop the buildprocess if the command exits with a returncode other than 0. Only available if fork is true. No
dir The directory to invoke the VM in. (ignored if fork is disabled) No

Parameters specified as nested elements

arg and jvmarg

Use nested <arg> and <jvmarg> elements to specify arguments for the or the forked VM. See Command line arguments.

classpath

Java's classpath attribute is a PATH like structure and can also be set via a nested classpath element.

Example
  
       <java classname="test.Main" >
         <arg value="-h" /> 
         <classpath>
           <pathelement location="\test.jar" />
           <pathelement path="${java.class.path}" />
         </classpath>
       </java>

Examples

  <java classname="test.Main" />
  <java classname="test.Main"
        fork="yes" >
    <arg value="-h" /> 
    <jvmarg value="-Xrunhprof:cpu=samples,file=log.txt,depth=3" /> 
  </java>

Javac

Description

Compiles a source tree within the running (Ant) VM.

The source and destination directory will be recursively scanned for Java source files to compile. Only Java files that have no corresponding class file or where the class file is older than the java file will be compiled.

The directory structure of the source tree should follow the package hierarchy.

It is possible to refine the set of files that are being compiled/copied. This can be done with the includes, includesfile, excludes, excludesfile and defaultexcludes attributes. With the includes or includesfile attribute you specify the files you want to have included by using patterns. The exclude or excludesfile attribute is used to specify the files you want to have excluded. This is also done with patterns. And finally with the defaultexcludes attribute, you can specify whether you want to use default exclusions or not. See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

It is possible to use different compilers. This can be selected with the "build.compiler" property. There are three choices:

For JDK 1.1/1.2 is classic the default. For JDK 1.3 is modern the default.

Parameters

Attribute Description Required
srcdir location of the java files. Yes, unless nested <src> elements are present.
destdir location where to store the class files. Yes
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
classpath the classpath to use. No
bootclasspath location of bootstrap class files. No
classpathref the classpath to use, given as reference to a PATH defined elsewhere. No
bootclasspathref location of bootstrap class files, given as by reference to a PATH defined elsewhere. No
extdirs location of installed extensions. No
encoding encoding of source files. No
debug indicates whether there should be compiled with debug information ("on"). No
optimize indicates whether there should be compiled with optimization ("on"). No
deprecation indicates whether there should be compiled with deprecation information ("on"). No
target Generate class files for specific VM version, e.g. "1.1" or "1.2". No
verbose asks the compiler for verbose output. No
depend enables dependency tracking for compilers that support this (jikes and modern) No

Parameters specified as nested elements

This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes srcdir) as well as the nested <include>, <exclude> and <patternset> elements.

src, classpath, bootclasspath and extdirs

Javac's srcdir, classpath, bootclasspath and extdirs attributes are PATH like structure and can also be set via nested src, classpath, bootclasspath and extdirs elements respectively.

Examples

  <javac srcdir="${src}"
         destdir="${build}"
         classpath="xyz.jar"
         debug="on"
  />

compiles all .java files under the directory ${src}, and stores the .class files in the directory ${build}. The classpath used contains xyz.jar, and debug information is on.

  <javac srcdir="${src}"
         destdir="${build}"
         includes="mypackage/p1/**,mypackage/p2/**"
         excludes="mypackage/p1/testpackage/**"
         classpath="xyz.jar"
         debug="on"
  />

compiles .java files under the directory ${src}, and stores the .class files in the directory ${build}. The classpath used contains xyz.jar, and debug information is on. Only files under mypackage/p1 and mypackage/p2 are used. Files in the mypackage/p1/testpackage directory are excluded form compilation and copy.

  <javac srcdir="${src}:${src2}"
         destdir="${build}"
         includes="mypackage/p1/**,mypackage/p2/**"
         excludes="mypackage/p1/testpackage/**"
         classpath="xyz.jar"
         debug="on"
  />

is the same as the previous example with the addition of a second source path, defined by the propery src2. This can also be represented using nested elements as follows

  <javac destdir="${build}"
         classpath="xyz.jar"
         debug="on">
    <src path="${src}" />
    <src path="${src2}" />
    <include name="mypackage/p1/**,mypackage/p2/**" />
    <exclude name="mypackage/p1/testpackage/**" />
  </javac>

Note: If you are using Ant on Windows and a new DOS-Window pops up for every use of an external compiler this may be a problem of the JDK you are using. This problem may occur with all JDK's < 1.2.


Javadoc/Javadoc2

Description

Generates code documentation using the javadoc tool.

The source directory will be recursively scanned for Java source files to process but only those matching the inclusion rules will be passed to the javadoc tool. This allows wildcards to be used to choose between package names, reducing verbosity and management costs over time. This task, however, has no notion of "changed" files, unlike the javac task. This means all packages will be processed each time this task is run. In general, however, this task is used much less frequently.

This task works seamlessly between different javadoc versions (1.1 and 1.2), with the obvious restriction that the 1.2 attributes will be ignored if run in a 1.1 VM.

NOTE: since javadoc calls System.exit(), javadoc cannot be run inside the same VM as ant without breaking functionality. For this reason, this task always forks the VM. This overhead is not significant since javadoc is normally a heavy application and will be called infrequently.

NOTE: the packagelist attribute allows you to specify the list of packages to document outside of the Ant file. It's a much better practice to include everything inside the build.xml file. This option was added in order to make it easier to migrate from regular makefiles, where you would use this option of javadoc. The packages listed in packagelist are not checked, so the task performs even if some packages are missing or broken. Use this option if you wish to convert from an existing makefile. Once things are running you should then switch to the regular notation.

DEPRECATION: the javadoc2 task simply points to the javadoc task and it's there for back compatibility reasons. Since this task will be removed in future versions, you are strongly encouraged to use javadoc instead.

Parameters

Attribute Description Availability Required
sourcepath Specify where to find source files all At least one of the two or nested <sourcepath>
sourcepathref Specify where to find source files by reference to a PATH defined elsewhere. all
destdir Destination directory for output files all Yes
maxmemory Max amount of memory to allocate to the javadoc VM all No
sourcefiles Space separated list of source files all at least one of the two
packagenames Comma separated list of package files (with terminating wildcard) all
packageList The name of a file containing the packages to process all No
classpath Specify where to find user class files all No
Bootclasspath Override location of class files loaded by the bootstrap class loader 1.2 No
classpathref Specify where to find user class files by reference to a PATH defined elsewhere. all No
bootclasspathref Override location of class files loaded by the bootstrap class loader by reference to a PATH defined elsewhere. 1.2 No
Extdirs Override location of installed extensions 1.2 No
Overview Read overview documentation from HTML file 1.2 No
Public Show only public classes and members all No
Protected Show protected/public classes and members (default) all No
Package Show package/protected/public classes and members all No
Private Show all classes and members all No
Old Generate output using JDK 1.1 emulating doclet 1.2 No
Verbose Output messages about what Javadoc is doing 1.2 No
Locale Locale to be used, e.g. en_US or en_US_WIN 1.2 No
Encoding Source file encoding name all No
Version Include @version paragraphs all No
Use Create class and package usage pages 1.2 No
Author Include @author paragraphs all No
Splitindex Split index into one file per letter 1.2 No
Windowtitle Browser window title for the documentation (text) 1.2 No
Doctitle Include title for the package index(first) page (html-code) 1.2 No
Header Include header text for each page (html-code) 1.2 No
Footer Include footer text for each page (html-code) 1.2 No
bottom Include bottom text for each page (html-code) 1.2 No
link Create links to javadoc output at the given URL 1.2 No
linkoffline Link to docs at <url> using package list at <url2> 1.2 No
group Group specified packages together in overview page 1.2 No
nodeprecated Do not include @deprecated information all No
nodeprecatedlist Do not generate deprecated list 1.2 No
notree Do not generate class hierarchy all No
noindex Do not generate index all No
nohelp Do not generate help link 1.2 No
nonavbar Do not generate navigation bar 1.2 No
serialwarn FUTURE: Generate warning about @serial tag 1.2 No
helpfile FUTURE: Specifies the HTML help file to use 1.2 No
stylesheetfile Specifies the CSS stylesheet to use 1.2 No
charset FUTURE: Charset for cross-platform viewing of generated documentation 1.2 No
docencoding Output file encoding name 1.1 No
doclet Specifies the class file that starts the doclet used in generating the documentation. 1.2 No
docletpath Specifies the path to the doclet class file that is specified with the -doclet option. 1.2 No
docletpathref Specifies the path to the doclet class file that is specified with the -doclet option by reference to a PATH defined elsewhere. 1.2 No
additionalparam Lets you add additional parameters to the javadoc command line. Useful for doclets 1.2 No
failonerror Stop the buildprocess if the command exits with a returncode other than 0. all No

Parameters specified as nested elements

link

Create link to javadoc output at the given URL. This performs the same role as the link and linkoffline attributes. You can use either syntax (or both at once), but with the nested elements you can easily specify multiple occurrences of the arguments.

Parameters

Attribute Description Required
href The URL for the external documentation you wish to link to Yes
offline True if this link is not available online at the time of generating the documentation No
packagelistLoc The location to the directory containing the package-list file for the external documentation Only if the offline attribute is true

groups

Separates packages on the overview page into whatever groups you specify, one group per table. This performs the same role as the group attribute. You can use either syntax (or both at once), but with the nested elements you can easily specify multiple occurrences of the arguments.

Attribute Description Required
title Title of the group Yes
packages List of packages to include in that group Yes

sourcepath, classpath and bootclasspath

Javadoc's sourcepath, classpath and bootclasspath attributes are PATH like structure and can also be set via nested sourcepath, classpath and bootclasspath elements respectively.

Example

  <javadoc packagenames="com.dummy.test.*"
           sourcepath="src"
           destdir="docs/api"
           author="true"
           version="true"
           use="true"
           windowtitle="Test API"
           doctitle="<h1>Test</h1>"
           bottom="<i>Copyright &#169; 2000 Dummy Corp. All Rights Reserved.</i>">
    <group title="Group 1 Packages" packages="com.dummy.test.a*"/>
    <group title="Group 2 Packages" packages="com.dummy.test.b*"/>
    <link offline="true" href="http://java.sun.com/products/jdk/1.2/docs/api/" packagelistLoc="C:\tmp"/>
    <link href="http://developer.java.sun.com/developer/products/xml/docs/api/"/>
  </javadoc>

Mkdir

Description

Creates a directory. Also non-existent parent directories are created, when necessary.

Parameters

Attribute Description Required
dir the directory to create. Yes

Examples

<mkdir dir="${dist}" />

creates a directory ${dist}.

<mkdir dir="${dist}/lib" />

creates a directory ${dist}/lib.


Patch

Description

Applies a diff file to originals.

Parameters

Attribute Description Required
patchfile the file that includes the diff output Yes
originalfile the file to patch No, tries to guess it from the diff file
backups Keep backups of the unpatched files No
quiet Work silently unless an error occurs No
reverse Assume patch was created with old and new files swapped. No
ignorewhitespace Ignore whitespace differences. No
strip Strip the smallest prefix containing num leading slashes from filenames. No

Examples

  <patch patchfile="module.1.0-1.1.patch" />

applies the diff included in module.1.0-1.1.patch to the files in base directory guessing the filename(s) from the diff output.

  <patch patchfile="module.1.0-1.1.patch" strip="1" />

like above but one leading directory part will be removed. i.e. if the diff output looked like

--- a/mod1.0/A	Mon Jun  5 17:28:41 2000
+++ a/mod1.1/A	Mon Jun  5 17:28:49 2000
the leading a/ will be stripped.

Property

Description

Sets a property (by name and value), or set of properties (from file or resource) in the project.

When a property was set by the user, or was a property in a parent project (that started this project with the ant task), then this property cannot be set, and will be ignored. This means that properties set outside the current project always override the properties of the current project.

There are three ways to set properties:

Although combinations of the three ways are possible, only one should be used at a time. Problems might occur with the order in which properties are set, for instance.

The value part of the properties being set, might contain references to other properties. These references are resolved at the time these properties are set. This also holds for properties loaded from a property file.

Parameters

Attribute Description Required
name the name of the property to set. Yes
value the value of the property. Yes
resource the resource name of the property file.
file the filename of the property file .

Examples

  <property name="foo.dist" value="dist" />

sets the property foo.dist to the value "dist".

  <property file="foo.properties" />

reads a set of properties from a file called "foo.properties".

  <property resource="foo.properties" />

reads a set of properties from a resource called "foo.properties".

Note that you can reference a global properties file for all of your Ant builds using the following:

  <property file="${user.home}/.ant-global.properties" />

since the "user.home" property is defined by the Java virtual machine to be your home directory. This technique is more appropriate for Unix than Windows since the notion of a home directory doesn't exist on Windows. On the JVM that I tested, the home directory on Windows is "C:\". Different JVM implementations may use other values for the home directory on Windows.


Rename

Description

Renames a given file.

Parameters

Attribute Description Required
src file to rename. Yes
dest new name of the file. Yes
replace Enable replacing of existing file (default: on). No

Examples

  <rename src="foo.jar" dest="${name}-${version}.jar" />

Renames the file foo.jar to ${name}-${version}.jar (assuming name and version being predefined properties). If a file named ${name}-${version}.jar already exists, it will be removed prior to renaming foo.jar.


Replace

Description

Replace is a directory based task for replacing the occurrence of a given string with another string in selected file.

If you want to replace a text that crosses line boundaries, you must use a nested <replacetoken> element.

Parameters

Attribute Description Required
file file for which the token should be replaced. Exactly one of the two.
dir The base directory to use when replacing a token in multiple files.
token the token which must be replaced. Yes, unless a nested replacetoken element is used.
value the new value for the token. When omitted, an empty string ("") is used. No
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No

Examples

  <replace file="${src}/index.html" token="@@@" value="wombat" />

replaces occurrences of the string "@@@" with the string "wombat", in the file ${src}/index.html.

Parameters specified as nested elements

This task forms an implicit FileSet and supports all attributes of <fileset> as well as the nested <include>, <exclude> and <patternset> elements.

If either the text you want to replace or the replacement text cross line boundaries, you can use nested elements to specify them.

Examples

  
<replace dir="${src}" value="wombat">
  <include name="**/*.html" />
  <replacetoken><[CDATA[multi line
token]]></replacetoken>
</replace>

replaces occurrences of the string "multi line\ntoken" with the string "wombat", in all HTML files in the directory ${src}.Where \n is the platform specific line separator.

  
<replace file="${src}/index.html">
  <replacetoken><[CDATA[two line
token]]></replacetoken>
  <replacevalue><[CDATA[two line
token]]></replacevalue>
</replace>

Rmic

Description

Runs the rmic compiler for a certain class.

Rmic can be run on a single class (as specified with the classname attribute) or a number of classes at once (all classes below base that are neither _Stub nor _Skel classes).

It is possible to refine the set of files that are being rmiced. This can be done with the includes, includesfile, excludes, excludesfile and defaultexcludes attributes. With the includes or includesfile attribute you specify the files you want to have included by using patterns. The exclude or excludesfile attribute is used to specify the files you want to have excluded. This is also done with patterns. And finally with the defaultexcludes attribute, you can specify whether you want to use default exclusions or not. See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes base) as well as the nested <include>, <exclude> and <patternset> elements.

Parameters

Attribute Description Required
base the location to store the compiled files. Yes
classname the class for which to run rmic. No
filtering indicates whether token filtering should take place No
sourcebase Pass the "-keepgenerated" flag to rmic and move the generated source file to the base directory. No
stubversion Specify the JDK version for the generated stub code. Specify "1.1" to pass the "-v1.1" option to rmic. No
classpath The classpath to use during compilation No
classpathref The classpath to use during compilation, given as reference to a PATH defined elsewhere No
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
verify check that classes implement Remote before handing them to rmic (default is false) No

Parameters specified as nested elements

classpath

Rmic's classpath attribute is a PATH like structure and can also be set via a nested classpath elements.

Examples

  <rmic classname="com.xyz.FooBar" base="${build}/classes" />

runs the rmic compiler for the class com.xyz.FooBar. The compiled files will be stored in the directory ${build}/classes.

  <rmic base="${build}/classes" includes="**/Remote*.class" />

runs the rmic compiler for all classes with .class files below ${build}/classes whose classname starts with Remote. The compiled files will be stored in the directory ${build}/classes.


SignJar

Description

Signs a jar or zip file with the javasign command line tool.

Parameters

Attribute Description Required
jar the jar file to sign Yes.
alias the alias to sign under Yes.
storepass password for keystore integrity. Yes.
keystore keystore location No
storetype keystore type No
keypass password for private key (if different) No
sigfile name of .SF/.DSA file No
signedjar name of signed JAR file No
verbose (true | false) verbose output when signing No
internalsf (true | false) include the .SF file inside the signature block No
sectionsonly (true | false) don't compute hash of entire manifest No

Examples

<signjar jar="${dist}/lib/ant.jar" alias="apache-group" storepass="secret" />

signs the ant.jar with alias "apache-group" accessing the keystore and private key via "secret" password.


Style

Description

Process a set of documents via XSLT.

This is useful for building views of XML based documentation, or in generating code.

It is possible to refine the set of files that are being copied. This can be done with the includes, includesfile, excludes, excludesfile and defaultexcludes attributes. With the includes or includesfile attribute you specify the files you want to have included by using patterns. The exclude or excludesfile attribute is used to specify the files you want to have excluded. This is also done with patterns. And finally with the defaultexcludes attribute, you can specify whether you want to use default exclusions or not. See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes basedir) as well as the nested <include>, <exclude> and <patternset> elements.

Parameters

Attribute Description Required
basedir where to find the source xml file. Yes
destdir directory where to store the results. Yes
extension desired file extension to be used for the targets. If not specified, the default is "html". No
style name of the stylesheet to use. Yes
processor name of the XSLT processor to use. Permissible values are "xslp" for the XSL:P processor, "xalan" for the Apache XML Xalan processor, or the name of an arbitrary XSLTLiaison class. Defaults to xslp or xalan (in that order), if one is found in your class path No
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No

Examples

<style basedir="doc" destdir="build/doc"
       extension="html" style="style/apache.xml"/>


Tar

Description

Creates a tar archive.

The basedir attribute is the reference directory from where to tar.

It is possible to refine the set of files that are being tarred. This can be done with the includes, includesfile, excludes, excludesfile and defaultexcludes attributes. With the includes or includesfile attribute you specify the files you want to have included by using patterns. The exclude or excludesfile attribute is used to specify the files you want to have excluded. This is also done with patterns. And finally with the defaultexcludes attribute, you can specify whether you want to use default exclusions or not. See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes basedir) as well as the nested <include>, <exclude> and <patternset> elements.

Note that this task does not perform compression. You might want to use the GZip task to come up with a .tar.gz package.

Parameters

Attribute Description Required
tarfile the tar-file to create. Yes
basedir the directory from which to zip the files. Yes
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No

Examples

  <tar tarfile="${dist}/manual.tar" basedir="htdocs/manual" />
  <gzip zipfile="${dist}/manual.tar.gz" src="${dist}/manual.tar" />

tars all files in the htdocs/manual directory in a file called manual.tar in the ${dist} directory, then applies the gzip task to compress it.

  <tar tarfile="${dist}/manual.tar"
       basedir="htdocs/manual"
       excludes="mydocs/**, **/todo.html"
  />

tars all files in the htdocs/manual directory in a file called manual.tar in the ${dist} directory. Files in the directory mydocs, or files with the name todo.html are excluded.


Taskdef

Description

Adds a task definition to the current project, such that this new task can be used in the current project. Two attributes are needed, the name that identifies this task uniquely, and the full name of the class (including the packages) that implements this task.

Taskdef should be used to add your own tasks to the system. See also "Writing your own task".

Parameters

Attribute Description Required
name the name of the task Yes
classname the full class name implementing the task Yes
classpath the classpath to use when looking up classname. No

Parameters specified as nested elements

classpath

Taskdef's classpath attribute is a PATH like structure and can also be set via a nested classpath element.

Examples

  <taskdef name="myjavadoc" classname="com.mydomain.JavadocTask" />

makes a task called myjavadoc available to Ant. The class com.mydomain.JavadocTask implements the task.


Touch

Description

Changes the modification time of a file and possibly creates it at the same time.

For JDK 1.1 only the creation of new files with a modification time of now works, all other cases will emit a warning.

Parameters

Attribute Description Required
file the name of the file Yes
millis specifies the new modification time of the file in milliseconds since midnight Jan 1 1970 No
datetime specifies the new modification time of the file in the format MM/DD/YYYY HH:MM AM_or_PM. No

If both millis and datetime are omitted the current time is assumed.

Examples

  <touch file="myfile" />

creates myfile if it doesn't exist and changes the modification time to the current time.

  <touch file="myfile" datetime="06/28/2000 2:02 pm" />

creates myfile if it doesn't exist and changes the modification time to Jun, 28 2000 2:02 pm (14:02 for those used to 24 hour times).


Tstamp

Description

Sets the DSTAMP, TSTAMP and TODAY properties in the current project. The DSTAMP is in the "yyyymmdd" format, the TSTAMP is in the "hhmm" format and TODAY is "month day year".

These properties can be used in the buildfile, for instance, to create timestamped filenames or used to replace placeholder tags inside documents to indicate, for example, the release date. The best place for this task is in your initialization target.

Parameters

Attribute Description Required

Examples

  <tstamp/>

Uptodate

Description

Sets a property if a Target file is more up to date than a set of Source files. Source files are specified by nested <srcfiles> elements, these are FileSets.

The value part of the property being set is true if the timestamp of the Target file is more recent than the timestamp of every Source file.

Normally, this task is used to set properties that are useful to avoid target execution depending on the relative age of the specified files.

Parameters

Attribute Description Required
property the name of the property to set. Yes
targetfile the file for which we want to determine the status. Yes

Examples

  <uptodate property="xmlBuild.notRequired" targetfile="${deploy}\xmlClasses.jar" >
    <srcfiles dir= "${src}/xml" includes="**/*.dtd" />
  </uptodate>

sets the property xmlBuild.notRequired to the value "true" if the ${deploy}/xmlClasses.jar is more up to date than any of the DTD files in the ${src}/xml directory.


Unjar/Unwar/Unzip

Description

Unzips a zip-, war- or jarfile.

For JDK 1.1 "last modified time" field is set to current time instead of being carried from zipfile.

File permissions will not be restored on extracted files.

Parameters

Attribute Description Required
src zipfile to expand. Yes
dest directory where to store the expanded files. Yes

Examples

<unzip src="${tomcat_src}/tools-src.zip" dest="${tools.home}" />


Untar

Description

Untars a tarfile.

File permissions will not be restored on extracted files.

For JDK 1.1 "last modified time" field is set to current time instead of being carried from tarfile.

Parameters

Attribute Description Required
src tarfile to expand. Yes
dest directory where to store the expanded files. Yes

Examples

<gunzip src="tools.tar.gz"/>
<untar src="tools.tar" dest="${tools.home}"/>


War

Description

An extension of the Jar task with special treatment for files that should end up in the WEB-INF/lib, WEB-INF/classes or WEB-INF directories of the Web Application Archive.

Parameters

Attribute Description Required
warfile the war-file to create. Yes
webxml The deployment descriptor to use (WEB-INF/web.xml). Yes
basedir the directory from which to jar the files. No
compress Not only store data but also compress them, defaults to true No
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
manifest the manifest file to use. No
whenempty Behavior to use if no files match. No

Nested elements

lib

The nested lib element specifies a FileSet. All files included in this fileset will end up in the WEB-INF/lib directory of the war file.

classes

The nested classes element specifies a FileSet. All files included in this fileset will end up in the WEB-INF/classes directory of the war file.

webinf

The nested webinf element specifies a FileSet. All files included in this fileset will end up in the WEB-INF directory of the war file. If this fileset includes a file named web.xml, the file is ignored and you will get a warning.

Examples

Assume the following structure in the project's base directory:

thirdparty/libs/jdbc1.jar
thirdparty/libs/jdbc2.jar
build/main/com/myco/myapp/Servlet.class
src/metadata/myapp.xml
src/html/myapp/index.html
src/jsp/myapp/front.jsp
then the war file myapp.war created with
<war warfile="myapp.war" webxml="src/metadata/myapp.xml">
  <fileset dir="src/html/myapp" />
  <fileset dir="src/jsp/myapp" />
  <lib dir="thirdparty/libs">
    <exclude name="jdbc1.jar" />
  </lib>
  <classes dir="build/main" />
</war>
will consist of
WEB-INF/web.xml
WEB-INF/lib/jdbc2.jar
WEB-INF/classes/com/myco/myapp/Servlet.class
META-INF/MANIFEST.MF
index.html
front.jsp
using Ant's default manifest file. The content of WEB-INF/web.xml is identical to src/metadata/myapp.xml.


Zip

Description

Creates a zipfile.

The basedir attribute is the reference directory from where to zip.

Note that file permissions will not be stored in the resulting zipfile.

It is possible to refine the set of files that are being zipped. This can be done with the includes, includesfile, excludes, excludesfile and defaultexcludes attributes. With the includes or includesfile attribute you specify the files you want to have included by using patterns. The exclude or excludesfile attribute is used to specify the files you want to have excluded. This is also done with patterns. And finally with the defaultexcludes attribute, you can specify whether you want to use default exclusions or not. See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes basedir) as well as the nested <include>, <exclude> and <patternset> elements.

Or, you may place within it nested file sets, or references to file sets. In this case basedir is optional; the implicit file set is only used if basedir is set. You may use any mixture of the implicit file set (with basedir set, and optional attributes like includes and optional subelements like <include>); explicit nested <fileset> elements so long as at least one fileset total is specified. The ZIP file will only reflect the relative paths of files within each fileset.

The whenempty parameter controls what happens when no files match. If skip (the default), the ZIP is not created and a warning is issued. If fail, the ZIP is not created and the build is halted with an error. If create, an empty ZIP file (explicitly zero entries) is created, which should be recognized as such by compliant ZIP manipulation tools.

Parameters

Attribute Description Required
zipfile the zip-file to create. Yes
basedir the directory from which to zip the files. No
compress Not only store data but also compress them, defaults to true No
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
whenempty Behavior when no files match. No

Examples

  <zip zipfile="${dist}/manual.zip"
       basedir="htdocs/manual"
  />

zips all files in the htdocs/manual directory in a file called manual.zip in the ${dist} directory.

  <zip zipfile="${dist}/manual.zip"
       basedir="htdocs/manual"
       excludes="mydocs/**, **/todo.html"
  />

zips all files in the htdocs/manual directory in a file called manual.zip in the ${dist} directory. Files in the directory mydocs, or files with the name todo.html are excluded.

  <zip zipfile="${dist}/manual.zip"
       basedir="htdocs/manual"
       includes="api/**/*.html"
       excludes="**/todo.html"
  />

zips all files in the htdocs/manual directory in a file called manual.zip in the ${dist} directory. Only html files under the directory api are zipped, and files with the name todo.html are excluded.

  <zip zipfile="${dist}/manual.zip">
    <fileset dir="htdocs/manual"/>
    <fileset dir="." includes="ChangeLog.txt"/>
  </zip>

zips all files in the htdocs/manual directory in a file called manual.zip in the ${dist} directory, and also adds the file ChangeLog.txt in the current directory. ChangeLog.txt will be added to the top of the ZIP file, just as if it had been located at htdocs/manual/ChangeLog.txt.


Optional tasks


Cab

Description:

The cab task creates Microsoft cab archive files. It is invoked similar to the jar or zip tasks. This task will only work on Windows, and will be silently ignored on other platforms. You must have the Microsoft cabarc tool available in your executable path.

See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes basedir) as well as the nested <include>, <exclude> and <patternset> elements.

Parameters:

Attribute Description Required
cabfile the name of the cab file to create. Yes
basedir the directory to start archiving files from. Yes
verbose set to "yes" if you want to see the output from the cabarc tool. defaults to "no". No
compress set to "no" to store files without compressing. defaults to "yes". No
options use to set additional command-line options for the cabarc tool. should not normally be necessary. No
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No

Examples

<cab cabfile="${dist}/manual.cab"
     basedir="htdocs/manual" 
  />

cabs all files in the htdocs/manual directory in a file called manual.cab in the ${dist} directory.

<cab cabfile="${dist}/manual.cab"
     basedir="htdocs/manual"
     excludes="mydocs/**, **/todo.html"
  />

cabs all files in the htdocs/manual directory in a file called manual.cab in the ${dist} directory. Files in the directory mydocs, or files with the name todo.html are excluded.

<cab cabfile="${dist}/manual.cab"
     basedir="htdocs/manual"
     includes="api/**/*.html"
     excludes="**/todo.html"
     verbose="yes"
  />

cab all files in the htdocs/manual directory in a file called manual.cab in the ${dist} directory. Only html files under the directory api are archived, and files with the name todo.html are excluded. Output from the cabarc tool is displayed in the build output.


FTP

Description:

The ftp task implements a basic FTP client that can send, receive, list, and delete files. See below for descriptions and examples of how to perform each task.

The ftp task makes no attempt to determine what file system syntax is required by the remote server, and defaults to Unix standards. remotedir must be specified in the exact syntax required by the ftp server. If the usual Unix conventions are not supported by the server, separator can be used to set the file separator that should be used instead.

See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

Parameters:

Attribute Description Required
server the address of the remote ftp server. Yes
port the port number of the remote ftp server. Defaults to port 21. No
userid the login id to use on the ftp server. Yes
password the login password to use on the ftp server. Yes
remotedir the directory to which to upload files on the ftp server. No
action the ftp action to perform, defaulting to "send". Currently supports"put", "get", "del", and "list". No
binary selects binary-mode ("yes") or text-mode ("no") transfers. Defaults to "yes" No
verbose displays information on each file transferred if set to "yes". Defaults to "no". No
depends transfers only new or changed files if set to "yes". Defaults to "no". No
newer a synonym for depends. No
separator sets the file separator used on the ftp server. Defaults to "/". No
listing the file to write results of the "list" action. Required for the "list" action, ignored otherwise. No

Sending Files

The easiest way to describe how to send files is with a couple of examples:

  <ftp server="ftp.apache.org"
       userid="anonymous"
       password="me@myorg.com">
    <fileset dir="htdocs/manual" />
  </ftp>

Logs in to ftp.apache.org as anonymous and uploads all files in the htdocs/manual directory to the default directory for that user.

  <ftp server="ftp.apache.org"
       remotedir="incoming"
       userid="anonymous"
       password="me@myorg.com"
       depends="yes"
  >
    <fileset dir="htdocs/manual" />
  </ftp>

Logs in to ftp.apache.org as anonymous and uploads all new or changed files in the htdocs/manual directory to the incoming directory relative to the default directory for anonymous.

  <ftp server="ftp.apache.org"
       port="2121"
       remotedir="/pub/incoming"
       userid="coder"
       password="java1"
       depends="yes"
       binary="no"
  >
    <fileset dir="htdocs/manual">
      <include name="**/*.html" />
    </fileset>
  </ftp>

Logs in to ftp.apache.org at port 2121 as coder with password java1 and uploads all new or changed HTML files in the htdocs/manual directory to the /pub/incoming directory. The files are transferred in text mode.

  <ftp server="ftp.nt.org"
       remotedir="c:\uploads"
       userid="coder"
       password="java1"
       separator="\"
       verbose="yes"
  >
    <fileset dir="htdocs/manual">
      <include name="**/*.html" />
    </fileset>
  </ftp>

Logs in to the Windows-based ftp.nt.org as coder with password java1 and uploads all HTML files in the htdocs/manual directory to the c:\uploads directory. Progress messages are displayed as each file is uploaded.

Getting Files

Getting files from an FTP server works pretty much the same way as sending them does. The only difference is that the nested filesets use the remotedir attribute as the base directory for the files on the FTP server, and the dir attribute as the local directory to put the files into. The file structure from the FTP site is preserved on the local machine.

  <ftp action="get"
       server="ftp.apache.org"
       userid="anonymous"
       password="me@myorg.com">
    <fileset dir="htdocs/manual" >
      <include name="**/*.html" />
    </fileset>
  </ftp>

Logs in to ftp.apache.org as anonymous and recursively downloads all .html files from default directory for that user into the htdocs/manual directory on the local machine.

Deleting Files

As you've probably guessed by now, you use nested fileset elements to select the files to delete from the remote FTP server. Again, the filesets are relative to the remote directory, not a local directory. In fact, the dir attribute of the fileset is ignored completely.
  <ftp action="del"
       server="ftp.apache.org"
       userid="anonymous"
       password="me@myorg.com" >
    <fileset>
      <include name="**/*.tmp" />
    </fileset>
  </ftp>

Logs in to ftp.apache.org as anonymous and tries to delete all *.tmp files from the default directory for that user. If you don't have permission to delete a file, a BuildException is thrown.

Listing Files

  <ftp action="list"
       server="ftp.apache.org"
       userid=quot;anonymous"
       password="me@myorg.com" 
       listing="data/ftp.listing" >
    <fileset>
      <include name="**" />
    </fileset>
  </ftp>

This provides a file listing in data/ftp.listing of all the files on the FTP server relative to the default directory of the anonymous user. The listing is in whatever format the FTP server normally lists files.


NetRexxC

Description:

Compiles a NetRexx source tree within the running (Ant) VM.

The source and destination directory will be recursively scanned for NetRexx source files to compile. Only NetRexx files that have no corresponding class file or where the class file is older than the java file will be compiled.

Files in the source tree are copied to the destination directory, allowing support files to be located properly in the classpath. The source files are copied because the NetRexx compiler cannot produce class files in a specific directory via parameters

The directory structure of the source tree should follow the package hierarchy.

It is possible to refine the set of files that are being compiled/copied. This can be done with the includes, includesfile, excludes, excludesfile and defaultexcludes attributes. With the includes or includesfile attribute you specify the files you want to have included by using patterns. The exclude or excludesfile attribute is used to specify the files you want to have excluded. This is also done with patterns. And finally with the defaultexcludes attribute, you can specify whether you want to use default exclusions or not. See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns.

This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes srcdir) as well as the nested <include>, <exclude> and <patternset> elements.

Parameters:

Attribute Description Required
binary Whether literals are treated as the java binary type rather than the NetRexx types No
classpath The classpath to use during compilation No
comments Whether comments are passed through to the generated java source No
compact Whether error messages come out in compact or verbose format No
compile Whether the NetRexx compiler should compile the generated java code No
console Whether or not messages should be displayed on the 'console' No
crossref Whether variable cross references are generated No
decimal Whether decimal arithmetic should be used for the NetRexx code No
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
destDir the destination directory into which the NetRexx source files should be copied and then compiled Yes
diag Whether diagnostic information about the compile is generated No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
explicit Whether variables must be declared explicitly before use No
format Whether the generated java code is formatted nicely or left to match NetRexx line numbers for call stack debugging No
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
java Whether the generated java code is produced No
keep Sets whether the generated java source file should be kept after compilation. The generated files will have an extension of .java.keep, not .java No
logo Whether the compiler text logo is displayed when compiling No
replace Whether the generated .java file should be replaced when compiling No
savelog Whether the compiler messages will be written to NetRexxC.log as well as to the console No
sourcedir Tells the NetRexx compiler to store the class files in the same directory as the source files. The alternative is the working directory No
srcDir Set the source dir to find the source Netrexx files Yes
strictargs Tells the NetRexx compiler that method calls always need parentheses, even if no arguments are needed, e.g. aStringVar.getBytes vs. aStringVar.getBytes() No
strictassign Tells the NetRexx compile that assignments must match exactly on type No
strictcase Specifies whether the NetRexx compiler should be case sensitive or not No
strictimport Whether classes need to be imported explicitly using an import statement. By default the NetRexx compiler will import certain packages automatically No
strictprops Whether local properties need to be qualified explicitly using this No
strictsignal Whether the compiler should force catching of exceptions by explicitly named types No
symbols Whether debug symbols should be generated into the class file No
time Asks the NetRexx compiler to print compilation times to the console No
trace Turns on or off tracing and directs the resultant trace output No
utf8 Tells the NetRexx compiler that the source is in UTF8 No
verbose Whether lots of warnings and error messages should be generated Yes

Examples

<netrexxc srcDir="/source/project" includes="vnr/util/*" destDir="/source/project/build" classpath="/source/project2/proj.jar" comments="true" crossref="false" replace="true" keep="true" />


RenameExtensions

Description:

Renames files in the srcDir directory ending with the fromExtension string so that they end with the toExtension string. Files are only replaced if replace is true

See the section on directory based tasks, on how the inclusion/exclusion of files works, and how to write patterns. This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes srcDir) as well as the nested <include>, <exclude> and <patternset> elements.

Parameters:

Attribute Description Required
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. No
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. No
excludesfile the name of a file. Each line of this file is taken to be an exclude pattern No
fromExtention The string that files must end in to be renamed Yes
includes comma separated list of patterns of files that must be included. All files are included when omitted. No
includesfile the name of a file. Each line of this file is taken to be an include pattern No
replace Whether the file being renamed to should be replaced if it already exists No
srcDir The starting directory for files to search in Yes
toExtension The string that renamed files will end with on completion Yes

Examples

<renameext srcDir="/source/project1" includes="**" excludes="**/samples/*" fromExtension=".java.keep" toExtension=".java" replace="true" />


Script

Description:

Execute a script in a BSF supported language.

All items (tasks, targets, etc) of the running project are accessible from the script, using either their name or id attributes.

Scripts can do almost anything a task written in Java could do.

Parameters:

Attribute Description Required
language The programming language the script is written in. Must be a supported BSF language No
src The location of the script as a file, if not inline No

Examples

<project name="squares" default="main" basedir=".">

  <target name="setup">

    <script language="javascript"> <![CDATA[

      for (i=1; i<=10; i++) {
        echo = squares.createTask("echo");
        main.addTask(echo);
        echo.setMessage(i*i);
      }

    ]]> </script>

  </target>

  <target name="main" depends="setup" />

</project>

generates

setup:

main:
1
4
9
16
25
36
49
64
81
100

BUILD SUCCESSFUL

Another example, using references by id and two different scripting languages:

<project name="testscript" default="main">
  <target name="sub">
    <echo id="theEcho" />
  </target>

  <target name="sub1">
    <script language="netrexx"><![CDATA[
      theEcho.setMessage("In sub1")
      sub.execute
    ]]></script>
  </target>

  <target name="sub2">
    <script language="javascript"><![CDATA[
      theEcho.setMessage("In sub2");
      sub.execute();
    ]]></script>
  </target>

  <target name="main" depends="sub1,sub2" />
</project>

generates

sub1:
In sub1

sub2:
In sub2

main:

BUILD SUCCESSFUL

VssGet

Description:

Task to perform GET commands to Microsoft Visual Source Safe.

If you specify two or more attributes from version, date and label only one will be used in the order version, date, label.

Parameters:

Attribute Values Required
login username,password No
vsspath SourceSafe path Yes
localpath Override the working directory and get to the specified path No
writable true or false No
recursive true or false No
version a version number to get No
date a date stamp to get at No
label a label to get for No
ssdir directory where ss.exe resides. By default the task expects it to be in the PATH. No

Note that only one of version, date or label should be specified

Examples

<vssget localPath="C:\mysrc\myproject"
        recursive="true" 
        label="Release1"
        login="me,mypassword"
        vsspath="/source/aProject"
        writable="true"/>
Does a get on the VSS-Project $/source/aproject using the username me and the password mypassword. It will recursively get the files which are labeled Release1 and write them to the local directory C:\mysrc\myproject. The local files will be writable.

Build Events

Ant is capable of generating build events as it performs the tasks necessary to build a project. Listeners can be attached to ant to receive these events. This capability could be used, for example, to connect Ant to a GUI or to integrate Ant with an IDE.

To use build events you need to create an ant Project object. You can then call the addBuildListener method to add your listener to the project. Your listener must implement the org.apache.tools.antBuildListener interface. The listener will receive BuildEvents for the following events

If you wish to attach a listener from the command line you may use the -listener option. For example
ant -listener org.apache.tools.ant.XmlLogger
will run ant with a listener which generates an XML representation of the build progress. This listener is included with ant as is the default listener which generates the logging to standard output.

Writing your own task

It is very easy to write your own task:

  1. Create a Java class that extends org.apache.tools.ant.Task.
  2. For each attribute, write a setter method. The setter method must be a public void method that takes a single argument. The name of the method must begin with "set", followed by the attribute name, with the first character in uppercase, and the rest in lowercase. The type of the attribute can be String, any primitive type (they are converted for you from their String-representation in the build-file. If you specify a boolean your method will be passed the value true if the value specified in the build-file is one of "true", "yes" or "on"), Class, File (in which case the value of the attribute is interpreted relative to the project's basedir) or any other type that has a constructor with a single String argument
  3. If your task has enumerated attributes, you should consider using a subclass of org.apache.tools.ant.types.EnumeratedAttribute as argument to your setter method. See org.apache.tools.ant.taskdefs.FixCRLF for an example.
  4. If the task should support character data, write a public void addText(String) method.
  5. For each nested element, write a create or add method. A create method must be a public method that takes no arguments and returns an Object type. The name of the create method must begin with "create", followed by the element name. An add method must be a public void method that takes a single argument of an Object type with a no argument constructor. The name of the add method must begin with "add", followed by the element name.
  6. Write a public void execute method, with no arguments, that throws a BuildException. This method implements the task itself.

The life cycle of a task

  1. The task gets instantiated using a no-arg constructor at parser time. This means even tasks that are never executed get instantiated.
  2. The tasks gets references to its project and location inside the build file via their inherited project and location variables.
  3. If the user specified an id attribute to this task, the project registers a reference to this newly created task - at parser time.
  4. The task gets a reference to the target it belongs to via its inherited target variable.
  5. init() is called at parser time.
  6. All child elements of the XML element corresponding to this task are created via this task's createXXX() methods or instantiated and added to this task via its addXXX() methods - at parser time.
  7. All attributes of this task get set via their corresponding setXXX methods - at runtime.
  8. The content character data sections inside the XML element corresponding to this task is added to the task via its addText method - at runtime.
  9. All attributes of all child elements get set via their corresponding setXXX methods - at runtime.
  10. execute() is called at runtime.

Example

Let's write our own task, that prints a message on the System.out stream. The task has one attribute called "message".

package com.mydomain;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

public class MyVeryOwnTask extends Task {
  private String msg;

  // The method executing the task
  public void execute() throws BuildException {
    System.out.println(msg);
  }

  // The setter for the "message" attribute
  public void setMessage(String msg) {
    this.msg = msg;
  }
}

It's really this simple;-)

Adding your task to the system is rather simple too:

  1. Make sure the class that implements your task is in the classpath when starting Ant.
  2. Add a taskdef element to your project. This actually adds your task to the system.
  3. Use your task in the rest of the buildfile.

Example

<?xml version="1.0"?>

<project name="OwnTaskExample" default="main" basedir=".">
  <taskdef name="mytask" classname="com.mydomain.MyVeryOwnTask"/>

  <target name="main">
    <mytask message="Hello World! MyVeryOwnTask works!" />
  </target>
</project>

Another way to add a task (more permanently), is to add the task name and implementing class name to the default.properties file in the org.apache.tools.ant.taskdefs package. Then you can use it as if it were a built in task.


FAQ, DTD, external resources

There is an online FAQ for Ant at jakarta.apache.org. This FAQ is interactive, which means you can ask and answer questions online.

One of the questions poping up quite often is "Is there a DTD for buildfiles?". Please refer to the FAQ for an answer.


Feedback

To provide feedback on this software, please subscribe to the Ant User Mail List (ant-user-subscribe@jakarta.apache.org)

If you want to contribute to Ant or stay current with the latest development, join the Ant Development Mail List (ant-dev-subscribe@jakarta.apache.org)

Archives of both lists can be found at http://archive.covalent.net/. Many thanks to Covalent Technologies.


Copyright 2000 Apache Software Foundation. All rights Reserved.