Вы находитесь на странице: 1из 15

How to work with Ant (Another Neat Tool)

Project Details:

• Projects involved :- Telstra OSCA (Online Services Customer Access)


• H/W Platform: Windows XP as well as Sun Solaris9
• S/W Environment: Java Technologies (JDK1.5.0_01-b08,Sun Java System
Application Server 8.1 2005Q1, Sun Java System Web Server 6.1 2005Q1
SP4 , Apache Ant 1.6.5 and Oracle 10G)
• Appln. Type: Web based Application using Java Technology.
• Project Type: - OSCA (Online Services Customer Access System) was
developed as an interface that sales consultants and other Telstra staff will
use to provide support for customers using the online services of Telstra
Corporation. It was in the maintenance phase when I worked

Table of Contents

1. Introduction to ANT (Another Neat Tool)..................................................3


1.1 What is Ant?...........................................................................................3
1.2 Features of Ant.......................................................................................3
1.3 The differences between Ant and Make......................................................3
2. Prerequisites.............................................................................................3
3. Installation of Ant.....................................................................................4
4. How to run Ant?........................................................................................4
4.1 Running ant scripts with a file other build.xml file.........................................4
4.2 Saving the output after running the Ant script.............................................5
4.3 Running the Ant script partially..................................................................5
5. Structure of the Ant build script................................................................5
5.1 Project....................................................................................................6
5.2 Targets...................................................................................................6
5.3 Property..................................................................................................7
5.4 Tasks......................................................................................................8
6. Writing of the Ant build script...................................................................8
General Steps to create a build for J2EE application...........................................8
6.1 Create directory.......................................................................................8
Example and explanation................................................................................9
6.2 Compile the java files.............................................................................9
Example and explanation................................................................................9
6.3 Create the jar files.................................................................................10
Example and explanation..............................................................................10
6.4 Copy file(s)..........................................................................................11
Example and explanation..............................................................................11
6.5 Create Enterprise Archive (.ear) file........................................................12
Example and explanation..............................................................................12
6.6 Create Web Application Archive (.war) file...............................................13
Example and explanation..............................................................................13
6.7 Delete a directory or set of files..............................................................13
Example and explanation..............................................................................14
7. Other tasks............................................................................................14
7.1 Run an application..................................................................................14
Example and explanation..............................................................................15
7.2 Print a message.....................................................................................15
Example and explanation..............................................................................15
7.3 Documentation.......................................................................................15
Example and explanation..............................................................................16
7.4 Changing the file permissions for Unix platform..........................................16
Example and explanation..............................................................................16
7.5 Linking files on Unix platform...................................................................16
Example and explanation..............................................................................17

Introduction to ANT (Another Neat Tool)

1.1 What is Ant?

Ant is an automated build-and-deploy tool for simple and complex Java projects. Ant
has value for those creating all-Java applications and for those creating Web
applications using HTML, Java Server Pages (JSP), and Java Servlets. Ant can also
automate and simultaneously document during deployment.
Ant scripts are XML based. Ant handles many tasks that are useful when building and
deploying Java applications. Basic tasks include adding and removing directories,
creating JAR and ZIP files, copying and downloading files using FTP and creating
documentation. More-advanced features include checking out source code from
source code control systems such as CVS or SourceSafe, executing SQL queries or
scripts, transforming XML files to human-readable HTML, and generating stub files
for remote method invocation.

1.2 Features of Ant

1. Ant is written in Java so involves the advantages of Java like portability.


2. Ant uses XML as the scripting language so easy in writing as well as it has the
advantages of XML.
3. Since Ant is written in Java it is platform independent
4. The Ant tasks can be extended by adding your own custom Java classes.
5. The tasks like starting Application Server or Web Server can be automated
with the Ant scripts.

1.3 The differences between Ant and Make

Let us see what are the differences between Ant and Make, the well-known build
tool many C developers use?

Ant is highly suitable for Java, with its own unique paradigms, including portability.
Whereas Make relies on non-portable operating system commands (so a Make file
running under Microsoft Windows won't be of any help to developers using UNIX),
pure Java projects built using Ant are portable, because Ant itself is written in Java
and Ant build files use XML syntax.

This article walks you through the installation, usage and basic Ant tasks
which are used widely.
Prerequisites
1) Jdk should be installed with version 1.3 onwards. The environment variable
JAVA_HOME set to point to the jdk.
2) Ant should be installed. Site to download Ant is http://www.apache.org and
the environment variable ANT_HOME set to point to Ant.
3) Any simple Text Editor like Notepad/Textpad/Editplus/vi

Installation of Ant

The ant executable generally comes in the form of a zip file which you can unzip at a
specific location you want.
The binary distribution of Ant consists of the following directory layout:
ant
+--- bin à contains important scripts like ant.bat for Windows or ant.sh for Unix
| platform
|
+--- lib à contains Ant jars as well as other necessary jar files
|
+--- docs à contains documentation
| +--- ant2 à a brief description of ant2 requirements
| |
| +--- images à various logos for html documentation
| |
| +--- manual à Ant documentation
|
+--- etc à contains XSL files to:
à a) Create an enhanced report from xml output of various
tasks.
à b) Migrate your build files and get rid of 'deprecated'
warning.

Only the bin and lib directories are required to run Ant. This directory will be pointed
to by ANT_HOME environment variable.

How to run Ant?

If Ant is installed as described in the earlier section, to run Ant from the command-
line just type ant
When you run ant on command line without any other file name then it searches for
build.xml file in the present working directory.

4.1 Running ant scripts with a file other build.xml file

If you have created a file other than build.xml then use the following command to
run the scripts:-
ant –buildfile buildfilename

4.2 Saving the output after running the Ant script


If you want to save the output which is shown on the screen to some output file then
just redirect the output to the file like:-
ant –buildfile buildfilename > outputfile
or
ant > outputfile

This works on Unix as well as Windows if you got a doubt about it.

4.3 Running the Ant script partially


If you want only a particular target to be run use the following syntax:-

ant targetname

If required you can also use the –verbose option to get more details like:-
ant –verbose > outputfile

Structure of the Ant build script


Now let us learn how to write an Ant script.
The Ant file structure is made up of one project element as the root containing
target elements which then contain task elements.
Target:-
A target holds a collection of tasks and may depend on other targets.

Tasks:-
A task does the work of the Ant script, such as compiling java files.

There are hundreds of pre-built Ant tasks you can use to create your own Ant scripts.
Ant comes with support for about 75 core tasks and another 40 or so optional tasks.
Core tasks are included in the ant.jar file, and optional tasks are found in
optional.jar. Most of the optional tasks also have library dependencies that make it
necessary to install additional JAR files.

An Ant task is a Java class that extends org.apache.tools.ant.Task. You can also
create your own tasks. Tasks are Java programs that add functionality to Ant.

The basic structure of a well formed build XML file will be like:-

XML tag to depict it is an xml file à <?xml version="1.0" encoding="UTF-8"?>


|
Project Element à <project basedir="." default="release" name="Sample_App">
|
Property Element (Optional) à <property file="properties.xml.ant.properties"/>
|
Target Element à <target name="clean"> …. </target>
|
Ant Tasks à <name attribute1="value1" attribute2="value2" ... />

5.1 Project

A project element 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
basedir The base directory from which all path calculations are done. No

Each project defines one or more targets. When starting Ant, you can select which
target(s) you want to have executed. When no target is given, the project's default
is used.

5.2 Targets
The target element can specify depends attribute which require the specified targets
to be run once before the current target starts.
You can only build a distributable when you have compiled first, so the distribute
target depends on the compile target.

Ant's depends attribute only specifies the order (from left to right) in which targets
should be executed.
<target name="A"/>
<target name="B" depends="A"/>
<target name="C" depends="B"/>
<target name="D" depends="C, B, A"/>

Suppose we want to execute target D. C depends on B, and B depends on A, so first


A is executed, then B, then C, and finally D.
Each target gets executed only once, even when more than one target depends on it.
A target has the following attributes:

Attribute Description Required


name The name of the target. Yes
depends A comma-separated list of names of targets which should get No
executed before execution of this target.
if The name of the property that must be set for this target to No
execute.
unless The name of the property that must not be set in order for this No
target to execute.
description Explanation of this target's function. No

A target name can be any alphanumeric string valid in the encoding of the XML file.
Please avoid using the empty string "", comma "," and space " " which are is in this
set, because they will not be supported in future
Targets beginning with a hyphen such as "-restart" are valid, and can be used to
name targets that should not be called directly from the command line.

5.3 Property
To declare properties (or variables in programming language paradigm) to be
used later in the script you require:-
♦ Name of the property
♦ Value of the property

Use the property element with the attributes name and value.

For example:-
<property name="src" value="src"/>

Thus the property src can be used in the file where it is defined.

But if you have divided your script into multiple files and you want to use the same
property in multiple files then declare the properties in a properties file in the form of
name=value pair and use the properties file in the script.

For example:-
If you write the following properties in a file names common.properties:-
src=src
dest=D://VSS
kit=D://kit
JAVA_HOME=D://jdk1.5.0_03

to use this common.properties in a script use the property element with the
attribute file in the Ant script.

For example:-
<property file="common.properties"/>

You can use these properties by prefixing with a $ like ${src}.

It is advisable to define all properties in a properties file so that even any person not
knowing XML and/or ANT can just edit the properties file with the new values of the
properties (any Ant XML script need not be modified) and make a build.
The additional advantage of having separate properties file is that without modifying
any Ant XML script and just by changing the values of properties in the properties
file the same Ant script can be used on Windows as well as Unix.

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

A task can have multiple attributes (or arguments, you can say). The value of an
attribute might contain references to a property. These references will be resolved
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, and valueN is
the value for this attribute.
All tasks share a task name attribute. The value of this attribute will be used in the
logging messages generated by Ant.
Writing of the Ant build script

General Steps to create a build for J2EE application


The steps to be performed to create a build for a J2EE application can be broadly
listed as follows:-
1) Create Directories to be used in the build process.
2) Compile the java files.
3) Create jar files.
4) Copy the required jsp, html and image files at required locations.
5) Create EJB jar files if required by the project.
6) Create Enterprise Archive .ear file if required by the project.
7) Create Web Application Archive .war file if required by the project.
8) Deleting the temporary directories

Now let us see step-by-step how we convert the above written steps into Ant script:-

Create directory

Requirement:-
To create a directory we require: -
♦ The location where we want to create a directory
♦ The name of the directory.

Ant Task Solution:-


The directories can be created using the mkdir ant task with the following
attributes:-

Attribute Description Required


dir The directory to create. Yes

Example and explanation


For example:-
<mkdir dir="${dest}/temp" />

Where dir attribute will contain the location where the directory has to be created
and the name of the directory to be created. Considering the dest property is
pointing to D://VSS the temp directory will be created under this.

Compile the java files

Requirement:-
To compile the java classes we require:-
♦ Source directory where the java source files (.java) exist.
♦ Destination directory where to place the output of compilation (.class files)
♦ Class path if required.

Ant Task Solution:-


This can be achieved by the javac ant task with the following attributes:-
Attribute Description Required
srcdir Location of the java files. Yes
destdir Location to store the class files. No
includes Comma- or space-separated list of files (may be specified using No
wildcard patterns) that must be included otherwise all .java
files are included when omitted.

Example and explanation


For example:-
<javac srcdir="${src} " destdir="${dest}/temp" includes="**/*.java" >
<classpath>
<pathelement location="${JAVA_HOME}/jre/lib/jsse.jar" />
</classpath>
</javac>

The “includes” attribute in the javac task contains list of files specified using wild-
card patterns. Ant's special handling of wildcards expands **/ to any number of
directories so this task will act on all java files in this directory and all of its
subdirectories. The classpath element has pathelement which can locate the jar files
required by your application.
If you have to write multiple javac tasks and the same classpath has to be repeated
you can give it some id and use it in the task.

For example:-
<path id="compile.classpath">
<pathelement location="${src}"/>
<pathelement location="${JAVA_HOME}/jre/lib/jsse.jar" />
<pathelement location="${dest}"/>
</path>
Now you can use this compile.classpath in the javac tasks as shown in the next
example .

The javac task contains attributes which are similar to the options provided by javac
command.
Let us take a look at some more attributes and their usage:-

Attribute Description Required


failonerror Indicates whether the build will continue even if there are No
compilation errors; defaults to true.
deprecation Indicates whether source should be compiled with deprecation No
information; defaults to off.
debug Indicates whether source should be compiled with debug No
information; defaults to off.

For example:-
<javac srcdir="${src} " destdir="${dest}/temp" includes="**/*.java"
failonerror=false" deprecation="on" debug="on">
<classpath refid="compile.classpath"/>
</javac>

6.3 Create the jar files

Requirement:-
To create jar file we require:-
♦ Location and name of the jar file.
♦ The class files to be included in the jar file.

Ant Task Solution:-


This can be achieved by the jar ant task with the following attributes:-

Attribute Description Required


destfile The JAR file to create. Yes
basedir The directory from which to jar the files. No

Example and explanation


a) If you have to jar class files only from one directory then you can use the
following task:-

For example:-
<jar destfile="${kit}/common.jar" basedir="${dest}"/>

b) If you have to jar class files from multiple directories then you can use the jar
task containing nested fileset task with the dir attribute specifying the base
directory and includes attribute specifying the comma-separated file names or wild-
card patterns of class files to be included in the jar file.

For example:-
<jar destfile="${kit}/app.jar" >
<fileset dir="${dest}" includes="com /foundation/*.class"/>
<fileset dir="${dest}" includes="com /web/*.class"/>
</jar>
c) If you have to create an EJB jar then you can use the jar task containing
manifest attribute if you want to provide your own manifest file otherwise default
manifest file will be included in the jar file.

For example:-
<jar destfile="${kit}/AccMgrEJB.jar" manifest="${dest}/META-
INF/Manifest.mf">
<fileset dir="${dest}" includes="/business_objects/ejb/AccMgrEJB.class"/>

<fileset dir="${ dest}"


includes="/business_objects/ejb/AccMgrEJBBean.class"/>
<fileset dir="${dest}"
includes="/business_objects/ejb/AccMgrEJBHome.class"/>
<fileset dir="${dest}" includes="META-INF/*.xml"/>
</jar>
Copy file(s)

Requirement:-
To copy file(s) what is it that you need to know?
♦ The source directory from where to copy the file(s) and file name(s) to be
copied
♦ The destination directory where to copy the file(s).

Ant Task Solution:-


This can be achieved by the copy ant task with the following attributes:-

Attribute Description Required


file The file to copy. Yes, unless a nested <fileset> element is used.
tofile The file to copy to. With the file attribute, either tofile or todir can be
used.
todir The directory to copy to.

Example and explanation


a) To copy a file from source to destination use the copy task with file attribute to
specify the file to be copied and the tofile attribute to specify where to copy the file.
For example:-
<copy file="${dest}/app.jar" tofile="${kit}/public_html/lib/app.jar" />

b) To copy a set of files from source to destination use the copy task with todir
attribute to specify the destination directory where to copy the files and use the
nested fileset tasks with dir attribute to specify the source directory from where to
copy the files.

For example:-
<copy todir="${dest}/public_html/public/jsps/images/">
<fileset dir="${src}/images/">
<include name="bt_bfdbk.gif" />
<include name="bt_bsrch.gif"/>
<include name="bt_bsthp.gif" />
<include name="bullet.gif" />
</fileset>
</copy>

The fileset task contains nested include task where you can specify the names of
specific files to be copied. So only the files specified in the include task are copied to
the destination directory. Similarly you can also use exclude tasks to specify the
names of the files which you do not want to be copied.

Create Enterprise Archive (.ear) file

Requirement:-
The requirements to create ear file are:-
♦ Name and location of the ear file.
♦ The location of application.xml file
♦ The location and names of the jar files to be included in the ear file.

Ant Task Solution:-


The ear file can be created using the ear ant task with the following attributes:-

Attribute Description Required


Destfile The EAR file to create. Yes
Appxml The deployment descriptor to use (META- Yes, unless update is set
INF/application.xml). to true
Basedir The directory from which to jar the files. No

Example and explanation


The ear task can be used with destfile attribute which will give the location and
name of the ear file to be created, the appxml attribute will specify the location of
the application.xml file and the nested fileset task will help to locate the jar files to
be included in the ear file.

For example:-
<ear destfile="${kit}/ear_war/${ear_filename}"
appxml="${src}/deployment_descriptor/application.xml">
<fileset dir="${dest}/lib" includes="*.jar"/>
</ear>

Create Web Application Archive (.war) file

Requirement:-
To create a War file you need to know
♦ Where do the jsps, html, images, scripts reside
♦ The jar files to be provided to the lib directory.
♦ The location of web.xml file.
♦ Location and name of the war file.

Ant Task Solution:-


The war file can be created using the war ant task with the following attributes:-

Attribute Description Required


Destfile The WAR file to create. Yes
Webxml The deployment descriptor to use Yes, unless update is
(WEB-INF/web.xml). set to true

Example and explanation


To create a war file the war ant task can be used with destfile attribute specifying
the location and name of war file, webxml attribute specifying the location of the
web.xml file, the lib element within the war task will provide the list of jar files. All
files included in this lib element will end up in the WEB-INF/lib directory of the war
file. You can have nested fileset task within the lib element to specify jar files from
diff directories. The web.xml is stored in WEB-INF/web.xml.
For example:-
<war destfile="${kit}/ear_war/${war_filename}"
webxml="${dest}/public_html/web.xml">
<fileset dir="${dest}/public_html/jsps" />
<lib dir="${dest}/public_html/lib/" includes="*.jar"/>
</war>
The nested fileset task here provides the jsp, html, script and image files.

Note:- The jar, ear and war tasks contain an attribute update set to false by default
which means that a new file will be created however it can be set to true when you
want to update an already existing file.

Delete a directory or set of files

Requirement:-
To delete directory we require:-
♦ Location and Name of directory.
To delete a set of files we require:-
♦ Location and Name of directory.
♦ Names of the files.

Ant Task Solution:-


The attributes of delete ant task are as follows:-

Attribute Description Required


file The file to delete, specified as either the simple
filename (if the file exists in the current base
directory), a relative-path filename, or a full-path
filename. At least one of the
two, unless a
dir The directory to delete, including all its files and <fileset> is specified.
subdirectories.
Note: dir is not used to specify a directory name
for file; file and dir are independent of each other.

WARNING: Do not set dir to ".", "${basedir}", or the full-pathname. It will remove
the entire contents of the current base directory (and the base directory itself, if
different from the current working directory).

Example and explanation


a) To delete a directory you can use the delete task with dir attribute specifying the
location and name of the directory.
For example:-
<delete dir="${dest}"/>

b) If you want to delete a particular set of files you can use nested fileset task within
the delete task.

For example:-
<delete>
<fileset dir="${dest}/META-INF" includes="*.xml"/>
</delete>
7. Other tasks
A few other helpful tasks:-

7.1 Run an application


Requirement:-
What is required to run a java application?
♦ Name of the class which contains the main method
♦ Classpath if required.

Ant Task Solution:-


If you want to run an application then you need to use the java ant task with the
following attributes:-

Attribute Description Required


classname The Java class to execute. Either jar or classname
classpath The classpath to use. No

Example and explanation


For example:-
<java classname="test.Main"
classpath=" ${kit}/app.jar"/>

7.2 Print a message


Requirement:-
The way echo is used in Unix to print some message to the user similarly echo task
outputs a message to the users. This works on Unix ad well as Windows platform. It
is similar to System.out.print. It shows the output on the screen else if you have
saved the build output to a file then in the files.

Ant Task Solution:-


The following is the attribute of echo ant task:-

Attribute Description Required


message The message to echo. Yes

Example and explanation


For example:-
<echo message="Creating app.jar file in ${kit}"/>

7.3 Documentation
For generating documentation you can use the javadoc task which makes use of the
javadoc tool.
Requirement:-
♦ The source from which to generate the documentation.

Ant Task Solution:-


The following are the attributes of the javadoc ant task:-
Attribute Description
sourcepath Specify where to find source files
destdir Destination directory for output files
packagenames Comma separated list of package files (with terminating wildcard)

Example and explanation


For example:-
<javadoc sourcepath="${src}"
destdir="${api}"
packagenames="test.*"/>

7.4 Changing the file permissions for Unix platform


You can change the permissions of a file or all files inside specified directories. In
Unix platform the way we have chmod command similarly in Ant we have chmod
task to change the permissions.

Requirement:-
To change permissions you need:-
♦ The name of the directory or file.
♦ The new permissions

Ant Task Solution:-


The following are the attributes of chmod ant task:-

Attribute Description Required


Dir The directory which holds the files whose permissions must be
Yes
changed.
perm The new permissions. Yes

Example and explanation


For example:-
<chmod perm="755"
verbose="true"
dir="${CONFIG_APP}"/>

7.5 Linking files on Unix platform

The way you have ln command in Unix to create symbolic links for files you have
symlink ant task to perform the same job in ANT.

Ant Task Solution:-


The following are the attributes of symlink ant task:-

Attribute Description
link The name of the link to be created
resource The resource where the link should point to.
Example and explanation
For example:-
<symlink link="${CONFIG_APP}/log" resource="/app/log"/>

SAMPLE
Click here to download the sample.

Вам также может понравиться