0% found this document useful (0 votes)
16 views15 pages

A3 Using Ant

Uploaded by

toanvmk3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views15 pages

A3 Using Ant

Uploaded by

toanvmk3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Getting Started with ANT

ANT is an open –source tool. It’s available from:


http://ant.apache.org/

Windows Install

Download and extract the files in the ant zip.

Installing Ant

The binary distribution of Ant consists of the following directory layout:

ant
+--- bin // contains launcher scripts
|
+--- lib // contains Ant jars plus necessary dependencies
|
+--- docs // contains documentation
| +--- ant2 // a brief description of ant2 requirements
| |
| +--- images // various logos for html documentation
| |
| +--- manual // Ant documentation (a must read ;-)
|
+--- etc // contains xsl goodies to:

// - create an enhanced report from xml output of various tasks.


// - migrate your build files and get rid of 'deprecated' warning
// - ... and more ;-)

Only the bin and lib directories are required to run Ant. To install Ant, choose a
directory and copy the distribution file there. This directory will be known as
ANT_HOME.

ANT Setup

Before you can run ant there is some additional set up you will need to do:

• Add the bin directory to your path.


• Set the ANT_HOME environment variable to the directory where you installed Ant.
On some operating systems the ant wrapper scripts can guess ANT_HOME (Unix
dialects and Windows NT/2000) - but it is better to not rely on this behavior.
• Optionally, set the JAVA_HOME environment variable (see the Advanced section
below). This should be set to the directory where your JDK is installed.

Note: Do not install Ant's ant.jar file into the lib/ext directory of the JDK/JRE. Ant is an
application, whilst the extension directory is intended for JDK extensions. In particular
there are security restrictions on the classes which may be loaded by an extension.

1/25/2005 1
Everything ready?
at the command prompt type:

ant –version

you should see something like:

Apache Ant version 1.6.2 compiled on July 16 2004

Writing an Ant Build File: Hello World


There is a long standing tradition in software of starting with "Hello
World." This example assumes that you've successfully installed Ant
and that you understand the basics of XML syntax.

So let’s look at what it takes to get ant to say Hello World. Copy the following xml into a
file named "build.xml" (the default name assumed by ant).

<project default="hello">
<target name="hello">
<echo message="Hello, World"/>
</target>
</project>

Then execute ant.


$ ant
Buildfile: build.xml

hello:
[echo] Hello, World

BUILD SUCCESSFUL
Total time: 2 seconds

Build Files

Now that we’ve got a build file, let's examine it. Like all XML files, there’s a hierarchy
with tag elements nested in other tag elements. With ant, the hierarchy reflects how we
think about software projects with milestones (targets) and the tasks needed to meet those
targets.

• Project
The project is the root element of the build file, it contains one or more targets.

1/25/2005 2
The default attribute is required and specifies the default build target (in this case:
"hello").
o Target
A target represents a project milestone in ant, it contains zero or more
tasks. The name attribute is required and specifes the name of the target
(in this case: "hello"). Users may specify which target that would like to
achieve via the command line (see below).
§ Task (echo in this case)
Tasks are the smallest units of work in ant. Tasks may operate on
many files, but the same operation will be applied to each file.
The echo task's message attribute specifies the text that is
generated by this task.

Next, let's create another build file and examine some common command line options in
ant. Copy the following lines into a file named "echo.xml" (the new lines are shown in
bold).

<project default="hello">
<target name="hello">
<echo message="Hello, World"/>
</target>

<target name="goodbye">
<echo message="Goodbye, Cruel World"/>
</target>
</project>

Execution a specific ant xml file with –f option:

• -f echo.xml to specify "echo.xml" as the build file


• goodbye to specify "goodbye" as the target rather than the default

$ ant -f echo.xml goodbye


Buildfile: echo.xml

goodbye:
[echo] Goodbye, Cruel World

BUILD SUCCESSFUL
Total time: 2 seconds

1/25/2005 3
Setting up depends in your ant file
Finally, let's take a look at the target depends attribute. Edit "echo.xml" and add the target
"all" as shown below:

<project default="hello">
<target name="hello">
<echo message="Hello, World"/>
</target>

<target name="goodbye">
<echo message="Goodbye, Cruel World"/>
</target>

<target name="all" depends="hello,goodbye" />


</project>

The target depends attribute specifies targets that should be achieved prior to executing
the current target. Ant will attempt to execute depends targets left to right, but this may
be altered by their respective depends targets. In this case "hello" and "goodbye" have no
dependencies, so they will execute in that order.

$ ant -f echo.xml all


Buildfile: echo.xml

hello:
[echo] Hello, World

goodbye:
[echo] Goodbye, Cruel World

all:

BUILD SUCCESSFUL
Total time: 2 seconds

1/25/2005 4
Writing an Ant Build File: Java Compilation
Copy the following lines into a file named "build.xml" (the default name assumed by
ant).

<project default="compile">

<target name="compile">
<javac srcdir="." />
</target>

</project>

And execute ant.


$ ant

Buildfile: build.xml

compile:

[javac] Compiling 2 source files

BUILD SUCCESSFUL

Total time: 5 seconds

Now that we've got a working build file, let's take a closer look at it's contents:

• Project
The project is the root element of the build file, it contains one or more targets.
The default attribute is required and specifies the default build target (in this case:
"compile").

Using Property variables

Next, let's create another build file and look at how to define our source directory as an
ant variable. Note that we’ve declared “.” (use current directory) as the value of the
property called mysrc. We then use this value in the javac task through the use of the
${mysrc} construct. When ant sees this, it substitutes the value of mysrc when executing
the javac task.

<project default="compile">
<property name="mysrc" value = "."/>

1/25/2005 5
<target name="compile">
<javac srcdir="${mysrc}" />
<echo message="Java Version = ${ant.java.version}" />
</target>

</project>

Execute ant using either:

• -buildfile build.01.xml to specify "build.01.xml" as the default build file,


OR the shortcut
• -f build.01.o.xml to specify "build.01.xml" as the build file

$ ant -f build.01.xml
Buildfile: build.01.xml

compile:
[echo] Java Version = 1.4

BUILD SUCCESSFUL
Total time: 1 second

Note that we have added another task to the target. It’s the built in echo task that displays
output on the console. Here we access one of the predefined ant properties,
ant.java.version, whose value is the current java runtime version.

ANT Properties

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; the name is case-
sensitive. Properties may be used in the value of task attributes. 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.

Built-in Properties

Ant provides access to all system properties as if they had been defined using a
<property> task. For example, ${os.name} expands to the name of the operating
system.

For a list of system properties see the Javadoc of System.getProperties.

In addition, Ant has some built-in properties:

1/25/2005 6
basedir the absolute path of the project's basedir (as set
with the basedir attribute of <project>).
ant.file the absolute path of the buildfile.
ant.version the version of Ant
ant.project.name the name of the project currently executing;
it is set in the name attribute of <project>.
ant.java.version the JVM version Ant detected; currently it can hold
the values "1.1", "1.2", "1.3" and "1.4".

1/25/2005 7
More on Ant Buildfile with Java
Example 1-1. build.xml

<?xml version="1.0"?>

<!-- build.xml - a simple Ant buildfile -->


<project name="Simple Buildfile" default="compile" basedir=".">

<!-- The directory containing source code -->


<property name="src.dir" value="src"/>

<!-- Temporary build directories -->


<property name="build.dir" value="build"/>
<property name="build.classes" value="${build.dir}/classes"/>
<property name="build.lib" value="${build.dir}/lib"/>

<!-- Target to create the build directories prior to the -->


<!-- compile target. -->
<target name="prepare">
<mkdir dir="${build.dir}"/>
<mkdir dir="${build.classes}"/>
<mkdir dir="${build.lib}"/>
</target>

<target name="clean" description="Removes all generated files.">


<delete dir="${build.dir}"/>
</target>

<target name="compile" depends="prepare"


description="Compiles all source code.">
<javac srcdir="${src.dir}" destdir="${build.classes}"/>
</target>

<target name="jar" depends="compile"


description="Generates oreilly.jar in the 'dist' directory.">
<!-- Exclude unit tests from the final JAR file -->
<jar jarfile="${build.lib}/oreilly.jar"
basedir="${build.classes}"
excludes="**/*Test.class"/>
</target>

<target name="all" depends="clean,jar"


description="Cleans, compiles, then builds the JAR file."/>

</project>

1/25/2005 8
Notes:

Ant buildfiles are XML files and can be created with any text editor.

l The first line is the optional XML declaration. If present, it must be the very first line
in the XML file; no preceding blank lines are allowed. In fact, even a single blank
space before <?xml causes the XML parser to fail.
l XML is very picky about capitalization, quotes, and proper tag syntax. If any item is
incorrect, Ant fails because its underlying XML parser fails.

Bad XML?
The following example shows the output of Ant if the </project> end tag is typed incorrectly as
</Project>:

Buildfile: build.xml
BUILD FAILED
C:\antbook\build.xml:41: Expected "</project>" to terminate
element starting on line 4.
Total time: 2 seconds

Executing Ant
To execute the tasks in the default target, compile, type the following command from the
directory containing our sample build.xml file:

ant
Ant will open the default buildfile, which is build.xml, and execute that buildfile's default target
(which in our case is compile). You should see the following output, assuming your
directory is called antbook:

Buildfile: build.xml
prepare:
[mkdir] Created dir: C:\antbook\build
[mkdir] Created dir: C:\antbook\build\classes
[mkdir] Created dir: C:\antbook\build\lib
compile:
[javac] Compiling 3 source files to C:\antbook\build\classes
BUILD SUCCESSFUL
Total time: 5 seconds

When you invoke Ant without specifying a buildfile name, Ant searches for a file named
build.xml in the current working directory. You aren't limited to this default; you can use any
name you like for the buildfile. For example, if we call our buildfile proj.xml, we must type this
command, instead:

ant -buildfile proj.xml

1/25/2005 9
We can also explicitly specify one or more targets to run. We can type ant clean to remove all
generated code, for instance. If our buildfile is called proj.xml, and we want to execute the
clean target, we type ant -buildfile proj.xml clean. Our output would look something
like this:

Buildfile: proj.xml
clean:
[delete] Deleting directory C:\antbook\build
BUILD SUCCESSFUL
Total time: 2 seconds

Asking Ant for Help

You may have noticed that some of our targets include the description attribute, while others
do not. This is because Ant distinguishes between main targets and subtargets. Targets
containing descriptions are main targets, and those without are considered subtargets. Other than
documentation differences, main targets and subtargets behave identically. Typing

ant –projecthelp

from our project base directory produces the following output:


Buildfile: build.xml

Default target:
compile Compiles all source code.

Main targets:
all Cleans, compiles, then builds the JAR file.
clean Removes all generated files.
compile Compiles all source code.
jar Generates oreilly.jar in the 'dist' directory.

Subtargets:
prepare

BUILD SUCCESSFUL
Total time: 2 seconds

1/25/2005 10
ANT Syntax

The syntax to use to invoke Ant from the command-line is as follows:


ant [option [option...]] [target [target...]]
option := {-help
|-projecthelp
|-version
|-quiet
|-verbose
|-debug
|-emacs
|-logfile filename
|-logger classname
|-listener classname
|-buildfile filename
|-Dproperty=value
|-find filename}

A Buildfile Template

Shown next is a generic buildfile good for using as a template. A buildfile consists of the
<project> element with its nested <target>, <property>, and <path> elements.

<project default="all">

<property name="a.property" value="a value"/>


<property name="b.property" value="b value"/>

<path id="a.path">
<pathelement location="${java.home}/jre/lib/rt.jar"/>
</path>

<target name="all">
<javac srcdir=".">
<classpath refid="a.path"/>
</javac>
</target>

</project>

Some notes about buildfiles to remember:


l All buildfiles require the <project> element and at least one <target> element.
l There is no default value for the <project> element's default attribute.
l Buildfiles do not have to be named build.xml. However, build.xml is the default name
for which Ant searches.
l You can have only one <project> element per buildfile.

1/25/2005 11
The Project

We call the set of tags and elements in an XML file from the root element — in this case
<project> — to the lowest-nested tag, the document object model (or DOM). The first
or root element of any buildfile is always the <project> tag. No buildfile can be
without one, nor can it have more than one. The DOM lays elements out in a tree-like
hierarchy, making the buildfile more of an object model than simply a plain process-
description document. The following example shows a valid project tag:

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


...
</project>

The <project> tag has three attributes: name, default, and basedir. The name
attribute gives the project a name. A project name is valuable for purposes of identifying
log output (to know what project you're building). For systems that manage buildfiles,
such as an IDE that can read buildfiles, the project name acts like an identifier for the
buildfile.

The default attribute refers to a target name within the buildfile. If you run Ant
without specifying a target on the command line, Ant executes the default target. If the
default target doesn't exist, Ant returns an error. While we do not recommend it, the value
of default does not have to be a valid target name (i.e., a name corresponding to an
actual target name in the buildfile).

We suggest either making the default target compile everything or display help for using
the buildfile. The basedir attribute defines the root directory of a project. Typically, it
is ".", the directory in which the buildfile resides, regardless of the directory you're in
when you run Ant. However, basedir can also define different points of reference. For
example, a buildfile that is part of a hierarchical project structure needs a different
reference point, referring to the project's root directory. You can use the basedir to
specify this point of reference.

Targets
Targets map directly to the broad goals set forth in a build's requirements specification.
For example, compiling the latest source code for the package org.jarkarta and placing it
into a JAR is a broad goal and, thus, would be a target in a buildfile. Targets consist of
tasks that do the actual work of accomplishing the target goal.

In general, it is better that targets are coarse-grained operations. Tasks solve fine-grained
goals better than targets.

Tasks
Tasks are the smallest building blocks of a buildfile and solve the more granular goals of
a build. They perform the actual work, compiling source code, packaging classes,
retrieving file revisions from CVS, or copying files and/or directories. Rather than

1/25/2005 12
provide a direct conduit to the underlying shell like some other build tools, Ant wraps all
operations into task definitions, each correlating to a Java object within Ant's object
model. There are no tasks in Ant that do not have a corresponding object. Contrast this to
shells that not only can run executable programs (a similar pattern to Ant's task objects),
but also have commands that do not correspond to executables — for example, the
Win32 shell's dir command. The "every task is an object" architecture provides Ant with
its flexible extensibility, which we discuss later in Chapter 5 and Chapter 6.

The following task example uses the copy task to copy all the files (and subdirectories)
from jsp in the project's www source directory to the jsp directory in the system's
WebLogic installation. The "/" path separator works in Windows and Unix, which is one
of Ant's benefits:

<copy
todir="${weblogic.dir}/${weblogic.server.home}/public_html/jsp">
<fileset dir="${src.www.dir}/jsp"/>
</copy>

Ant Core Task List


Core Tasks

Ant
AntCall
AntStructure
Apply/ExecOn
Available
Basename
BuildNumber
BUnzip2
BZip2
Checksum
Chmod
Concat
Condition
Supported conditions
Copy
Copydir
Copyfile
Cvs
CvsChangeLog
CvsVersion
CVSPass
CvsTagDiff

1/25/2005 13
Defaultexcludes
Delete
Deltree
Dependset
Dirname
Ear
Echo
Exec
Fail
Filter
FixCRLF
GenKey
Get
GUnzip
GZip
Import
Input
Jar
Java
Javac
Javadoc/Javadoc2
LoadFile
LoadProperties
Mail
MacroDef
Manifest
Mkdir
Move
Nice
Parallel
Patch
PathConvert
PreSetDef
Property
Record
Rename
Replace
Rmic
Sequential
SignJar
Sleep
Sql
Style
Subant
Sync
Tar

1/25/2005 14
Taskdef
Tempfile
Touch
TStamp
Typedef
Unjar
Untar
Unwar
Unzip
Uptodate
Waitfor
War
WhichResource
XmlProperty
Xslt
Zip

1/25/2005 15

You might also like