Cari di Apache Ant 
    Apache Ant Tutorial
Daftar Isi
(Sebelumnya) Proxy configurationTargets (Berikutnya)
Using Apache Ant

Writing a Simple Buildfile

Using Apache Ant

Writing a Simple Buildfile

Apache Ant's buildfiles are written in XML. Each buildfile contains one projectand at least one (default) target. Targets contain task elements.Each task element of the buildfile can have an id attribute andcan later be referred to by the value supplied to this. The value hasto be unique. (For additional information, see the Tasks section below.)

Projects

A project has three attributes:

Attribute Description Required
name the name of the project. No
default the default target to use when no target is supplied. No; however, since Ant 1.6.0, every project includes an implicit target that contains any and all top-level tasks and/or types. This target will always be executed as part of the project's initialization, even when Ant is run with the -projecthelp option.
basedir the base directory from which all path calculations are done. This attribute might be overridden by setting the "basedir" property beforehand. When this is done, it must be omitted in the project tag. If neither the attribute nor the property have been set, the parent directory of the buildfile will be used.
A relative path is resolved relative to the directory containing the build file.
No

Optionally, a description for the project can be provided as atop-level <description> element (see the description type).

Each project defines one or more targets.A target is a set of tasks you wantto be executed. When starting Ant, you can select which target(s) youwant 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 example, and a target for creating a distributable. You can only build adistributable when you have compiled first, so the distribute targetdepends on the compile target. Ant resolves these dependencies.

It should be noted, however, that Ant's depends attributeonly specifies the order in which targets should be executed - itdoes not affect whether the target that specifies the dependency(s) getsexecuted if the dependent target(s) did not (need to) run.

More information can be found in the dedicated manual page.

Tasks

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

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

Tasks have a common structure:

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

where name is the name of the task,attributeN is the attribute name, andvalueN is the value for this attribute.

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

All tasks share a task name attribute. The value ofthis attribute will be used in the logging messages generated byAnt.

Tasks can be assigned an id attribute:
<taskname id="taskID" ... />
where taskname is the name of the task, and taskID isa unique identifier for this task.You can refer to thecorresponding task object in scripts or other tasks via this name.For example, in scripts you could do:
<script ... >  task1.setFoo("bar");</script>
to set the foo attribute of this particular task instance.In another task (written in Java), you can access the instance viaproject.getReference("task1").

Note1: If "task1" has not been run yet, thenit has not been configured (ie., no attributes have been set), and if it isgoing to be configured later, anything you've done to the instance maybe overwritten.

Note2: Future versions of Ant will most likely notbe backward-compatible with this behaviour, since there will likely be notask instances at all, only proxies.

Properties

Properties are an important way to customize a build process or to just provide shortcuts for strings that are used repeatedly inside a build file.

In its most simple form properties are defined in the build file (for example by the property task) or might be set outside Ant. A property has a name and a value; the name is case-sensitive. Properties may be used in the value of task attributes or in the nested text of tasks that support them. This is done by placing the property name between "${" and "}" in the attribute value. For example, if there is a "builddir" property with the value "build", then this could be used in an attribute like this: ${builddir}/classes. This is resolved at run-time as build/classes.

With Ant 1.8.0 property expansion has become much more powerful than simple key value pairs, more details can be found in the concepts section of this manual.

Example Buildfile

<project name="MyProject" default="dist" basedir="."> <description> simple example build file </description>  <!-- set global properties for this build -->  <property name="src" location="src"/>  <property name="build" location="build"/>  <property name="dist"  location="dist"/>  <target name="init"> <!-- Create the time stamp --> <tstamp/> <!-- Create the build directory structure used by compile --> <mkdir dir="${build}"/>  </target>  <target name="compile" depends="init" description="compile the source " > <!-- Compile the java code from ${src} into ${build} --> <javac srcdir="${src}" destdir="${build}"/>  </target>  <target name="dist" depends="compile" description="generate the distribution" > <!-- Create the distribution directory --> <mkdir dir="${dist}/lib"/> <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file --> <jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/>  </target>  <target name="clean" description="clean up" > <!-- Delete the ${build} and ${dist} directory trees --> <delete dir="${build}"/> <delete dir="${dist}"/>  </target></project>

Notice that we are declaring properties outside any target. As ofAnt 1.6 all tasks can be declared outside targets (earlier versiononly allowed <property>,<typedef> and<taskdef>). When you do this they are evaluated beforeany targets are executed. Some tasks will generate build failures ifthey are used outside of targets as they may cause infinite loopsotherwise (<antcall> for example).

We have given some targets descriptions; this causes the projecthelpinvocation option to list them as public targets with the descriptions; theother target is internal and not listed.

Finally, for this target to work the source in the src subdirectoryshould be stored in a directory tree which matches the package names. Check the<javac> task for details.

Token Filters

A project can have a set of tokens that might be automatically expanded iffound when a file is copied, when the filtering-copy behavior is selected in thetasks that support this. These might be set in the buildfileby the filter task.

Since this can potentially be a very harmful behavior,the tokens in the files mustbe of the form @token@, wheretoken is the token name that is setin the <filter> task. This token syntax matches the syntax of other build systemsthat perform such filtering and remains sufficiently orthogonal to mostprogramming and scripting languages, as well as with documentation systems.

Note: If a token with the format @token@is found in a file, but nofilter is associated with that token, no changes take place;therefore, no escapingmethod is available - but as long as you choose appropriate names for yourtokens, this should not cause problems.

Warning: If you copy binary files with filtering turned on, you can corrupt thefiles. This feature should be used with text files only.

Path-like Structures

You can specify PATH- and CLASSPATH-typereferences using both":" and ";" as separatorcharacters. Ant willconvert the separator to the correct character of the current operatingsystem.

Wherever path-like values need to be specified, a nested element canbe used. This takes the general form of:

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

The location attribute specifies a single file ordirectory relative to the project's base directory (or an absolutefilename), while the path attribute accepts colon-or semicolon-separated lists of locations. The pathattribute is intended to be used with predefined paths - in any othercase, multiple elements with location attributes should bepreferred.

Since Ant 1.8.2 the location attribute can also contain a wildcard in its last path component (i.e. it can end in a "*") in order to support wildcard CLASSPATHs introduced with Java6. Ant will not expand or evaluate the wildcards and the resulting path may not work as anything else but a CLASSPATH - or even as a CLASSPATH for a Java VM prior to Java6.

As a shortcut, the <classpath> tagsupports path andlocation attributes of its own, so:

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

can be abbreviated to:

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

In addition, one or moreResource Collectionscan be specified as nested elements (these must consist offile-type resources only).Additionally, it should be noted that although resource collections areprocessed in the order encountered, certain resource collection typessuch as fileset,dirset andfilesare undefined in terms of order.

 <classpath>  <pathelement path="${classpath}"/>  <fileset dir="lib"> <include name="**/*.jar"/>  </fileset>  <pathelement location="classes"/>  <dirset dir="${build.dir}"> <include name="apps/**/classes"/> <exclude name="apps/**/*Test*"/>  </dirset>  <filelist refid="third-party_jars"/> </classpath>

This builds a path that holds the value of ${classpath},followed by all jar files in the lib directory,the classes directory, all directories namedclasses under the apps subdirectory of${build.dir}, except thosethat have the text Test in their name, andthe files specified in the referenced FileList.

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

By default a path like structure will re-evaluate all nested resource collections whenever it is used, which may lead to unnecessary re-scanning of the filesystem. Since Ant 1.8.0 path has an optional cache attribute, if it is set to true, the path instance will only scan its nested resource collections once and assume it doesn't change during the build anymore (the default for cache still is false). Even if you are using the path only in a single task it may improve overall performance to set cache to true if you are using complex nested constructs.

A path-like structure can include a reference to another path-likestructure (a path being itself a resource collection)via nested <path> elements:

 <path id="base.path">  <pathelement path="${classpath}"/>  <fileset dir="lib"> <include name="**/*.jar"/>  </fileset>  <pathelement location="classes"/> </path> <path id="tests.path" cache="true">  <path refid="base.path"/>  <pathelement location="testclasses"/> </path>
The shortcuts previously mentioned for <classpath> are also valid for <path>.For example:
 <path id="base.path">  <pathelement path="${classpath}"/> </path>
can be written as:
 <path id="base.path" path="${classpath}"/>

Path Shortcut

In Ant 1.6 a shortcut for converting paths to OS specific strings in properties has been added. One can use the expression ${toString:pathreference} to convert a path element reference to a string that can be used for a path argument. For example:

  <path id="lib.path.ref"> <fileset dir="lib" includes="*.jar"/>  </path>  <javac srcdir="src" destdir="classes"> <compilerarg arg="-Xbootclasspath/p:${toString:lib.path.ref}"/>  </javac>

Command-line Arguments

Several tasks take arguments that will be passed to anotherprocess on the command line. To make it easier to specify argumentsthat contain space characters, nested arg elements can be used.

Attribute Description Required
value a single command-line argument; can contain space characters. Exactly one of these.
file The name of a file as a single command-line argument; will be replaced with the absolute filename of the file.
path A string that will be treated as a path-like string as a single command-line argument; you can use ; or : as path separators and Ant will convert it to the platform's local conventions.
pathref Reference to a path defined elsewhere. Ant will convert it to the platform's local conventions.
line a space-delimited list of command-line arguments.
prefix A fixed string to be placed in front of the argument. In the case of a line broken into parts, it will be placed in front of every part. Since Ant 1.8. No
suffix A fixed string to be placed immediately after the argument. In the case of a line broken into parts, it will be placed after every part. Since Ant 1.8. No

It is highly recommended to avoid the line versionwhen possible. Ant will try to split the command line in a waysimilar to what a (Unix) shell would do, but may create something thatis very different from what you expect under some circumstances.

Examples

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

is a single command-line argument containing a space character,not separate commands "-l" and "-a".

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

This is a command line with two separate arguments, "-l" and "-a".

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

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

References

Any project element can be assigned an identifier using itsid attribute. In most cases the element can subsequentlybe referenced by specifying the refid attribute on anelement of the same type. This can be useful if you are going toreplicate the same snippet of XML over and over again--using a<classpath> structure more than once, for example.

The following example:

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

could be rewritten as:

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

All tasks that use nested elements for PatternSets, FileSets, ZipFileSets or path-like structures accept references to these structures as shown in the examples. Using refid on a task will ordinarily have the same effect (referencing a task already declared), but the user should be aware that the interpretation of this attribute is dependent on the implementation of the element upon which it is specified. Some tasks (the property task is a handy example) deliberately assign a different meaning to refid.

Use of external tasks

Ant supports a plugin mechanism for using third party tasks. For using them you have to do two steps:
  1. place their implementation somewhere where Ant can find them
  2. declare them.
Don't add anything to the CLASSPATH environment variable - this is often the reason for very obscure errors. Use Ant's own mechanisms for adding libraries:
  • via command line argument -lib
  • adding to ${user.home}/.ant/lib
  • adding to ${ant.home}/lib
For the declaration there are several ways:
  • declare a single task per using instruction using <taskdef name="taskname" classname="ImplementationClass"/>
    <taskdef name="for" classname="net.sf.antcontrib.logic.For" /> <for ... />
  • declare a bundle of tasks using a properties-file holding these taskname-ImplementationClass-pairs and <taskdef>
    <taskdef resource="net/sf/antcontrib/antcontrib.properties" /> <for ... />
  • declare a bundle of tasks using a xml-file holding these taskname-ImplementationClass-pairs and <taskdef>
    <taskdef resource="net/sf/antcontrib/antlib.xml" /> <for ... />
  • declare a bundle of tasks using a xml-file named antlib.xml, XML-namespace and antlib: protocoll handler
    <project xmlns:ac="antlib:net.sf.antconrib"/> <ac:for ... />
If you need a special function, you should
  1. have a look at this manual, because Ant provides lot of tasks
  2. have a look at the external task page in the manual (or better online)
  3. have a look at the external task wiki page
  4. ask on the Ant user list
  5. implement (and share) your own
(Sebelumnya) Proxy configurationTargets (Berikutnya)