Ant User Manual

by

Version 1.0.8 - 2000/03/04


Table of Contents


Introduction

Ant is a Java based build tool. In theory it is kind of like make without makes 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/tomcat/release/v3.0/ant.zip. If you like living on the edge, you can download the latest version from http://jakarta.apache.org/builds/tomcat/nightly/ant.zip.

Source edition

If you prefer the source edition, you can download Ant from http://jakarta.apache.org/builds/tomcat/release/v3.0/src/jakarta-tools.src.zip (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.


Building Ant

Go to the directory jakarta-ant.

Make sure the JDK is in you path.

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

When finished, use

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

for Windows, and

build.sh -Ddist.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 xml.jar.

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, tools.jar must be added.

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. 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. This can be done with the -D<property>=<value> option, where <property> is the name of the property and <value> the value.

To 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 the target that should be executed. Default the target that is mentioned in the default attribute of the project is used. This can be overridden by adding the target name to the end of the commandline.

Commandline option summary:

ant [options] [target]
Options:
-help                  print this message
-quiet                 be extra quiet
-verbose               be extra verbose
-logfile <file>        use given file for log
-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:

set CLASSPATH=c:\ant\lib\ant.jar;c:\ant\lib\xml.jar;c:\jdk1.2.2\lib\tools.jar
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.


Writing a simple buildfile

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

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 ommitted 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 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 attribute with the name of the property that the target should react to, for example

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

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

It is a good practice to place your property and tstamp tasks in a so called initialization target, on which all other targets depend. Make sure that 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".

A target has the following attributes:

Attribute Description Required
name the name of the project. 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

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.

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".

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@ if 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.

Examples

<project name="foo" default="dist" basedir=".">
  <target name="init">
    <tstamp/>
    <property name="build" value="build" />
    <property name="dist"  value="dist" />
    <filter token="version" value="1.0.3" />
    <filter token="year" value="2000" />
  </target>

  <target name="prepare" depends="init">
    <mkdir dir="${build}" />
  </target>

  <target name="compile" depends="prepare">
    <javac srcdir="${src}" destdir="${build}" filtering="on"/>
  </target>

  <target name="dist" depends="compile">
    <mkdir dir="${dist}/lib" />
    <jar jarfile="${dist}/lib/foo${DSTAMP}.jar"
     basedir="${build}" items="com"/>
  </target>

  <target name="clean" depends="init">
    <deltree dir="${build}" />
    <deltree dir="${dist}" />
  </target>
</project>

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, which both 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

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.


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).

Parameters:

Attribute Description Required
antfile the buildfile to use. No
dir the directory to use as a basedir for the new Ant project. Yes
target the target of the new Ant project that should be executed. No

Examples

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

<ant dir="subproject" />


Available

Description

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

The value part of the properties being set is true if the resource is present, otherwise, the property is not set.

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
classname the class to look for in classpath. Yes
resource the resource to look for in the JVM
file the file to look for.

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. Right now it has efect only under Unix. The permissions are also UNIX style, like the argument for the chmod command.

Parameters

Attribute Description Required
src the file of which the permissions must be changed. Yes
perm the new permissions. Yes

Examples

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

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


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, excludes and defaultexcludes attributes. With the includes attribute you specify the files you want to have included by using patterns. The exclude 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. The patterns are relative to the src directory.

The ignore attribute contains the names of the files/directories that must be excluded from the copy. The names specified in the ignore attribute are just names, they do not contain any path information! Note that this attribute has been replaced by the excludes attribute.

Parameters

Attribute Description Required
src the directory to copy. Yes
dest the directory to copy to. Yes
ignore comma separated list of filenames/directorynames to ignore. No files (except default excludes) are excluded when omitted. (deprecated, use excludes instead). No
includes comma separated list of patterns of files that must be included. All files are included 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
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

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

Examples

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

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


Cvs

Description

Checks out a package/module from a CVS repository.

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

Parameters

Attribute Description Required
cvsRoot the CVSROOT variable. Yes
dest the directory where the checked out files should be placed. Yes
package the package/module to check out. Yes
tag the tag of the package/module to check out. No

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}".


Delete

Description

Deletes a single file.

Parameters

Attribute Description Required
file the file to delete. Yes

Examples

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

deletes the file /lib/ant.jar.

  <delete file="${ant}" />

deletes the file ${ant}.


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

Examples

  <echo message="Hello world" />

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. Yes
dir the directory in which the command should be executed. Yes
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. Yes

Examples

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


Expand

Description

Unzips a zipfile.

Parameters

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

Examples

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


Filter

Description

Sets a token filter for this project. Token filters are used by all tasks that perform file copying operations through the Project commodity methods.

Note: the token string must not contain the separators chars (@).

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

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.


Get

Description

Gets a file from an 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 significant slower than loading a compressed archive with http/ftp.

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 information ("on"/"off"). 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.


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" />


FixCRLF

Description

Adjusts a text file to local.

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

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
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded 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 preceed 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
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.


Jar

Description

Jars a set of files.

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

It is possible to refine the set of files that are being jarred. This can be done with the includes, excludes and defaultexcludes attributes. With the includes attribute you specify the files you want to have included by using patterns. The exclude 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. The patterns are relative to the basedir directory.

The includes, excludes and defaultexcludes attributes replace the items and ignore attributes. The following explains how the deprecated items and ignore attribute behave.

When "*" is used for items, all files in the basedir, and its subdirectories, will be jarred. Otherwise all the files and directories mentioned in the items list will jarred. When a directory is specified, then all files within it are also jarred.

With the ignore attribute, you can specify files or directories to ignore. These files will not be jarred. The items in the ignore attribute override the items in the items attribute. The names specified in the ignore attribute are just names, they do not contain any path information!

Parameters

Attribute Description Required
jarfile the jar-file to create. Yes
basedir the directory from which to jar the files. Yes
items a comma separated list of the files/directories to jar. All files are included when omitted. (deprecated, use includes instead). No
ignore comma separated list of filenames/directorynames to exclude from the jar. No files (except default excludes) are excluded when omitted. (deprecated, use excludes instead). No
includes comma separated list of patterns of files that must be included. All files are included 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
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

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.

Deprecated examples

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

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" items="*" ignore="Test.class" />

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


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. No
fork if enabled triggers the class execution in another VM (disabled by default) No
jvmargs the arguments to pass to the forked VM (ignored if fork is disabled) No

Examples

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

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.

Files in the source tree, that are no java files, are copied to the destination directory, allowing support files to be located properly in the classpath.

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, excludes and defaultexcludes attributes. With the includes attribute you specify the files you want to have included by using patterns. The exclude 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. The patterns are relative to the srcdir directory.

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
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
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. 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
extdirs location of installed extensions. 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
filtering indicates whether token filtering should take place No

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}. It also copies the non-java files from the tree under ${src} to the tree under ${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}. It also copies the non-java files from the tree under ${src} to the tree under ${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.


Javadoc/Javadoc2

Description

Generates code documentation using the javadoc tool.

The source directory will be recursively scanned for Java source files to 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, but it's not used so 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(), we cannot run javadoc inside the same VM without breaking functionality. For this reason, this task always forks the VM. But this is not a performance penalty since javadoc is normally a heavy application and must be called just once.

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 Yes
destdir Destination directory for output files all Yes
sourcefiles Space separated list of source files all at least one of the two
packagenames Space separated list of package files (with terminating wildcard) all
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
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 documenation (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 Generate warning about @serial tag 1.2 No
helpfile Specifies the HTML help file to use 1.2 No
stylesheetfile Specifies the CSS stylesheet to use 1.2 No
charset Charset for cross-platform viewing of generated documentation 1.2 No
docencoding Output file encoding name 1.1 No

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>"
  />

KeySubst

Description

Performs keyword substitution in the source file, and writes the result to the destination file.

Keys in the source file are of the form ${keyname}. The keys attribute contains key/value pairs. When a key is found in the keys attribute, then "${keyname}" is replaced by the corresponding value.

The keys attribute is of the form "name1=value1*name2=value2*name3=value3". The '*' is called the separator, which might we changed with the sep attribute.

Note: the source file and destination file may not be the same.

Parameters

Attribute Description Required
src the source file. Yes
dest the destination file. Yes
sep the separator for the name/value pairs. No
keys name/value pairs for replacement. Yes

Examples

  <keysubst src="abc.txt" dest="def.txt" keys="VERSION=1.0.3*DATE=2000-01-10" />

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.


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".


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 renameing foo.jar.


Replace

Description

Replaces the occurrence of a given string with another string in a file.

Parameters

Attribute Description Required
file file for which the token should be replaced. Yes
token the token which must be replaced. Yes
value the new value for the token. When omitted, an empty string ("") is used. 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.


Rmic

Description

Runs the rmic compiler for a certain class.

Parameters

Attribute Description Required
base the location to store the compiled files. Yes
classname the class for which to run rmic. Yes
filtering indicates whether token filtering should take place No

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.


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, excludes and defaultexcludes attributes. With the includes attribute you specify the files you want to have included by using patterns. The exclude 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. The patterns are relative to the basedir directory.

The includes, excludes and defaultexcludes attributes replace the items and ignore attributes. The following explains how the deprecated items and ignore attribute behave.

When "*" is used for items, all files in the basedir, and its subdirectories, will be tarred. Otherwise all the files and directories mentioned in the items list will tarred. When a directory is specified, then all files within it are also tarred.

With the ignore attribute, you can specify files or directories to ignore. These files will not be tarred. The items in the ignore attribute override the items in the items attribute. The names specified in the ignore attribute are just names, they do not contain any path information!

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
excludes comma separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted. 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

Examples

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

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


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/>

Zip

Description

Creates a zipfile.

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

It is possible to refine the set of files that are being zipped. This can be done with the includes, excludes and defaultexcludes attributes. With the includes attribute you specify the files you want to have included by using patterns. The exclude 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. The patterns are relative to the basedir directory.

The includes, excludes and defaultexcludes attributes replace the items and ignore attributes. The following explains how the deprecated items and ignore attribute behave.

When "*" is used for items, all files in the basedir, and its subdirectories, will be zipped. Otherwise all the files and directories mentioned in the items list will zipped. When a directory is specified, then all files within it are also zipped.

With the ignore attribute, you can specify files or directories to ignore. These files will not be zipped. The items in the ignore attribute override the items in the items attribute. The names specified in the ignore attribute are just names, they do not contain any path information!

Parameters

Attribute Description Required
zipfile the zip-file to create. Yes
basedir the directory from which to zip the files. Yes
items a comma separated list of the files/directories to zip. All files are included when omitted. (deprecated, use includes instead). No
ignore comma separated list of filenames/directorynames to exclude from the zip. No files (except default excludes) are excluded when omitted. (deprecated, use excludes instead). No
includes comma separated list of patterns of files that must be included. All files are included 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
defaultexcludes indicates whether default excludes should be used or not ("yes"/"no"). Default excludes are used when omitted. 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.

Deprecated examples

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

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"
       items="*"
       ignore="mydocs, todo.html"
  />

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


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 one String as an 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.
  3. Write a public void execute method, with no arguments, that throws a BuildException. This method implements the task itself.

It is important to know that Ant first calls the setters for the attributes it encounters for a specific task in the buildfile, before it executes is.

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. In your initialization target, add a taskdef task. 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=".">
  <target name="init">
    <taskdef name="mytask" classname="com.mydomain.MyVeryOwnTask"/>
  </target>

  <target name="main" depends="init">
    <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.


Feedback

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


Copyright © 2000 Apache Software Foundation. All rights Reserved.

Optional tasks


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, excludes and defaultexcludes attributes. With the includes attribute you specify the files you want to have included by using patterns. The exclude 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. The patterns are relative to the srcDir directory.

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
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
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. The patterns are relative to the srcDir directory.

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
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
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.

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

None yet available