Professional Documents
Culture Documents
com
CONTENTS INCLUDE:
n
About Apache Ant Getting Started with
Apache Ant
n
Anatomy of an Ant Script
n
Core Java Related Tasks
n
Infrastructure Tasks
n
SCM Related Tasks
n
Hot Tips and more...
By James Sugrue
Attribute Description Required
ABOUT APACHE ANT
name The name and identifier of this target Yes
Apache Ant is an XML based tool for automating software depends Comma separated list of other targets that this No
build processes. Starting out as part of the Apache Tomcat target depends on
codebase, Ant got its first standalone release in July 2000. if The name of a property which must be set for No
Today it is the most widely used build tool for Java projects, this target to run
enabling developers to adopt agile principles: most unless The name of a property which must not be set No
importantly test-driven development. for this target to run
You can download the latest Ant distribution (1.8.1) extensionOf Add the target to the depends list of the No
Hot as a standalone tool from http://Ant.apache.org/. Ant named extension point
Tip is also built into most Java development IDEs, such Table 2: Target element attributes
as Eclipse, and NetBeans which uses it as its internal
build system. Extension Points
Introduced in Ant 1.8.0 <extension-point> is similar
www.dzone.com
The Anatomy of an Ant Script Hot to a <target> with its name and depends attributes.
A typical Ant script consists of a single build.xml file. The Tip However, it does not contain any tasks and is used
root element of the build script is the project tag. Within the to collect targets that contribute to a state in the
project element there are one or more targets specified. A
dependency relationships of the script.
target contains a set of tasks to be executed.
file Location of the properties file When Core Java Related Tasks
not using This section gives a complete reference of all taks and their
the name attributes that are most commonly used by Java Developers.
resource Location in the classpath of the properties file
attribute
(i.e. loading Compiling Java Code
url URL pointing to properties file external
properties)
Compilation is achieved with the <javac> task.
basedir The basedir to calculate the relative path from No. Default Attribute Description
is project
srcdir Location of java files to compile
basedir
classpath / The classpath to use when looking up a No bootclasspath/ Location of bootstrap class files or reference to a
classpathref resource boothclasspathref predefined path
environment Prefix to use when accessing environment No classpath/ classpathref Classpath to use for compilation or reference to a
variables predefined path
prefix Prefix to apply to properties loaded using file, No compiler Compiler implementation to use. Default is current VM
resource or url
debug Whether source should be compiled with debug
Table 3: Property element attributes information (-g parameter). Defaults to off
All system properties that can be accessed from the System. debuglevel Can be lines, var or source. Used in the –g parameter
for the compiler
getProperties() methods in Java can be used in Ant.
Additionally, the following built-in properties are available: depend Enables dependency tracking on jikes and classic
compilers
Property Name Description deprecation Whether source should compile with deprecation
basedir Absolute path of projects basedir information
ant.core.lib Absolute path of the ant.jar file destdir Destination for compiled .class files
ant.file Absolute path of buildfile encoding Encoding of source files
ant.home Home directory of Ant errorProperty Property to set to true if compilation fails
ant.java.version Java version detected excludes Comma separated list of files that must be excluded
ant.project.default-target Name of the default target from compilation. Wildcard patterns can be used
ant.project.invoked-targets List of targets specified in the command line when excludesFile File that contains the exclusion list
invoking this project executable Path to javac executable to use when fork set to yes
ant.project.name Name of the project that is running extdirs Location of installed extensions
ant.version Version of Ant fork Whether to execute javac using the JDK compiler
externally. Default no
Table 4: Built-in properties
failonerror Whether compilation error fails the build. Default true
Path Structures
includes Comma separated list of files that must be included in
Path structures can be created using a series of <pathelement> compilation. Wildcard patterns can be used
tags. For example, a classpath can be created using:
includeAntRuntime Whether to include ANT runtime libraries in the
classpath. Default yes
<classpath>
<pathelement location=”/path/jarfile.jar”/> includeDestClasses Whether classes compiled to the dest directory are
<pathelement path=”/path/lib/jar1.jar;/path/lib/jar2.jar”/>
</classpath> included in the classpath. Default true. When false,
causes recompilation of dependent classes
Table 5: Fileset attributes tempdir Temporary file location if fork set to yes
updatedProperty Property to set for successful compilation
Built-in Tasks
verbose Use verbose output on the compiler
The following sections list out the most commonly used tasks
in Ant build scripts. Required attributes are marked in bold. Table 6: javac tasks properties
Additional command line arguments can be passed through to indexMetaInf Whether to include META-INF in the index.
the compiler using the <compilerarg> nested element. Default false
level Compression level for files from 0 (none) to 9
Compiler Choice (maximum)
To use different compilers set the build.compiler
Hot property to classic (1.1, 1.2) modern (1.3-1.6) or
manifest Location of manifest for jar
Tip choose a separate compiler such as jikes, jvc, kjc, manifestencoding Encoding to use for manifest. Default is platform
encoding
gcj or sj.
mergeClassPathAttributes Merge classpath attributes of different manifests
when merging
Class file dependencies can be managed using the
preserve0permissions If a file has permissions value of 0, it will preserve
<depend> task. this instead of applying default values
includesfile The name of a file that defines an include pattern Attribute Description
file Manifest file to create or update
index Whether to create an index list to speed up
classloading. Default false encoding Encoding to read existing manifest
flattenAttributes Merge attributes occurring more than once in a public Show only public classes and members
section into one single attribute
protected Show only protected/public classes and members
mergeClassPathAttributes Merge classpath attributes of different manifests
package Show only package/protected/public classes and
when merging
members
mode Either update or replace (default)
private Show all classes and members
Table 10: Manifest task properties serialwarn Warn about @serial tag
source Source level used for compilation
Generating Documentation
JavaDoc generation is done through the <javadoc> task. splitindex Split index into one file per letter
stylesheetfile Specifies CSS stylesheet
Attribute Description
use Create class and package usage pages
sourcepath Location of the source files for the task. At least one
sourcepathref of these attributes required for this specification verbose Output all messages of javadoc process
sourcefiles version Include @version parts
destdir Destination directory required unless a doclet is windowtitle Browser window title for documentation
specified
Table 11: JavaDoc task properties
access Access mode (public, private, protected, package)
additionalparam Additional parameters to pass through Executing Java Classes
author Include @author parts Java classes can be executed from Ant using the <java> task.
bootclasspath / Location of class files loaded by bootstrap class Attribute Description
bootclasspathref loader
classname The jar file or classname to execute. If using jar, fork must be
bottom Bottom text for each page jar set to true
breakiterator Use new breakiterator algorithm append Whether output/error files should be appended or overwritten
charset Charset for cross platform viewing
args Arguments for class. Better to use nested <arg> elements
classpath/classpathref Location of classpath
classpath / Classpath to use for execution
defaultexcludes Whether default excludes should be used classpathref
docencoding Encoding of output file clonevm Clones system properties and bootclasspath of forked VM to
be the same as the Ant VM
docfilessubdirs Deep copy of doc-file subdirectories
dir Directory to invoke VM in
doclet/docletpathref Classfile that starts to doclet used
error File to write error (System.err) output to
doctitle Title for the package index page
errorproperty Property to store error output from command
encoding Source file encoding
failonerror Stops Ant build process if failure occurs
excludepackagenames Packages to exclude from javadoc
fork Executes the class in another VM
executable Specify a javadoc executable instead of VM default
input File where standard input is taken from
extdirs Location of installed extensions
inputstring String where standard input is taken from
failonerror Stops build process if command fails
jvm Command used to invoke JVM. Default is java
footer Footer text for each page
javmargs Arguments for forked JVM. Better to use nested <jvmarg>
group Group specified packages together in overview
page logError Shows error output in Ant log
header Header text for each page maxmemory Maximum memory to allocate to the forked VM
helpfile Specifies help file to include newenvironment When fork=true, do not propogate current environment
variables
includenosourcepackages When true includes packages with no source
output File to write output to
link Create links to javadoc output at given url
outputproperty Property to store output of the command
linksource Generate links to source files
locale Locale to be used resultproperty Property where return code of command is stored
maxmemory Maximum amount of memory to allocate in VM spawn Need fork set to true. Will spawn a process independent of
calling Ant process
nodeprecated Do not include @deprecated information
timeout Timeout for the command to execute within before being
nodeprecatedlist Do not generate deprecated list stopped
notree Do not generate class hierarchy
Table 12: Java task properties
noindex Do not generate index
nohelp Do not generate help link Running Unit Tests
JUnit tests are executed from Ant through the <junit> task
nonavbar Do not generate naviation bar
noqualifier Enables –noqualifier argument for a list of packages Attribute Description
(or all) clonevm Clones system properties and bootclasspath of forked VM
overview Read overview documentation from HTML file to be the same as the Ant VM
packagenames List of package files to use dir Directory from which to invoke the VM
packageList File containing packages to use errorproperty Property to set when errors occur
failureproperty Property to set when failure occurs unless Use formatter if property is not set
filtertrace Filter out JUnit or Ant stack frames from stack traces in usefile If output should be sent to a file. Default true
errors or failures
Table 15: JUnit formatter definition
fork Run JUnit in a separate VM
forkmode How many VMs to create when forking tests. (preTest, Once tests are completed, reports can be generated for the
perBatch or once) tests using the <junitreport> task.
haltonerror Stop build process if an error happens
Attribute Description
haltonfailure Stops build process if a test fails
todir The directory that will contain the results
includeAntruntime Stops build process if a test fails
tofile The name of the XML file that will aggregate all previously
jvm Command used to invoke VM, default java generated results
logfailedtests Log a FAILED message for each failed test to Ant’s logging
system Table 16: JUnitReport task properties
maxmemory Maximum memory to allocate to forked VM The <junitreport> task contains a fileset that collects all the
newenvironment When fork=true, do not propogate current environment reports from previous Junit tests.
variables
To output to a report file, use the internal <report> tag.
outputformatters Send output generated by tests to test formatters
printsummary Print statistics for each test case. (on, off, withOutAndErr) Attribute Description
reloading Whether a new classloader should be instAntiated for each format Format of report (frames or noframes)
test styledir Directory containing stylesheets. Files must be junit-frames.xsl
showoutput Send output to Ant log or junit-noframes.xsl
tempdir Location for temporary files todir The directory that files are written to. By default this is the
current directory
timeout Cancel tests if not complete in specified time
Table 17: Report tag for <junitreport>
Table 13: JUnit task properties
Infrastructure Tasks
Tests are defined in nested elements within the <junit> task.
There are a number of other core tasks related to file
Batch tests are defined using the <batchtest> tag:
operations. The following is an overview of these tasks:
Attribute Description
Task Description
name Name of test class
attrib /chmod Changes permission of a file (attrib for Windows, chmod for
errorproperty Property to set when errors occur Unix)
failureproperty Property to set when failure occurs checksum Generates a checksum for files
filtertrace Filter out JUnit or Ant stack frames from stack traces in errors concat Concatenates multiple files into one single file, or to the console
or failures
copy Copies a file, or collection of files, to another location
fork Run tests in a separate VM, overriding the value set in the
<junit> task delete Deletes a file, directory or collection of files
haltonerror Stop build process if an error happens exec Executes a system command
haltonfailure Stops build process if a test fails Provides basic FTP functionality
ftp
if Property condition to run test against, if set
get Gets a file from a URL
todir Directory to write reports to
import / Imports or includes another build file into the current Ant script
unless Property condition to run test against, if not set include
Table 14: JUnit batch test definition mail Sends mail over SMTP
mkdir Creates a new directory
Hot If you just need to run a single test, the <test> tag record Listens to the build process and outputs to a file
Tip can be used to specify the test. This contains similar replace Replaces occurances of a string in file or collection of files
attributes to the <batchtest> tag. replaceregexp Replaces occurances of a string in file or collection of files using
regular expressions
Test results can be written to different formats, using the sql Executes SQL statements to a database using JDBC
outputformatters attribute in the <junit> task. The following Synchronizes a target directory with a list of files
sync
table shows the options for formatter definition:
zip / unzip Creates a zip file / unzips an existing zip. Also provides
Attribute Description tar / untar functionality for tar files
type A predefined formatter type of either xml, plain, brief or failure Table 18: Overview of basic infrastructure tasks
classname If no type specified, use a customer formatter implementing
org.apache.tools.Ant.taskdefs.optional.junit SCM Related Tasks
.JUnitResultFormatter ANT provides a number of tasks for connecting with different
source control management systems. The core support deals
if Use formatter if property is set
with CVS.
cvsversion Retrieves CVS client and server version makeurl Converts filenames into URLs
patch Applies a diff file to originals pathconvert Converts a file list or path structure to a separated string for
the target platform
Table 19: CVS task properties
property Set a property
There are also tasks available for interfacing with ClearCase, propertyfile Creation and modification of property files
Visual Source Safe, Pvcs, Perforce and Continuus. Additional
uptodate Set property if specified target file is newer than source files
tasks can be found online for DCVS systems such as Git and
Mercurial. whichresource Find class or resource
xmlproperty Loads properties from property file written in XML
Property Tasks
Ant provides some tasks that deal with managing properties Table 20: Ant Property Tasks
throughout your build process.
Writing Your Own Tasks
Task Description
available Sets property if file, directory or class in classpath is available
Hot If Ant doesn’t provide you with the functionality that
at runtime
Tip you need, you can write your own Ant tasks in Java
by extending org.apache.tools.ant.Task.
basename Sets property to last element of specified path
#82
CONTENTS INCLUDE:
■
■
About Cloud Computing
Usage Scenarios Getting Started with
Aldon Cloud#64Computing
■
Underlying Concepts
Cost
by...
■
Upcoming Refcardz
youTechnologies ®
■
Data
t toTier
brough Comply.
borate.
Platform Management and more...
■
Chan
ge. Colla By Daniel Rubio
tion:
dz. com
tegra ternvasll
ABOUT CLOUD COMPUTING one time events. TEN TS
INC ■
HTML LUD E:
us Ind Anti-PPaat
Basics
Automated growthHTM
ref car
nuorn
■
Valid
ation one time events, cloud ML
connected to what is now deemed the ‘cloud’. Having the capability to support
Apache Ant
Usef
Du
ti
■
ul M.
computing platforms alsoulfacilitate
#84
Open the gradual growth curves
n an
Page Source
o
■
s
Vis it
C
faced by web applications. Tools
Core
By Key ■
Elem
Patte
has changed substantially in recent years, especially with Structur
E: al Elem ents
INC LUD gration the entrance of service providers like Amazon, Google and Large scale growth scenarios involvingents
specialized
NTS and mor equipment
rdz !
HTML
CO NTE Microsoft. es e... away by
(e.g. load balancers and clusters) are all but abstracted
Continu at Every e chang
m
About ns to isolat
relying on a cloud computing platform’s technology.
Software i-patter
space
Hadoop
rdz .co
■
n
Re fca
e Work
Build
riptio
and Ant
Desc
These companies have a Privat
are in long deployed
trol repos
itory
webmana applications
ge HTM
L BAS
■
Build
re
Buil Repo
This Refcard active
will introduce are within
to you to cloud riente computing, with an
d units
RATION etc. Some platforms ram support large grapRDBMS deployments.
■
The src
dy Ha
softw
e ine loping and Java s written in hical on of
INTEG attribute
task-o it all
softwar emphasis onDeve es by
Mainl these
ines providers, so youComm can better understand
also rece JavaScri user interfac web develop and the rris
Vis it
Spring Security
codel chang desc
INUOU ding Task Level as the
e code
w ww.dzone.com
Label
Build
manu
al
d tool
depe deplo t need but as if
eve , a ) stalle the same nmen for stan overlap uen
(i.e. , inef Build t, use target enviro Amazon EC2: Industry standard it has
software and uagvirtualization ine. HTM , so <a>< tly are) nest
with terns problem ce pre-in whether dards
ated b></
ory. ns (i.e. Autom Redu ymen
has bec become e with a> is
via pat ticular d deploEAR) in each very little L
Subversion
reposit -patter s that Pay only cieswhat you consume
tagge or Amazon’s cloud
the curr you cho platform
computing isome
heavily based moron fine. b></ ed insid
lained ) and anti the par solution duce nden For each (e.g. WAR es t
ent stan ose to writ more e imp a></ e
not lega each othe
x” b> is
be exp text to “fi are al Depeapplication deployment
Web ge until t a
librarifew years agonmen
t enviro was similar that will softwaredard
industry standard and virtualization app
e HTM technology.
orta nt,
tterns to pro Minim packa nden
Mo re
CI can ticular con used can rity all depe all targe
s will L or XHT arent. Reg the HTM l, but r. Tags
etimes Anti-pa they
tend
es, but to most phone services:
y Integ alizeplans with le that
late fialloted resources, ts with an and XHT simplify all help ML, und ardless
L VS
XHTM <a><
in a par hes som
Centr
end,
Binar
pro cess. the practic enti ng incurred costgeme
nt
whether e a single
such
temp
resources on
were consumed
t enviro
nmen
orthenot. Virtualization MLaare your
othe
you prov
erst of L
b></
in muchallows physical piece of hardware to
ide be HTM
rily bad
Mana based
approac ed with the cial, but, implem anding
Creat targe es to actually r web
nden
cy rties are nt
of the a solid L has
into differe coding.resources
necessa pared to
chang
efi Depe prope itting utilized by multiple operating
function systems.simplerThis allows foundati job adm been arou
associat to be ben
er
Ge t
te builds commo
are not Fortuna
late Verifi e comm than on
n com Cloud computing asRun it’sremo
known etoday has changed this.
befor alitytohas irably, nd for
They they
etc.
Temp Build (e.g. bandwidth, n memory, CPU) be allocated exclusively to tely exp that som
lts whe
ually,
appear effects. Privat y, contin Every elem mov used
to be, HTML
ecte job e time
ed resu The various resourcesPerfo rm a
consumed by webperio applications
dicall (e.g. nt team
pag
individual operating entsinstances. ed to CSS
system Brow d. Earl
y HTM has expand . Whi
gration
opme because
adverse unintend d Builds sitory Build r to devel common e (HTML . ser ed far le it has don
ous Inte web dev manufacture L had very
Stage Repo
e bandwidth, memory, CPU) areIntegtallied
ration on a per-unit CI serve basis or XHT
produc tinu e Build rm an from
extensio .) All are more e its
e.com
DZone, Inc.
Cloud Computing
the
s on
expand
ISBN-13: 978-1-934238-75-2
140 Preston Executive Dr. ISBN-10: 1-934238-75-9
Suite 100
50795
Cary, NC 27513