Apache Ant site Apache Ant logo

the Apache Ant site
Home
Projects
 

Frequently Asked Questions

Questions

About this FAQ

General

Installation

How do I ...

It doesn't work (as expected)

Apache Ant and IDEs/Editors

Advanced Issues

Known Problems

Answers

Where do I find the latest version of this document?

The latest version can always be found at Apache Ant's homepage https://ant.apache.org/faq.html.

How can I contribute to this FAQ?

The page you are looking it is generated from this document. If you want to add a new question, please submit a patch against this document to one of Ant's mailing lists; hopefully, the structure is self-explanatory.

Patches can be created by the svn diff command. See also the Fixing the Bug paragraph in this page.

How do you create the HTML version of this FAQ?

We use Anakia to render the HTML version from the original XML file.

The Velocity stylesheets used to process the XML files can be found in the sources/stylesheets subdirectory of Ant's site SVN repository - the build file build.xml at the top level of the ant site SVN module is used to drive Anakia.

What is Apache Ant?

Ant is a Java-based build tool. In theory, it is kind of like Make, without Make's wrinkles and with the full portability of pure Java code.

Why do you call it Ant?

According to Ant's original author, James Duncan Davidson, the name is an acronym for "Another Neat Tool".

Later explanations go along the lines of "ants do an extremely good job at building things", or "ants are very small and can carry a weight dozens of times their own" - describing what Ant is intended to be.

Tell us a little bit about Ant's history.

Initially, Ant was part of the Tomcat code base, when it was donated to the Apache Software Foundation. It was created by James Duncan Davidson, who is also the original author of Tomcat. Ant was there to build Tomcat, nothing else.

Soon thereafter, several open source Java projects realized that Ant could solve the problems they had with Makefiles. Starting with the projects hosted at Jakarta and the old Java Apache project, Ant spread like a virus and is now the build tool of choice for a lot of projects.

In January 2000, Ant was moved to a separate CVS module and was promoted to a project of its own, independent of Tomcat, and became Apache Ant.

The first version of Ant that was exposed to a larger audience was the one that shipped with Tomcat's 3.1 release on 19 April 2000. This version has later been referred to as Ant 0.3.1.

The first official release of Ant as a stand-alone product was Ant 1.1, released on 19 July 2000. The complete release history:

Ant Version Release Date
1.1 19 July 2000
1.2 24 October 2000
1.3 3 March 2001
1.4 3 September 2001
1.4.1 11 October 2001
1.5 10 July 2002
1.5.1 3 October 2002
1.5.2 3 March 2003
1.5.3 9 April 2003
1.5.4 12 August 2003
1.6.0 18 December 2003
1.6.1 12 February 2004
1.6.2 16 July 2004
1.6.3 28 April 2005
1.6.4 19 May 2005
1.6.5 2 June 2005
1.7.0 19 December 2006
1.7.1 27 June 2008
1.8.0 8 February 2010
1.8.1 7 May 2010
1.8.2 27 December 2010
1.8.3 29 February 2012
1.8.4 23 May 2012
1.9.0 07 March 2013
1.9.1 21 May 2013
1.9.2 12 July 2013
1.9.3 29 December 2013
1.9.4 05 May 2014
1.9.5 03 Jun 2015
1.9.6 02 Jul 2015
1.9.7 12 Apr 2016
1.9.8 31 Dec 2016
1.9.9 06 Feb 2017
1.9.10 06 Feb 2018
1.9.11 27 Mar 2018
1.9.12 22 Jun 2018
1.9.13 13 Jul 2018
1.9.14 17 Mar 2019
1.9.15 13 May 2020
1.9.16 13 July 2021
1.10.0 31 Dec 2016
1.10.1 06 Feb 2017
1.10.2 06 Feb 2018
1.10.3 27 Mar 2018
1.10.4 22 Jun 2018
1.10.6 8 May 2019
1.10.7 5 Sep 2019
1.10.8 13 May 2020
1.10.9 30 September 2020
1.10.10 17 April 2021
1.10.11 13 July 2021
1.10.12 19 October 2021
1.10.13 10 January 2023
1.10.14 20 August 2023

Which version of Java is required to run Apache Ant?

You will need Java installed on your system, version 1.8 or later required. The later the version of Java, the more Ant tasks you get.

The git branch 1.9.x is used for long term support of Ant 1.9.x versions that can be built and run with Java 1.5.

If only the JRE is present but not a full JDK then many tasks will not work.

The following table lists the minimum Java versions required to compile and run Ant. Note that most committers work with more recent versions of the JDK and that Ant doesn't get tested much for older versions.

Ant Version Minimum Java Version
1.1 up to 1.5.4 1.1
1.6.0 up to 1.6.5 1.2
1.7.0 up to 1.7.1 1.3
1.8.0 up to 1.8.3 1.4
Any 1.9.x release and the git branch 1.9.x 1.5
Any 1.10.x release and the current git master branch 1.8

I get checksum errors when I try to extract the tar.gz distribution file. Why?

Ant's distribution contains file names that are longer than 100 characters, which is not supported by the standard tar file format. Several different implementations of tar use different and incompatible ways to work around this restriction.

Ant's <tar> task can create tar archives that use the GNU tar extension, and this has been used when putting together the distribution. If you are using a different version of tar (for example, the one shipping with Solaris), you cannot use it to extract the archive.

The solution is to either install GNU tar, which can be found here, or use the zip archive instead (you can extract it using jar xf).

How do you get ant-1.6.x (or any version later than 1.5.2) to work on on RedHat ES 3?

Redhat ES 3.0 comes installed with ant 1.5.2. Even if you have your PATH and ANT_HOME variables set correctly to a later version of ant, you will always be forced to use the preinstalled version.

To use a later version of ant on this OS you could do the following:

$ ant -version
Apache Ant version 1.5.2-23 compiled on November 12 2003
$ su -
# rpm -e ant ant-libs
# exit
$ hash -r
$ ant -version
Apache Ant version 1.6.2 compiled on July 16 2004

How to I precompile Java Server Pages (JSPs)?

Apache Ant has a built in optional task <jspc> which was intended for that. But this task is deprecated. Here the alternative suggested by the manual:

Instead of relying on container specific JSP-compilers we suggest deploying the raw files (*.jsp) and use the container build-in functions: after deploying run a test suite (e.g. with Cactus or HttpUnit) against the deployed web application. So you'll get then test result and the compiled JSPs.

How do I realize os--specific configurations?

The core idea is using property files which name accords to the os-name. Then simply use the build-in property os.name.

For better use you should also provide a file with default values. But be careful with the correct os-names. For test simply <echo> the ${os.name} on all machines and you can be sure to use the right file names.

          <property file="${os.name}.properties"/>
          <property file="default.properties"/>

How do I add an external task that I've written to the page "External Tools and Tasks"?

Join and post a message to the dev or user mailing list (one list is enough), including the following information:

The preferred format for this information is a patch to this document.

If you have written something bigger than a 'simple plugin' to Ant it may be better to add the link to projects.html. The procedure to add it is the same. The file to patch is this document. The syntax of that file is the same.

How do I create new tasks?

Apart from a lot of information on using Ant, the Manual also contains information on how to extend Ant with new tasks. This information can be found under "Developing with Ant".

Chances are that someone else already created the task you want to create, it may be wise to see External Tools and Tasks and Related Projects first.

How do I pass parameters from the command line to my build file?

Use properties. Using ant -Dname=value lets you define values for properties on the Ant command line. These properties can then be used within your build file as any normal property: ${name} will put in value.

How can I use Jikes-specific command-line switches?

A couple of switches are supported via "magic" properties:

switch property default
+E build.compiler.emacs false == not set
+P build.compiler.pedantic false == not set
+F build.compiler.fulldepend false == not set
(Only for Ant < 1.4; replaced by the nowarn attribute of the <javac> task after that.)
-nowarn
build.compiler.warnings true == not set

With Ant >= 1.5, you can also use nested <compilerarg> elements with the <javac> task.

How do I include a < character in my command-line arguments?

The short answer is "Use: &lt;".

The long answer is that this probably won't do what you want anyway (see the next section).

How do I redirect standard input or standard output in the <exec> task?

Say you want to redirect the standard output stream of the m4 command to write to a file, something like:

shell-prompt> m4 foo.m4 > foo

and try to translate it into

<exec executable="m4">
  <arg value="foo.m4"/>
  <arg value="&gt;"/>
  <arg value="foo"/>
</exec>

This will not do what you expect. The output redirection is performed by your shell, not the command itself, so this should read:

<exec executable="/bin/sh">
  <arg value="-c" />
  <arg value="m4 foo.m4 &gt; foo" />
</exec>

Note that you must use the value attribute of <arg> in the last element, in order to have the command passed as a single, quoted argument. Alternatively, you can use:

<exec executable="/bin/sh">
  <arg line='-c "m4 foo.m4 &gt; foo"'/>
</exec>

Note the double-quotes nested inside the single-quotes.

How do I execute a batch file or shell script from Ant?

On native Unix systems, you should be able to run shell scripts directly. On systems running a Unix-type shell (for example, Cygwin on Windows) execute the (command) shell instead - cmd for batch files, sh for shell scripts - then pass the batch file or shell script (plus any arguments to the script) as a single command, using the /c or -c switch, respectively. See the above section for example <exec> tasks executing sh. For batch files, use something like:

<exec dir="." executable="cmd" os="Windows NT">
  <arg line="/c test.bat"/>
</exec>

I want to execute a particular target only if multiple conditions are true.

There are actually several answers to this question.

If you have only one set and one unset property to test, you can specify both an if and an unless attribute for the target, and they will act as if they are "anded" together.

If you are using a version of Ant 1.3 or earlier, the way to work with all other cases is to chain targets together to determine the specific state you want to test for.

To see how this works, assume you have three properties: prop1, prop2, and prop3. You want to test that prop1 and prop2 are set, and that prop3 is not. If the condition holds true you want to echo "yes".

Here is the implementation in Ant 1.3 and earlier:

<target name="cond" depends="cond-if"/>

<target name="cond-if" if="prop1">
  <antcall target="cond-if-2"/>
</target>

<target name="cond-if-2" if="prop2">
  <antcall target="cond-if-3"/>
</target>

<target name="cond-if-3" unless="prop3">
  <echo message="yes"/>
</target>

Note: <antcall> tasks do not pass property changes back up to the environment they were called from, so you wouldn't be able to, for example, set a result property in the cond-if-3 target, then do <echo message="result is ${result}"/> in the cond target.

Starting with Ant 1.4, you can use the <condition> task.

<target name="cond" depends="cond-if,cond-else"/>

<target name="check-cond">
  <condition property="cond-is-true">
    <and>
      <not>
        <equals arg1="${prop1}" arg2="$${prop1}" />
      </not>
      <not>
        <equals arg1="${prop2}" arg2="$${prop2}" />
      </not>
      <equals arg1="${prop3}" arg2="$${prop3}" />
    </and>
  </condition>
</target>

<target name="cond-if" depends="check-cond" if="cond-is-true">
  <echo message="yes"/>
</target>

<target name="cond-else" depends="check-cond" unless="cond-is-true">
  <echo message="no"/>
</target>

This version takes advantage of two things:

Because testing for a literal ${property} string isn't all that readable or easy to understand, post-1.4.1 Ant introduces the <isset> element to the <condition> task.

Here is the previous example done using <isset>:

<target name="check-cond">
  <condition property="cond-is-true">
    <and>
      <isset property="prop1"/>
      <isset property="prop2"/>
      <not>
        <isset property="prop3"/>
      </not>
    </and>
  </condition>
</target>

The last option is to use a scripting language to set the properties. This can be particularly handy when you need much finer control than the simple conditions shown here but, of course, comes with the overhead of adding JAR files to support the language, to say nothing of the added maintenance in requiring two languages to implement a single system. See the <script> task documentation for more details.

How can I include national characters like German umlauts in my build file?

You need to tell the XML parser which character encoding your build file uses, this is done inside the XML declaration.

By default the parser assumes you are using the UTF-8 encoding instead of your platform's default. For most Western European countries you should set the encoding to ISO-8859-1. To do so, make the very first line of you build file read like

<?xml version="1.0" encoding="ISO-8859-1" ?>

How do I use jar's M switch? I don't want a MANIFEST.

A JAR archive is a ZIP file, so if you don't want a MANIFEST you can simply use <zip>.

If your file names contain national characters you should know that Sun's jar utility like Ant's <jar> uses UTF-8 to encode their names while <zip> uses your platforms default encoding. Use the encoding attribute of <zip> if necessary.

How can I do something like <property name="prop" value="${${anotherprop}}"/> (double expanding the property)?

Without any external help it is tricky.

With <script/>, which needs external libraries, you can do

<script language="javascript">
    propname = project.getProperty("anotherprop");
    project.setNewProperty("prop", propname);
</script>

With AntContrib (external task library) you can do <propertycopy name="prop" from="${anotherprop}"/>.

With Ant 1.6 you can simulate the AntContribs <propertycopy> and avoid the need of an external library:

<macrodef name="propertycopy">
  <attribute name="name"/>
  <attribute name="from"/>
  <sequential>
    <property name="@{name}" value="${@{from}}"/>
  </sequential>
</macrodef>

With the 'props' antlib (external, but also from Ant) you could do the dereferencing with ${${anotherprop} - not just in the property task - instead everywhere in your buildfile (after registering the required property helper).

<propertyhelper>
  <props:nested />
</propertyhelper>
<property name="foo" value="foo.value" />
<property name="var" value="foo" />
<echo> ${${var}} = foo.value </echo>

With Flaka (external Ant Plugin) you could do the dereferencing with #{${anotherprop}} - not just in flaka tasks, but all tasks after installing flaka's property handler.

<project xmlns:fl="antlib:it.haefelinger.flaka">
  <fl:install-property-handler/>
  <property name="foo" value="foo.value"/>
  <property name="var" value="foo" />
  <property name="buildtype" value="test"/>
  <property name="appserv_test" value="//testserver"/>
  <echo>
    #{${var}} = foo.value
    <!-- nested property -->
    #{appserv_${buildtype}}
  </echo>
</project>

How can I delete everything beneath a particular directory, preserving the directory itself?

Most users who go down this path have no problem figuring out that <delete includeemptydirs="true" /> will help them. The seemingly tricky part is preserving the base directory itself, which Ant includes in the directory scan. Fortunately the answer is simple:

<delete includeemptydirs="true">
  <fileset dir="dirtokeep" includes="**/*" />
</delete>

How can I delete a particular directory, if and only if it is empty?

Most users who go down this path have no problem figuring out that <delete includeemptydirs="true" /> will help them. The seemingly tricky part is preserving the non-empty directories, which Ant includes in the directory scan. Fortunately the answer is simple:

<delete includeemptydirs="true">
  <fileset dir="dirtokeepifnotempty" excludes="**/*" />
</delete>

General Advice

There are many reasons why Apache Ant doesn't behave as expected, not all of them are due to Ant bugs. See our Having Problems? page for hints that may help pinning down the reasons for your problem.

Why does Ant always recompile all my Java files?

In order to find out which files should be compiled, Ant compares the timestamps of the source files to those of the resulting .class files. Opening all source files to find out which package they belong to would be very inefficient. Instead, Ant expects you to place your source files in a directory hierarchy that mirrors your package hierarchy and to point Ant to the root of this directory tree with the srcdir attribute.

Say you have <javac srcdir="src" destdir="dest"/>. If Ant finds a file src/a/b/C.java, it expects it to be in package a.b so that the resulting .class file is going to be dest/a/b/C.class.

If your source-tree directory structure does not match your package structure, Ant's heuristic won't work, and it will recompile classes that are up-to-date. Ant is not the only tool that expects a source-tree layout like this.

If you have Java source files that aren't declared to be part of any package, you can still use the <javac> task to compile these files correctly - just set the srcdir and destdir attributes to the actual directory the source files live in and the directory the class files should go into, respectively.

I've used a <delete> task to delete unwanted SourceSafe control files (CVS files, editor backup files, etc.), but it doesn't seem to work; the files never get deleted. What's wrong?

This is probably happening because, by default, Ant excludes SourceSafe control files (vssver.scc) and certain other files from FileSets.

Here's what you probably did:

<delete>
  <fileset dir="${build.src}" includes="**/vssver.scc"/>
</delete>

You need to switch off the default exclusions, and it will work:

<delete>
  <fileset dir="${build.src}" includes="**/vssver.scc"
           defaultexcludes="no"/>
</delete>

For a complete listing of the patterns that are excluded by default, see the user manual.

I have a target I want to skip if a property is set, so I have unless="property" as an attribute of the target, but all the targets this target depends on are still executed. Why?

The list of dependencies is generated by Ant before any of the targets are run. This allows dependent targets, such as an init target, to set properties that can control the execution of the targets higher in the dependency graph. This is a good thing.

However, when your dependencies break down the higher-level task into several smaller steps, this behaviour becomes counter-intuitive. There are a couple of solutions available:

  1. Put the same condition on each of the dependent targets.
  2. Execute the steps using <antcall>, instead of specifying them inside the depends attribute.

In my <fileset>, I've put in an <exclude> of all files followed by an <include> of just the files I want, but it isn't giving me any files at all. What's wrong?

The order of the <include> and <exclude> tags within a <fileset> is ignored when the FileSet is created. Instead, all of the <include> elements are processed together, followed by all of the <exclude> elements. This means that the <exclude> elements only apply to the file list produced by the <include> elements.

To get the files you want, focus on just the <include> patterns that would be necessary to get them. If you find you need to trim the list that the <include> elements produce, then use <exclude> elements.

ant failed to build my program via javac even when I put the needed jars in an external build.properties file and reference them by pathelement or classpath refid.

When ant loads properties from an external file it doesn't touch the value of properties, trailing blanks will not be trimmed for example.

If the value represents a file path, like a jar needed to compile, the task which requires the value, javac for example would fail to compile since it can't find the file due to trailing spaces.

Ant creates WAR files with a lower-case web-inf or JAR files with a lower-case meta-inf directory.

No it doesn't.

You may have seen these lower-case directory names in WinZIP, but WinZIP is trying to be helpful (and fails). If WinZIP encounters a filename that is all upper-case, it assumes it has come from an old DOS box and changes the case to all lower-case for you.

If you extract (or just check) the archive with jar, you will see that the names have the correct case.

With WinZIP (version 8.1 at least), this can be corrected in the configuration. In the Options/Configuration menu, in the View tab, General section, check the "Allow all upper case files names" box. The META-INF and WEB-INF will look correct.

I installed Ant 1.6.x and now get Exception in thread "main" java.lang.NoClassDefFoundError:

The cause of this is that there is an old version of ant somewhere in the class path or configuration.

A version of this problem happens with jars that are in the classpath that include an embedded copy of ant classes. An example of this is some copies of weblogic.jar.

One can check if this is the case by doing (on unix/sh):

        unset CLASSPATH
        ant -version
        

I installed Ant 1.6.x and now get java.lang.InstantiationException: org.apache.tools.ant.Main

The cause of this is that there is an old version of ant somewhere in the class path or configuration.

A version of this problem may be seen on some linux systems. Some linux systems (Fedora Core 2 for example), comes with a version of ant pre-installed. There is a configuration file called /etc/ant.conf which if present, the ant shell script will 'dot' include. On Fedora Core 2, the /etc/ant.conf file resets the ANT_HOME environment variable to /usr/share/ant. This causes the problem that an old version of ant (1.5.x in this cause) will be used with a new version of the ant script file.

One can check if this is the case by doing ant --noconfig -version.

Whenever I use the Ant jar or manifest related tasks, long lines in my manifest are wrapped at 70 characters and the resulting jar does not work in my application server. Why does Ant do this?

Ant implements the Java Jar file specification. Please refer to the notes section where it discusses the maximum allowable length of a line and the concept of continuation characters.

If a jar file produced by Ant does not work in your appserver, and that failure is due to the wrapped manifest, then you need to consult your appserver provider, as it is a bug in their appserver. Far more likely, however, is a problem in your specification of your classpath. It is not Ant's wrapping of your classpath that is the problem.

Do not raise a bug about this issue until you have checked to ensure that the problem is not due to your classpath specification.

<exec> fails with "Cannot run program "...":CreateProcess error=2" on Windows.

A common problem is not having the executable on the PATH. In case you get an error message Cannot run program "...":CreateProcess error=2. The system cannot find the path specified. have a look at your PATH variable.

Just type the command directly on the command line and if Windows finds it, Ant should do it too. (Otherwise ask on the user mailinglist for help.) If Windows can not execute the program add the directory of the programm to the PATH (set PATH=%PATH%;dirOfProgram) or specify the absolute path in the executable attribute in your buildfile.

My <junit> reports are missing the first line containing the failure message.

Starting with Ant 1.8.0 the text " more" has been added to the set of lines that will be filtered out from stacktraces if the filtertrace attribute has been set. The intention is to suppress the "24 more ..." line at the bottom of the trace.

If the failure message contains the word "more" the line containing the message will be removed as well. This is supposed to be fixed in Ant 1.8.3 once it is released.

The only existing work-arounds are to disable filtertrace or change the failure message to not contain the word "more".

Properties are expanded twice in my macrodefed tasks.

If your macrodefed tasks contains attributes, property references are expanded twice, for example

  <macrodef name="echotest">
    <attribute name="message" />
    <sequential>
      <echo message="@{message}" />
    </sequential>
  </macrodef>
  <echotest message="$${basedir}" />

echos the value of the basedir property rather than the text ${basedir} one would expect.

It happens because ${} sequences are expanded once before expanding @{} sequences and once afterwards. This is required to make things like the macrodef in this FAQ work. It enables

<property name="choice" value="2"/>
<property name="thing.1" value="one"/>
<property name="thing.2" value="two"/>
<property name="thing.3" value="three"/>
<propertycopy to="thing" from="thing.${choice}"/>

which wouldn't be possible if properties weren't expanded twice.

If you want to avoid the double expansion, since Ant 1.8.3 you can turn it off explicitly:

  <macrodef name="echotest">
    <attribute name="message" doubleexpanding="false" />
    <sequential>
      <echo message="@{message}" />
    </sequential>
  </macrodef>
  <echotest message="$${basedir}" />

Is Apache Ant supported by my IDE/Editor?

See the section on IDE integration on our External Tools and Tasks page.

Why doesn't (X)Emacs/vi/MacOS X's project builder correctly parse the error messages generated by Ant?

Ant adds a "banner" with the name of the current task in front of all logging messages - and there are no built-in regular expressions in your editor that would account for this.

You can disable this banner by invoking Ant with the -emacs switch. To make Ant autodetect Emacs' compile mode, put this into your .antrc (contributed by Ville Skyttä).

# Detect (X)Emacs compile mode
if [ "$EMACS" = "t" ] ; then
  ANT_ARGS="$ANT_ARGS -emacs"
  ANT_OPTS="$ANT_OPTS -Dbuild.compiler.emacs=true"
fi

Alternatively, you can add the following snippet to your .emacs to make Emacs understand Ant's output.

(require 'compile)
(setq compilation-error-regexp-alist
  (append (list
     ;; works for jikes
     '("^\\s-*\\[[^]]*\\]\\s-*\\(.+\\):\\([0-9]+\\):\\([0-9]+\\):[0-9]+:[0-9]+:" 1 2 3)
     ;; works for javac
     '("^\\s-*\\[[^]]*\\]\\s-*\\(.+\\):\\([0-9]+\\):" 1 2))
  compilation-error-regexp-alist))

Yet another alternative that preserves most of Ant's formatting is to pipe Ant's output through the following Perl script by Dirk-Willem van Gulik:

#!/usr/bin/perl
#
# May 2001 dirkx@apache.org - remove any
# [foo] lines from the output; keeping
# spacing more or less there.
#
$|=1;
while(<STDIN>) {
        if (s/^(\s+)\[(\w+)\]//) {
                if ($2 ne $last) {
                        print "$1\[$2\]";
                        $s = ' ' x length($2);
                } else {
                        print "$1 $s ";
                };
                $last = $2;
        };
        print;
};

Is there a DTD that I can use to validate my build files?

An incomplete DTD can be created by the <antstructure> task - but this one has a few problems:

How do I include an XML snippet in my build file?

You can use XML's way of including external files and let the parser do the job for Ant:

<?xml version="1.0"?>

<!DOCTYPE project [
       <!ENTITY common SYSTEM "common.xml">
]>

<project name="test" default="test" basedir=".">

  <target name="setup">
    ...
  </target>

  &common;

  ...

</project>

will literally include the contents of common.xml where you've placed the &common; entity.

(The filename common.xml in this example is resolved relative to the containing XML file by the XML parser. You may also use an absolute file: protocol URI.)

In combination with a DTD, this would look like this:

<!DOCTYPE project PUBLIC "-//ANT//DTD project//EN" "ant.dtd" [
   <!ENTITY include SYSTEM "header.xml">
]>

Starting with Ant 1.6, there is a new <import> task that can (also) be used to include build file fragments. Unlike the snippets used with entity includes, the referenced files have to be complete Ant build files, though.

The example above would become:

<?xml version="1.0"?>
<project name="test" default="test" basedir=".">

  <target name="setup">
    ...
  </target>

  <import file="./common.xml"/>

  ...

</project>

Unlike entity includes, <import> will let you use Ant properties in the file name.

How do I send an email with the result of my build process?

If you are using a nightly build of Ant 1.5 after 2001-12-14, you can use the built-in MailLogger:

         ant -logger org.apache.tools.ant.listener.MailLogger

See the Listeners & Loggers documentation for details on the properties required.

For older versions of Ant, you can use a custom BuildListener that sends out an email in the buildFinished() method. Will Glozer <will.glozer@jda.com> has written such a listener based on JavaMail. The source is:

import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import org.apache.tools.ant.*;

/**
 * A simple listener that waits for a build to finish and sends an email
 * of the results.  The settings are stored in "monitor.properties" and
 * are fairly self explanatory.
 *
 * @author      Will Glozer
 * @version     1.05a 09/06/2000
 */
public class BuildMonitor implements BuildListener {
    protected Properties props;

    /**
     * Create a new BuildMonitor.
     */
    public BuildMonitor() throws Exception {
        props = new Properties();
        InputStream is = getClass().getResourceAsStream("monitor.properties");
        props.load(is);
        is.close();
    }

    public void buildStarted(BuildEvent e) {
    }

    /**
     * Determine the status of the build and the actions to follow, now that
     * the build has completed.
     *
     * @param       e       Event describing the build status.
     */
    public void buildFinished(BuildEvent e) {
        Throwable th = e.getException();
        String status = (th != null) ? "failed" : "succeeded";

        try {
            String key = "build." + status;
            if (props.getProperty(key + ".notify").equalsIgnoreCase("false")) {
                    return;
            }

            Session session = Session.getDefaultInstance(props, null);

            MimeMessage message = new MimeMessage(session);
            message.addRecipients(Message.RecipientType.TO, parseAddresses(
                props.getProperty(key + ".email.to")));
            message.setSubject(props.getProperty(key + ".email.subject"));

            BufferedReader br = new BufferedReader(new FileReader(
                props.getProperty("build.log")));
            StringWriter sw = new StringWriter();

            String line = br.readLine();
            while (line != null) {
                sw.write(line);
                sw.write("\n");
                line = br.readLine();
            }
            br.close();

            message.setText(sw.toString(), "UTF-8");
            sw.close();

            Transport transport = session.getTransport();
            transport.connect();
            transport.send(message);
            transport.close();
        } catch (Exception ex) {
            System.out.println("BuildMonitor failed to send email!");
            ex.printStackTrace();
        }
    }

    /**
     * Parse a comma separated list of internet email addresses.
     *
     * @param       s       The list of addresses.
     * @return      Array of Addresses.
     */
    protected Address[] parseAddresses(String s) throws Exception {
        StringTokenizer st = new StringTokenizer(s, ",");
        Address[] addrs = new Address[st.countTokens()];

        for (int i = 0; i < addrs.length; i++) {
            addrs[i] = new InternetAddress(st.nextToken());
        }
        return addrs;
    }

    public void messageLogged(BuildEvent e) {
    }

    public void targetStarted(BuildEvent e) {
    }

    public void targetFinished(BuildEvent e) {
    }

    public void taskStarted(BuildEvent e) {
    }

    public void taskFinished(BuildEvent e) {
    }
}

With a monitor.properties like this:

# configuration for build monitor

mail.transport.protocol=smtp
mail.smtp.host=<host>
mail.from=Will Glozer <will.glozer@jda.com>

build.log=build.log

build.failed.notify=true
build.failed.email.to=will.glozer@jda.com
build.failed.email.subject=Nightly build failed!

build.succeeded.notify=true
build.succeeded.email.to=will.glozer@jda.com
build.succeeded.email.subject=Nightly build succeeded!

monitor.properties should be placed right next to your compiled BuildMonitor.class. To use it, invoke Ant like:

ant -listener BuildMonitor -logfile build.log

Make sure that mail.jar from JavaMail and activation.jar from the Java Beans Activation Framework are in your CLASSPATH.

How do I get at the properties that Ant was running with from inside BuildListener?

You can get at a hashtable with all the properties that Ant has been using through the BuildEvent parameter. For example:

public void buildFinished(BuildEvent e) {
    Hashtable table = e.getProject().getProperties();
    String buildpath = (String)table.get("build.path");
    ...
}

This is more accurate than just reading the same property files that your project does, since it will give the correct results for properties that were specified on the Ant command line.

<exec> causes other tasks to hang or leads to strange behaviour of <input> tasks.

When Apache Ant forks a new process for example by using the <exec>, <apply> or <java> tasks, it will also start a new thread reading from standard input and sending everything that it has read to that process.

Unfortunately Ant has no way to know whether the forked process is ever going to read any input, so it will start such a thread even if the process doesn't need one.

This behaviour leads to strange side effects like the Ant process being suspended when a build forking new process is run as a background process on Unix-like systems or <input> tasks requiring additional inputs if they come after an <exec> task.

Fortunately there is a workaround for this, always specify inputstring="" for any <exec> task (or one of its sibblings) if you know the forked process doesn't consume any input.

<javac> causes a StackOverflowError

For some Java source files it is possible that causes a StackOverlowError is thrown inside Sun's javac compiler. As far as we can tell this is not triggered by a bug in Ant.

It is possible to work around this problem by setting <javac>'s fork attribute to true.

Ant 1.7.0 doesn't build from sources without JUnit

When building Ant 1.7.0 from the source release without junit.jar the build fails with the message "We cannot build the test jar unless JUnit is present".

With Ant 1.7.0 we've started to add ant-testutil.jar as part of the distribution and this causes a hard dependency on JUnit - at least in version 1.7.0. Unfortunately the installation docs don't say so.

There are two workarounds:

  1. Add junit.jar to your CLASSPATH when building Ant.
  2. Change Ant's buildfile and remove test-jar from the depends list of the dist-lite target.

<chmod> or <exec> doesn't work in Ant 1.3 on Unix

The antRun script in ANT_HOME/bin has DOS instead of Unix line endings; you must remove the carriage-return characters from this file. This can be done by using Ant's <fixcrlf> task or something like:

tr -d '\r' < $ANT_HOME/bin/antRun > /tmp/foo
mv /tmp/foo $ANT_HOME/bin/antRun

<style> or <junit> ignores my <classpath>

Starting with Ant 1.7.0, <junit> will honor your nested <classpath>.

These tasks don't ignore your classpath setting, you are facing a common problem with delegating classloaders.

This question collects a common type of problem: A task needs an external library and it has a nested classpath element so that you can point it to this external library, but that doesn't work unless you put the external library into the CLASSPATH or place it in ANT_HOME/lib.

Some background is necessary before we can discuss solutions for Ant 1.5.x and Ant 1.6.x.

When you specify a nested <classpath> in Ant, Ant creates a new class loader that uses the path you have specified. It then tries to load additional classes from this classloader.

In most cases - for example using <style> or <junit> - Ant doesn't load the external library directly, it is the loaded class that does so.

In the case of <junit> it is the task implementation itself and in the case of <style> it is the implementation of the org.apache.tools.ant.taskdefs.XSLTLiaison class.

As of Ant 1.7 <junit> no longer requires you to have junit.jar in Ant's startup classpath even if ant-junit.jar is present there.

Ant's class loader implementation uses Java's delegation model, see https://download.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html the paragraph

The ClassLoader class uses a delegation model to search for classes and resources. Each instance of ClassLoader has an associated parent class loader. When called upon to find a class or resource, a ClassLoader instance will delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself. The virtual machine's built-in class loader, called the bootstrap class loader, does not itself have a parent but may serve as the parent of a ClassLoader instance.

The possible solutions depend on the version of Ant you use, see the next sections.

<style> or <junit> ignores my <classpath> - Ant 1.5.x version

Please read the previous entry before you go ahead.

First of all let's state that Ant's wrapper script (ant or ant.bat) adds all .jar files from ANT_HOME/lib to CLASSPATH, therefore "in CLASSPATH" shall mean "either in your CLASSPATH environment variable or ANT_HOME/lib" for the rest of this answer.

The root of the problem is that the class that needs the external library is on the CLASSPATH.

Let's see what happens when you load the <junit> task. Ant's class loader will consult the bootstrap class loader first, which tries to load classes from CLASSPATH. The bootstrap class loader doesn't know anything about Ant's class loader or even the path you have specified.

If the bootstrap class loader can load the class Ant has asked it to load (which it can if optional.jar is part of CLASSPATH), this class will try to load the external library from CLASSPATH as well - it doesn't know anything else - and will not find it unless the library is in CLASSPATH as well.

To solve this, you have two major options:

  1. put all external libraries you need in CLASSPATH as well this is not what you want, otherwise you wouldn't have found this FAQ entry.
  2. remove the class that loads the external library from the CLASSPATH.

The easiest way to do this is to remove optional.jar from ANT_HOME/lib. If you do so, you will have to <taskdef> all optional tasks and use nested <classpath> elements in the <taskdef> tasks that point to the new location of optional.jar. Also, don't forget to add the new location of optional.jar to the <classpath> of your <style> or <junit> task.

If you want to avoid to <taskdef> all optional tasks you need, the only other option is to remove the classes that should not be loaded via the bootstrap class loader from optional.jar and put them into a separate archive. Add this separate archive to the <classpath> of your <style> or <junit> task - and make sure the separate archive is not in CLASSPATH.

In the case of <junit> you'd have to remove all classes that are in the org/apache/tools/ant/taskdefs/optional/junit directory, in the <style> case it is one of the *Liaison classes in org/apache/tools/ant/taskdefs/optional.

If you use the option to break up optional.jar for <junit> or remove ant-junit.jar, you still have to use a <taskdef> with a nested <classpath> to define the junit task.

<style> or <junit> ignores my <classpath> - Ant 1.6.x version

Please read the general entry before you go ahead.

The wrapper script of Ant 1.6.x no longer adds the contents of ANT_HOME/lib to CLASSPATH, instead Ant will create a classloader on top of the bootstrap classloader - let's call it the coreloader for the rest of this answer - which holds the contents of ANT_HOME/lib. Ant's core and its tasks will be loaded through this classloader and not the bootstrap classloader.

This causes some small but notable differences between Ant 1.5.x and 1.6.x. Most importantly, a third-party task that is part of CLASSPATH will no longer work in Ant 1.6.x since the task now can't find Ant's classes. In a sense this is the same problem this entry is about, only ant.jar has become the external library in question now.

This coreloader also holds the contents of ~/.ant/lib and any file or directory that has been specified using Ant's -lib command line argument.

Let's see what happens when you load the <junit> task. Ant's class loader will consult the bootstrap class loader first, which tries to load classes from CLASSPATH. The bootstrap class loader doesn't know anything about Ant's class loader or even the path you have specified. If it fails to find the class using the bootstrap classloader it will try the coreloader next. Again, the coreloader doesn't know anything about your path.

If the coreloader can load the class Ant has asked it to load (which it can if ant-junit.jar is in ANT_HOME/lib), this class will try to load the external library from coreloader as well - it doesn't know anything else - and will not find it unless the library is in CLASSPATH or the coreloader as well.

To solve this, you have the following major options:

  1. put all external libraries you need in CLASSPATH as well this is not what you want, otherwise you wouldn't have found this FAQ entry.
  2. put all external libraries you need in ANT_HOME/lib or .ant/lib. This probably still isn't what you want, but you might reconsider the .ant/lib option.
  3. Always start Ant with the -lib command line switch and point to your external libraries (or the directories holding them).
  4. remove the class that loads the external library from the coreloader.

In Ant 1.6 optional.jar has been split into multiple jars, each one containing classes with the same dependencies on external libraries. You can move the "offending" jar out of ANT_HOME/lib. For the <junit> task it would be ant-junit.jar.

If you do so, you will have to <taskdef> all optional tasks that need the external library and use nested <classpath> elements in the <taskdef> tasks that point to the new location of ant-*.jar. Also, don't forget to add the new location of ant-*.jar to the <classpath> of your <style> or <junit> task.

For example

    <taskdef name="junit"
            class="org.apache.tools.ant.taskdefs.optional.junit.JUnitTask">
      <classpath>
        <pathelement location="HOME-OF/junit.jar"/>
        <pathelement location="NEW-HOME-OF/ant-junit.jar"/>
      </classpath>
    </taskdef>

Why do my custom task containers see Unknown Elements in Ant 1.6 - they worked in Ant 1.5?

The objects added in TaskContainer.addTask(Task task) have changed from Tasks to UnknownElements.

There was a number of valid reasons for this change. But the backward compatibility problems were not noticed until after Ant 1.6.0 was released.

Your container class will need to be modified to check if the Task is an UnknownElement and call perform on it to convert it to a Task and to execute it. (see apache.tools.ant.taskdefs.Sequential)

If you want to do more processing on the task, you need to use the techniques in apache.tools.ant.taskdefs.Antlib#execute() This does make use of one 1.6 method call (UE#getRealObject()), you need to use UE#getTask() instead - this will return null for non tasks (types like fileset id=x).

So.. iterate over the tasks, if they are UEs, convert them to tasks, using UE#maybeConfigure and UE#getTask()

        for (Iterator i = tasks.iterator(); i.hasNext();) {
           Task t = (Task) i.next();
           if (t instanceof UnknownElement) {
              ((UnknownElement) t).maybeConfigure();
              t = ((UnknownElement) t).getTask();
              if (t == null) {
                  continue;
              }
           }
           // .... original Custom code
        }
        

This approach should work for ant1.5 and ant1.6.

Ant runs into an infinite loop/throws an OutOfMemoryError when I compile my project under Mac OS X.

Apple's Java VMs reside in /System/Library/Frameworks/JavaVM.framework/Versions/X.Y.Z and JAVA_HOME will usually be something like /System/Library/Frameworks/JavaVM.framework/Versions/X.Y.Z/Home.

Inside this home directory there is a symbolic link named shared_bundle that links three levels up, i.e. to /System/Library/Frameworks/JavaVM.framework.

If your build file contains a fileset like

<fileset dir="${java.home}" includes="**/*.jar"/>

Ant is going to follow the shared_bundle symlink and ends up recursing into all your installed VMs. Even worse, it will enter /System/Library/Frameworks/JavaVM.framework/Versions/X.Y.Z/Home and will once again follow the same symlink.

Ant versions after Ant 1.7.1 will detect the infinite loop they are in, but the resulting fileset may still be too big to deal with, in particular if you have many different VM versions installed. The problem is amplified by the fact that each installed version has a shared_bundle symlink in it.

One solution is to not allow the fileset to follow symbolic links at all, like in

<fileset dir="${java.home}" includes="**/*.jar" followsymlinks="false"/>

another one excludes the shared_bundle directories:

<fileset dir="${java.home}" includes="**/*.jar" excludes="**/shared_bundle/**"/>

For Ant 1.7.1 and earlier excluding shared_bundle may not be enough since there is another symlink bundle that points to the Home directory and will cause infite recursions as well.

extension-point doesn't work with import like the documentation states.

Yes, there is a bug in Ant 1.8.0.

When using two build files like

importing.xml:
<project>
   ...
   <import file="imported.xml"/>
   <target name="bar" extensionOf="foo"/>
</project>
imported.xml:
<project>
   <extension-point name="foo"/>
</project>

Ant 1.8.0 will fail, claiming there was no extension point named "foo".

This bug has been fixed for Ant 1.8.1. For Ant 1.8.0 there is a work-around: add an additional layer of importing like in

importing.xml:
<project>
   <target name="bar" extensionOf="foo"/>
</project>
imported.xml:
<project>
   <extension-point name="foo"/>
</project>
build.xml:
<project>
   <import file="imported.xml"/>
   <import file="importing.xml"/>
</project>

How do I deal with the javadoc vulnerability CVE-2013-1571

There is a frame injection bug in Javadocs as produced by all Oracle JDK's javadoc tool prior to Java 7 update 25.

If you cannot upgrade your JDK you can use the patchtool provided by Oracle. Alternatively the macrodef provided as part of Issue 55132 can be used as part of your build process.

Ant 1.9.2 will postprocess the generated javadocs as part of the javadoc task.