Ant

From HaFrWiki
Jump to: navigation, search

Introduction

Apache ANT (Another Neat Tool) is a Java-based build tool. In theory, it is like Make, in practice better.


Programming

ANT is different. Instead of a model where it is extended with shell-based commands, Ant is extended using Java classes. Instead of writing shell commands, the configuration files are XML-based, calling out a target tree where various tasks get executed. Each task is run by an object that implements a particular Task interface.
A very simple example ANT Build File.

Install ANT

To use Ant you need:

  1. Java.
    Java is free and can be found at the Sun Website: The Source for Java Developers.
  2. ANT.
    Ant is free and can be found at the Apache Website: Ant Apache. Follow the instruction of the ANT Installation.

Example of setting the environment variables (Windows):

Environment Variable Description Example
JAVA_HOME Directory where Java is installed JAVA_HOME=C:\Program Files\Java\jdk1.5.0_02
ANT_HOME Directory where Ant is installed ANT_HOME=C:\Java\apache-ant-1.6.3
PATH Add both environment vars binaries to your PATH PATH=%JAVA_HOME%\bin;%ANT_HOME%\bin;%PATH%

Check the Java and Ant installation

Command-Line-Prompt
Ant and Java Test output

It is essential to check the correct installation of Java and Ant. To start the check (for Windows) goto a command-line-prompt. If you don't know how to get a command-line-prompt:

   Start -> Run

Type cmd in the Open text box.
A Command-Line-Window opens.


Java

Type the command:

  java -version

Ant

Type the command:

  ant -version

Tips & Tricks

Properties

Like the Unix/C++ make utility, it is important to know how property variables are threated in Ant. The hierarchy is:

Hier Where How Description
1 ant build xml-file <property name="prop" value="xx" /> Normal definition of a property.
2 ant build prop file prop = xx1 Normal defintion in a property file
3 ant command line -Dprop=xx2 Re-definition of a property.

The highest Hierarchy number will overrule the setting.

Ant example

A template for making it easier to create ANT scripts has been developed, documentation has to be finished. But take a look at:

  • Ant template, splitting the development of scripts into generic, local and end-user parts.
  • Ant copy-sync, will be the description of the use of the template for copy-sync. The documentation is not finished yet. It will give you an idea for copy an synchronize hard disk using fileset (id's and filter versions). This script totaly flexible for the end-user.


Ant Tasks

Ant implements since version 1.8 the following tasks:

ABC

Task Description
Ant Runs Apache Ant on a supplied buildfile. This can be used to build subprojects.
This task must not be used outside of a target if it invokes the same build file it is part of.
AntCall Call another target within the same buildfile optionally specifying some properties (params in this context). This task must not be used outside of a target.
ANTLR Invokes the ANTLR Translator generator on a grammar file.
AntStructure Generates an DTD for Apache Ant buildfiles which contains information about all tasks currently known to Ant.
AntVersion Stores the Apache Ant version (when used as task) or checks for a specific Ant version (when used as condition). Since Ant 1.7.0
Apply/ExecOn Executes a system command. When the os attribute is specified, then the command is only executed when Apache Ant is run on one of the specified operating systems.
Apt Runs the annotation processor tool (apt), and then optionally compiles the original code, and any generated source code.
Attrib Changes the attributes of a file or all files inside specified directories.
Augment Modify an existing reference by adding nested elements or (re-)assigning properties mapped as XML attributes.
Available Sets a property if a resource is available at runtime.
This resource can be a file, a directory, a class in the classpath, or a JVM system resource.
Basename Determines the basename of a specified file, optionally minus a specified suffix.
Bindtargets Make some target the extension of some defined extension point.
It will make the list of targets dependencies of the extension point.
BuildNumber Basic task that can be used to track build numbers.
BUnzip2 Expands a resource packed using GZip or BZip2.
BZip2 Packs a resource using the GZip or BZip2 algorithm.
The output file is only generated if it doesn't exist or the source resource is newer.
Cab The cab task creates Microsoft cab archive files.
Continuus/Synergy Tasks Wrappers around Continuus Source Manager.
They have been tested against versions 5.1/6.2 on Windows 2000, but should work on other platforms with ccm installed. Implemented are : CCMCheckin, CCMCheckout, CCMCheckinTask, CCMReconfigure, CCMCreateTask.
CvsChangeLog Generates an XML-formatted report file of the change logs recorded in a CVS repository.
Checksum Generates checksum for files. This task can also be used to perform checksum verifications.
Chgrp Changes the group of a file or all files inside specified directories.
Right now it has effect only under Unix.
The group attribute is equivalent to the corresponding argument for the chgrp command.
Chmod Changes the permissions of a file or all files inside specified directories.
Right now it has effect only under Unix or NonStop Kernel (Tandem).
The permissions are also UNIX style, like the argument for the chmod command.
Chown Changes the owner of a file or all files inside specified directories.
Right now it has effect only under Unix.
The owner attribute is equivalent to the corresponding argument for the chown command.
Clearcase Tasks IBM/Rational ClearCase implementation.
Componentdef Adds a component definition to the current project.
Concat Concatenates one or more resources to a single file or to the console.
The destination file will be created if it does not exist unless the resource list is empty and ignoreempty is true.
Condition Sets a property if a certain condition holds true - this is a generalization of Available and Uptodate.
Supported conditions Conditions are nested elements of the <condition> and <waitfor> tasks.
There are core conditions and custom conditions.
Custom conditions are described in Custom Conditions.
Copy Copies a file or resource collection to a new file or directory.
By default, files are only copied if the source file is newer than the destination file, or when the destination file does not exist.
However, you can explicitly overwrite files with the overwrite attribute.
Copydir Copies a directory tree from the source to the destination.
Copyfile Deprecated, use Copy.
Cvs Handles packages/modules retrieved from a CVS repository.
CVSPass Adds entries to a .cvspass file. Adding entries to this file has the same affect as a cvs login command.
CvsTagDiff Generates an XML-formatted report file of the changes between two tags or dates recorded in a CVS repository.
CvsVersion Retrieves the CVS client and server version.

DEF

Task Description
Defaultexcludes Alters the default excludes for all subsequent processing in the build, and prints out the current default excludes if desired.
Delete Deletes a single file, a specified directory and all its files and subdirectories, or a set of files specified by one or more resource collections.
Deltree Deprecated use Delete instead.
Depend Manages Java Class dependencies.
The depend task works by determining which classes are out of date with respect to their source and then removing the class files of any other classes which depend on the out-of-date classes.
Dependset Manages arbitrary dependencies between resources.
Diagnostics Runs Apache Ant's -diagnostics code inside Ant itself.
This is good for debugging Ant's configuration under an IDE.
Dirname Determines the directory path of a specified file.
Ear Extension of the Jar task with special treatment for files that should end up in an Enterprise Application archive.
Echo Echoes a message to the current loggers and listeners which means System.out unless overridden.
Echoproperties Displays all the current properties (or a subset of them specified by a nested <propertyset>) in the project.
EchoXML Echoes nested XML to the console or a file.
EJB Tasks Enterprise Java Beans (EJB) implementation.
Exec Executes a system command.
Fail Exits the current build (just throwing a BuildException), optionally printing additional information.
Filter Sets a token filter for this project or read multiple token filter from an input file and sets these as filters.
Token filters are used by all tasks that perform file copying operations through the Project commodity methods.
FixCRLF Adjusts a text file to local conventions.
FTP Implements a basic FTP client that can send, receive, list, delete files, and create directories.

GHI

Task Description
GenKey Generates a key in a keystore.
Get Gets files from URLs.
GUnzip Expands a resource packed using GZip or BZip2
GZip Packs a resource using the GZip or BZip2 algorithm. The output file is only generated if it doesn't exist or the source resource is newer.
Hostinfo Sets the NAME, DOMAIN, ADDR4, and ADDR6 properties in the current project.
Image Applies a chain of image operations on a set of files.
Requires Java Advanced Image API from Sun.
Import Imports another build file into the current project.
Include Include another build file into the current project. (Since Apache Ant 1.8.0)
Input Allows user interaction during the build process by prompting for input.
To do so, it uses the configured InputHandler.

JKL

Task Description
Jar JAR-file implementation.
Jarlib-available Checks whether an extension is present in a fileset or an extensionSet (ZIP-JAR).
If the extension is present then a property is set.
Jarlib-display Displays the "Optional Package" and "Package Specification" information contained within the specified jars.
Jarlib-manifest Generates a manifest that declares all the dependencies in manifest.
The dependencies are determined by looking in the specified path and searching for Extension / "Optional Package" specifications in the manifests of the jars.
Jarlib-resolve Tries to locate a jar to satisfy an extension and place location of jar into property.
Java Executes a Java class within the running (Apache Ant) VM or forks another VM if specified.
Javac Compiles a Java source tree.
JavaCC Invokes the JavaCC compiler compiler on a grammar file.
Javadoc/Javadoc2 Generates code documentation using the javadoc tool.
Javah Generates JNI headers from a Java class.
When this task executes, it will generate the C header and source files that are needed to implement native methods.
JDepend Invokes the JDepend parser.
This parser "traverses a set of Java source file directories and generates design quality metrics for each Java package". It allows to "automatically measure the quality of a design in terms of its extensibility, reusability, and maintainability to effectively manage and control package dependencies."
JJDoc Invokes the JJDoc preprocessor for the JavaCC compiler compiler.
It takes a JavaCC parser specification and produces documentation for the BNF grammar. It can operate in three modes, determined by command line options.
JJTree Invokes the JJTree preprocessor for the JavaCC compiler compiler. It inserts parse tree building actions at various places in the JavaCC source that it generates. The output of JJTree is run through JavaCC to create the parser
Jlink Deprecated use zipfileset or zipgroupfileset instead
JspC Dprecated.
Apache Ant task to run the JSP compiler and turn JSP pages into Java source.
JUnit Runs tests from the JUnit testing framework.
JUnitReport Merges the individual XML files generated by the JUnit task and eventually apply a stylesheet on the resulting merged document to provide a browsable report of the testcases results.
Length Displays or sets a property containing length information for a string, a file, or one or more nested Resource Collections.
LoadFile Specialization of loadresource that works on files exclusively and provides a srcFile attribute for convenience.
LoadProperties Loads a file's contents as Apache Ant properties.
LoadResource Loads a text resource into a single property.
Local Adds a local property to the current scope.

MNO

Task Description
MacroDef Defines a new task using a <sequential> nested task as a template.
Mail Sends a SMTP email.
MakeURL Takes one or more filenames and turns them into URLs, which it then assigns to a property.
Useful when setting up RMI or JNLP codebases, for example. Nested filesets are supported; if present, these are turned into the URLs with the supplied separator between them (default: space).
Manifest Creates a manifest file.
ManifestClassPath Converts a Path into a property whose value is appropriate for a Manifest's Class-Path attribute
MimeMail Deprecated use mail.
Mkdir Creates a directory.
Move Moves a file to a new file or directory, or collections of files to a new directory
Native2Ascii Converts files from native encodings to ASCII with escaped Unicode.
NetRexxC Compiles a NetRexx source tree within the running (Apache Ant) VM.
Nice Provide "nice-ness" to the current thread and/or query the current value.

PQRS

Task Description
Parallel Executes nested tasks in parallel with no guarantees of thread safety.
Every task will run in its own thread, with the likelihood of concurrency problems scaling with the number of CPUs on the host system.
Patch Applies a diff file to original(s) files. Requires "patch" to be on the execution path.
PathConvert Converts nested ResourceCollections, or a reference to just one, into a path form for a particular platform, optionally storing the result into a given property
tasks.html Perforce Tasks Provides an interface to the Perforce SCM.
PreSetDef Generates a new definition based on a current definition with some attributes or elements preset
ProjectHelper Provided for the purpose of allowing the user to install a different ProjectHelper at runtime.
Property Sets a property (by name and value), or set of properties (from file or resource) in the project. Properties are case sensitive.
PropertyFile Provides an optional task for editing property files.
This is very useful when wanting to make unattended modifications to configuration files for application servers and applications. Currently, the task maintains a working property file with the ability to add properties or make changes to existing ones. Since Ant 1.8.0 comments and layout of the original properties file are preserved.
PropertyHelper Provided for the purpose of allowing the user to (a) install a different PropertyHelper at runtime, or (b) (hopefully more often) install one or more.
Pvcs Provides interface for PVCS.
Record A recorder is a listener to the current build process that records the output to a file.
Rename Deprecated. Use move instead.
RenameExtensions Deprecated. Use move with a glob mapper instead.
Replace Replace is a directory based task for replacing the occurrence of a given string with another string in selected file.
ReplaceRegExp ReplaceRegExp is a directory based task for replacing the occurrence of a given regular expression with a substitution pattern in a selected file or set of files.
ResourceCount Displays or sets a property containing the size of a nested Resource Collection.
Retry Retry is a container which executes a single nested task until either: there is no failure; or: its retrycount has been exceeded.
RExec Automates a remote rexec session. Just like the Telnet task, it uses nested <read> to indicate strings to wait for, and <write> tags to specify text to send to the remote process.
Rmic Runs the rmic compiler for a certain class.
Rpm Invokes the rpm executable to build a RedHat Package Manager Linux installation file.
The task currently only works on Linux or other Unix platforms with rpm support.
SchemaValidate Validates XML files described by an XML Schema. The task extends the XmlValidate task with XSD-specific features.
Scp Copies a file or FileSet to or from a (remote) machine running an SSH daemon (Secure Copy.
FileSet only works for copying files from the local machine to a remote machine.
Script Executes a script in a Apache BSF or JSR 223 supported language.
Depends on external libraries not included in the Apache Ant distribution. See Library Dependencies for more information
Scriptdef Scriptdef can be used to define an Apache Ant task using a scripting language.
Sequential Sequential is a container task - it can contain other Apache Ant tasks. The nested tasks are simply executed in sequence. Sequential's primary use is to support the sequential execution of a subset of tasks within the parallel task.
ServerDeploy Runs a "hot" deployment tool for vendor-specific J2EE server.
The task requires nested elements which define the attributes of the vendor-specific deployment tool being executed. Vendor-specific deployment tools elements may enforce rules for which attributes are required, depending on the tool.
Setproxy Sets Java's web proxy properties, so that tasks and code run in the same JVM can have through-the-firewall access to remote web sites, and remote ftp sites.
SignJar Signs JAR files with the jarsigner command line tool.
Sleep Sleeps for a short period of time, useful when a build or deployment process requires an interval between tasks.
SourceOffSite Provides an interface to the Microsoft Visual SourceSafe SCM via SourceGear's SourceOffSite product. (VCSS)
Sound Plays a sound-file at the end of the build, according to whether the build failed or succeeded.
Splash Creates a splash screen. The splash screen is displayed for the duration of the build and includes a handy progress bar as well.
Sql Executes a series of SQL statements via JDBC to a database.
Statements can either be read in from a text file using the src attribute or from between the enclosing SQL tags.
Sshexec Runs a command on a remote machine running SSH daemon.
Sshsession Establishes an SSH connection with a remote machine running SSH daemon, optionally establishes any number of local or remote tunnels over that connection, then executes any nested tasks before taking down the connection.
Subant Calls a given target for all defined sub-builds.
Symlink Manages symbolic links on Unix based platforms. Can be used to make an individual link, delete a link, create multiple links from properties files, or create properties files describing links in the specified directories. Existing links are not overwritten by default.
Sync Synchronizes a target directory from the files defined in one or more Resource Collections.
This is not what I think sync should be!

TUV

Task Description
Tar Creates a tar archive.
Taskdef Adds a task definition to the current project, such that this new task can be used in the current project.
Telnet Task to automate a remote telnet session
Tempfile Sets a property to the name of a temporary file. Unlike java.io.File.createTempFile, this task does not actually create the temporary file, but it does guarantee that the file did not exist when the task was executed.
Touch Changes the modification time of a resource and possibly creates it at the same time.
Translate Identifies keys in files delimited by special tokens and translates them with values read from resource bundles.
Truncate Sets the length of one or more files, as the intermittently available truncate Unix utility/function
TStamp Sets the DSTAMP, TSTAMP, and TODAY properties in the current project. By default, the DSTAMP property is in the format "yyyyMMdd", TSTAMP is in the format "hhmm", and TODAY is in the format "MMMM dd yyyy". Use the nested <format> element to specify a different format.
Typedef Adds a task or a data type definition to the current project such that this new type or task can be used in the current project.
Unjar Unzips a zip-, war-, or jar file.
Untar Unzips a zip-, war-, or jar file.
Unwar Unzips a zip-, war-, or jar file.
Unzip Unzips a zip-, war-, or jar file.
Uptodate Sets a property if a target file or set of target files is more up-to-date than a source file or set of source files.
Visual SourceSafe Implementation of Miscrosoft Viusal Source Safe.

WXYZ

Task Description
Waitfor Blocks execution until a set of specified conditions become true.
War Extension of the Jar task with special treatment for files that should end up in the WEB-INF/lib, WEB-INF/classes or WEB-INF directories of the Web Application Archive.
WhichResource Finds a class or resource on the supplied classpath, or the system classpath if none is supplied.
The named property is set if the item can be found.
Weblogic JSP Compiler Precompiles JSP's using weblogic's jsp compiler (weblogic.jspc)
XmlProperty Loads property values from a well-formed xml file.
XmlValidate Checks that XML files are valid (or only well formed).
XSLT/Style Process a set of documents via XSLT.
This is useful for building views of XML based documentation, or for generating code.
Zip Creates a zipfile.

See also

  • Apache Ant Home page, The mother of Ant.
  • Sourceforge Ant-Contrib, The Ant-Contrib project is a collection of tasks (and at one point maybe types and other tools) for Apache Ant. The Ant-Contrib tasks are very useful. I would say don't use ant without the power of Ant-Contrib. The template I have created depends on the task of Ant-Contrib.
    The Software is distributed under the Apache Software License.

If you like Ant you may be like Maven too.

Examples

Books