Apache Ant Front Page News Documentation External Tools and Tasks Resources Ant FAQ Having Problems? Download Binaries Source Code Jakarta News & Status Mission Guidelines Notes FAQs Get Involved Overview CVS Repositories Mailing Lists Reference Library Bug Database Enhancement Requests |
Questions
> About this FAQ
> Where do I find the latest version of this document? How can I contribute to this FAQ? How do you create the HTML version of this FAQ?
> General
> What is Apache Ant? Why do you call it Ant? Tell us a little bit about Ant's history.
> Installation
> I get checksum errors when I try to extract the `tar.gz` distribution file. Why?
> Using Ant
> Why does Ant always recompile all my Java files? How do I pass parameters from the command line to my build file? How can I use Jikes specific command line switches? How do I include a < character in my command line arguments? How do I redirect standard input or standard output in the `<exec>` task? I've made a <delete> task to delete unwanted sourcesafe control files (CVS files, editor backup files), but it doesn't seem to work. The files never get deleted. What's wrong? I want to execute a particular target only if multiple conditions are true. I have a target I want to skip if a variable is set, so I have `unless="variable"` as an attribute of the target. The trouble is that all of the targets that this target depends on are still executed. Why? 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 anything at all. What's wrong?
> Ant and IDEs/Editors
> Is Ant supported by my IDE/Editor? Why doesn't (X)Emacs/vi/MacOS X's project builder parse the error messages generated by Ant correctly?
> Advanced issues
> Is there a DTD that I can use to validate my build files? How do I include an XML snippet in my build file? How do I send an email with the result of my build process? How do I get at the properties that Ant was running with from inside BuildListener?
> Known problems
> <chmod> or <exec> don't work in Ant 1.3 on Unix JavaDoc failed: java.io.IOException: javadoc: cannot execute
Answers
> Where do I find the latest version of this document?
> The latest version can always be found at Ant's homepage http://jakarta.apache.org/ant/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, the structure is hoped to be self-explaining. If you don't know how to create a patch, see the patches section of 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 `xdocs/stylesheets` subdirectory of Ant's CVS repository - the build file `docs.xml` is used to drive Anakia. This file assumes that you have the `jakarta-site2` module checked out from CVS as well, but if you follow the instruction from Anakia's homepage, you should get it to work without that. Just make sure all required jars are in the task's classpath.
> What is Apache Ant?
> Ant is a Java based build tool. In theory it is kind of like "make" without makes 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 are doing an extremely good job at building things" or "Ants are very small and can carry a weight a dozen times of 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 has been created by James Duncan Davidson, who also is 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 now is 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. Ant became Apache Ant. The first version of Ant that was exposed a lager audience was the one that shipped with Tomcat's 3.1 release on 19 April 2000. This version has later been referenced 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
> 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`).
> 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 of this, 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 setup is different, 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.
> How do I pass parameters from the command line to my build file?
> Use properties: `ant -D<name>=<value>` lets you define values for properties. These 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 javac after that -nowarn | build.compiler.warnings | true == not set
> 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 input stream of the `cat` command to read from a file, something like
> >     shell-prompt> cat < foo
> > and try to translate it into
> >     <exec executable="cat">
> >       <arg value="&lt;" />
> >       <arg value="foo" />
> >     </exec>
> > This will not do what you expect. The input-redirection is performed by your shell, not the command itself, so this should read:
> >     <exec executable="/bin/sh">
> >       <arg value="-c" />
> >       <arg value="cat &lt; foo" />
> >     </exec>
> Note, that you must use the `value` attribute of `<arg>` in the last element.
> I've made a <delete> task to delete unwanted sourcesafe control files (CVS files, editor backup files), 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 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 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 put both an `if` and an `unless` attribute into the target. The target 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 wish 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, but 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 that `<antcall>` tasks do not pass property changes back up to the environment they were called from. 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: If a property `a` has not been set, `${a}` will evaluate to `${a}`. To get a literal `$` in Ant, you have to escape it with another `$` - this will also break the special treatment of the sequence `${`. This is neither readable, nor easy to understand, therefore 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 better 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.
> I have a target I want to skip if a variable is set, so I have `unless="variable"` as an attribute of the target. The trouble is that all of the targets that 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. When your dependencies actually break down the higher level task into several simpler steps, though, this behaviour becomes counterintuitive. There are a couple of solutions available: Put the same condition on each of the dependent targets. 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 anything 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 need to trim the list that the includes would produce, use excludes.
> Is Ant supported by my IDE/Editor?
> See the section on IDE integration on our external tools page.
> Why doesn't (X)Emacs/vi/MacOS X's project builder parse the error messages generated by Ant correctly?
> > Ant adds a "banner" with the name of the current task in front of all 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. 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: It doesn't know about required attributes. Only manual tweaking of this file can help here. It is not complete - if you add new tasks via `<taskdef>` it won't know about it. See this page by Michel Casabianca for a solution to this problem. Note that the DTD you can download at this page is based on Ant 0.3.1. It may even be an invalid DTD. As Ant allows tasks writers to define arbitrary elements, name collisions will happen quite frequently - if your version of Ant contains the optional `<test>` and `<junit>` tasks, there are two XML elements named test (the task and the nested child element of `<junit>`) with different attribute lists. This problem cannot be solved, DTDs don't give a syntax rich enough to support this.
> 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 "file:./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. In combination with a DTD, this would look like this:
> >     <!DOCTYPE project PUBLIC "-//ANT//DTD project//EN" "file:./ant.dtd" [
> >        <!ENTITY include SYSTEM "file:./header.xml">
> >     ]>
> 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 Listener & Logger 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 tatus.
> >          */
> >         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 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 are specified on the command line when running Ant.
> <chmod> or <exec> don'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
> JavaDoc failed: java.io.IOException: javadoc: cannot execute
> There is a bug in the Solaris reference implementation of the JDK, see http://developer.java.sun.com/developer/bugParade/bugs/4230399.html. This also appears to be true under Linux, moving the JDK to the front of the PATH fixes the problem.
Copyright © 2000-2002, Apache Software Foundation