Ant

131
Vezi ca ai directorul /Ant pe stick si cu FAQ. Detaliaza si toate task-urile de la http://ant-contrib.sourceforge.net/tasks/tasks/ care o librarie free ce ofera task-uri suplimentare, (ex <if>) folositoare care se incarca astfel: <!-- A collection of additional ANT tasks and tools --> <taskdef resource="net/sf/antcontrib/antcontrib.properties"> <classpath> <pathelement location="${basedir}/ant/ant-contrib-0.6.jar"/> </classpath> </taskdef> Alte exemple: <taskdef name="native2ascii" classname="org.apache.tools.ant.taskdefs.optional.Native2Ascii"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar"/> </classpath> </taskdef> <taskdef name="chgrp" classname="org.apache.tools.ant.taskdefs.optional.unix.Chgrp"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar"/> </classpath> </taskdef> http://www.java2s.com/Code/Java/Ant/CatalogAnt.htm http://ant.apache.org/manual/index.html Eclipse has some help about Ant. Eclipse has a built-in ANT that sometimes has different results from an installed ANT. From Eclipse Executing Ant buildfiles from Eclipse Enabling access to Eclipse resources/function from Ant buildfiles (i.e., providing Ant tasks for Eclipse) Providing UI support for running Ant buildfiles and managing their output Providing Ant buildfile development facilities (e.g., buildfile editors, debuggers, ...) The goal of this component is to make Eclipse's Ant tooling the environment of choice for Ant users and support Eclipse-based developers in their product build requirements. 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. Granted, this removes some of the expressive power that is inherent in being able to construct a shell command such as `find . -name foo -exec rm {}`, but it gives you the ability to be cross-platform--to work anywhere and everywhere. And hey, if you really need to execute a shell command, Ant has an <exec> task that allows different commands to be executed based on the OS it is executing on. ATENTIE: Some of the IDEs (Eclipse and NetBeans in particular) ship with extra tasks that only work if IDE-specific tools are on Ant's path. To use these on command-line

Transcript of Ant

Page 1: Ant

Vezi ca ai directorul /Ant pe stick si cu FAQ.

Detaliaza si toate task-urile de la http://ant-contrib.sourceforge.net/tasks/tasks/ care o librarie free ce ofera task-uri suplimentare, (ex <if>) folositoare care se incarca astfel:

<!-- A collection of additional ANT tasks and tools --><taskdef resource="net/sf/antcontrib/antcontrib.properties"> <classpath>

<pathelement location="${basedir}/ant/ant-contrib-0.6.jar"/> </classpath></taskdef>

Alte exemple: <taskdef name="native2ascii" classname="org.apache.tools.ant.taskdefs.optional.Native2Ascii"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar"/> </classpath> </taskdef> <taskdef name="chgrp" classname="org.apache.tools.ant.taskdefs.optional.unix.Chgrp"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar"/> </classpath> </taskdef>

http://www.java2s.com/Code/Java/Ant/CatalogAnt.htmhttp://ant.apache.org/manual/index.html

Eclipse has some help about Ant.

Eclipse has a built-in ANT that sometimes has different results from an installed ANT.From Eclipse

Executing Ant buildfiles from Eclipse Enabling access to Eclipse resources/function from Ant buildfiles (i.e., providing Ant tasks for Eclipse) Providing UI support for running Ant buildfiles and managing their output

Providing Ant buildfile development facilities (e.g., buildfile editors, debuggers, ...)The goal of this component is to make Eclipse's Ant tooling the environment of choice for Ant users and support Eclipse-based developers in their product build requirements.

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.Granted, this removes some of the expressive power that is inherent in being able to construct a shell command such as `find . -name foo -exec rm {}`, but it gives you the ability to be cross-platform--to work anywhere and everywhere. And hey, if you really need to execute a shell command, Ant has an <exec> task that allows different commands to be executed based on the OS it is executing on.

ATENTIE: Some of the IDEs (Eclipse and NetBeans in particular) ship with extra tasks that only work if IDE-specific tools are

on Ant's path. To use these on command-line versions of Ant, the relevant JARs need to be added to the command-line Ant as extra libraries/tasks!!!.

Many Java applications, most particularly application servers, ship with a version of Ant. These are primarily for

internal use by the application, using the Java APIs to delegate tasks such as JSP page compilation to the Ant runtime!!!. Such distributions are usually unsupported by everyone. Particularly troublesome are those products that non only ship with their own Ant release, they add their own version of ANT.BAT or ant.sh to the PATH.

To build and use Ant, you must have a JAXP-compliant XML parser installed and available on your classpath, such as Xerces!!!. The binary distribution of Ant includes the latest version of the Apache Xerces2 XML parser. Please see http://java.sun.com/xml/ for more information about JAXP. If you wish to use a different JAXP-compliant parser, you should remove xercesImpl.jar and xml-apis.jar from Ant's lib directory.

Tip: ant -diagnostics will list the XML parser used and its location si foarte multe alte informatii importante. The later the version of Java , the more Ant tasks you get.

Obs: If a JDK is not present, only the JRE runtime, then many tasks will not work!!!.Before you can run Ant there is some additional set up you will need to do unless you are installing the RPM version from jpackage.org:

Page 2: Ant

Add the bin directory to your path. Set the ANT_HOME environment variable to the directory where you installed Ant. On some operating systems, Ant's

startup 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.

Windows Note:   The ant.bat script makes use of three environment variables - ANT_HOME, CLASSPATH and JAVA_HOME. Ensure that ANT_HOME and JAVA_HOME variables are set, and that they do not have quotes (either ' or ") and they do not end with \ or with /. CLASSPATH should be unset or empty. Daca totul a decurs ok ar trebui ai EXACT urmatorul mesaj cand tastezi ant:

Optional TasksAnt supports a number of optional tasks. An optional task is a task which typically requires an external library to function. The optional tasks are packaged together with the core Ant tasks.The external libraries required by each of the optional tasks is detailed in the Library Dependencies section. These external libraries must be added to Ant's classpath, in any of the following ways:

In ANT_HOME/lib. This makes the JAR files available to all Ant users and builds!!!. In ${user.home}/.ant/lib (as of Ant 1.6). This allows different users to add new libraries to Ant. All JAR files added to

this directory are available to command-line Ant. On the command line with a -lib parameter. This lets you add new JAR files on a case-by-case basis. In the CLASSPATH environment variable. Avoid this; it makes the JAR files visible to all Java applications, and causes no

end of support calls. See below for details.

In some <classpath> accepted by the task itself. For example, as of Ant 1.7.0 you can run the <junit> task without

junit.jar in Ant's own classpath, so long as it is included (along with your program and tests) in the classpath passed when running the task (vezi mult mai jos). Where possible, this option is generally to be preferred!!!, as the Ant script itself can determine the best path to load the library from: via relative path from the basedir (if you keep the library under version control with your project), according to Ant properties, environment variables, Ivy downloads, whatever you like.

IDEs have different ways of adding external JAR files and third-party tasks to Ant. Usually it is done by some configuration dialog.

ATENTION: Sometimes JAR files added to a project are automatically added to ant's classpath. The CLASSPATH environment variable (ATENTION: DO NOT USE Windows CLASSPATH , use <classpath>!!!)The CLASSPATH environment variable is a source of many Ant support queries. As the round trip time for diagnosis on the Ant user mailing list can be slow, and because filing bug reports complaining about 'ant.bat' not working will be rejected by the developers as WORKSFORME "this is a configuration problem, not a bug", you can save yourself a lot of time and frustration by following some simple steps. PROCEDE:

1. Do not ever set CLASSPATH. Ant does not need it, it only causes confusion and breaks things. 2. If you ignore the previous rule, do not ever, ever, put quotes in the CLASSPATH, even if there is a space in a directory.

This will break Ant, and it is not needed. 3. If you ignore the first rule, do not ever, ever, have a trailing backslash in a CLASSPATH, as it breaks Ant's ability to

quote the string. Again, this is not needed for the correct operation of the CLASSPATH environment variable, even if a DOS directory is to be added to the path.

4. You can stop Ant using the CLASSPATH environment variable by setting the -noclasspath option on the command line. This is an easy way to test for classpath-related problems.

The usual symptom of CLASSPATH problems is that ant will not run with some error about not being able to find org.apache.tools.ant.launch.Launcher , or, if you have got the quotes/backslashes wrong, some very weird Java startup error . To see if this is the case, run ant -noclasspath or unset the CLASSPATH environment variable. You can also make your Ant script reject this environment variable just by placing the following at the top of the script ( or in an init target): <property environment="env."/><property name="env.CLASSPATH" value=""/><fail message="Unset $CLASSPATH / %CLASSPATH% before running Ant!"> <condition> <not>

Page 3: Ant

<equals arg1="${env.CLASSPATH}" arg2=""/> </not> </condition></fail>

Displaying %CLASSPATH% !!!: <property environment="env."/> <echo> $$claspath = ${env.CLASSPATH} </echo>Proxy ConfigurationMany Ant built-in and third-party tasks use network connections to retrieve files from HTTP servers. If you are behind a firewall with a proxy server, then Ant needs to be configured with the proxy. Here are the different ways to do this.

With Java1.5When you run Ant on Java1.5, you could try to use the automatic proxy setup mechanism with -autoproxy.

With explicit JVM properties.These are documented by Sun, and control the proxy behaviour of the entire JVM. To set them in Ant, declare them in the ANT_OPTS environment variable. This is the best option for a non-mobile system. For a laptop, you have to change these settings as you roam.

In the build file itselfIf you are writing an build file that is always to be used behind the firewall, the <setproxy> task lets you configure the proxy (which it does by setting the JVM properties). If you do this, we strongly recommend using ant properties to define the proxy host, port, etc, so that individuals can override the defaults.

The Ant team acknowledges that this is unsatisfactory. Until the JVM automatic proxy setup works properly everywhere, explicit JVM options via ANT_ARGS are probably the best solution. Setting properties on Ant's command line do not work, because those are Ant properties being set, not JVM options. This means the following does not set up the command line: ant -Dhttp.proxyHost=proxy -Dhttp.proxyPort=81All it does is set up two Ant properties.One other troublespot with proxies is with authenticating proxies. Ant cannot go beyond what the JVM does here, and as it is very hard to remotely diagnose, test and fix proxy-related problems, users who work behind a secure proxy will have to spend much time configuring the JVM properties until they are happy.

Windows and OS/2Assume Ant is installed in c:\ant\. The following sets up the environment:set ANT_HOME=c:\antset JAVA_HOME=c:\jdk-1.5.0.05set PATH=%PATH%;%ANT_HOME%\binLinux/Unix (bash)Assume Ant is installed in /usr/local/ant. The following sets up the environment:export ANT_HOME=/usr/local/antexport JAVA_HOME=/usr/local/jdk-1.5.0.05export PATH=${PATH}:${ANT_HOME}/bin

Linux/Unix (csh)setenv ANT_HOME /usr/local/antsetenv JAVA_HOME /usr/local/jdk/jdk-1.5.0.05set path=( $path $ANT_HOME/bin )

Having a symbolic link set up to point to the JVM/JSK version makes updates more seamless.

RPM version from jpackage.orgThe JPackage project distributes an RPM version of Ant. With this version, it is not necessary to set JAVA_HOME or ANT_HOME environment variables and the RPM installer will correctly place the Ant executable on your path. NOTE: Since Ant 1.7.0, if the ANT_HOME environment variable is set, the jpackage distribution will be ignored. Optional jars for the JPackage version are handled in two ways. The easiest, and best way is to get these external libraries from JPackage if JPackage has them available. (Note: for each such library, you will have to get both the external package itself (e.g. oro-2.0.8-2jpp.noarch.rpm) and the small library that links ant and the external package (e.g. ant-apache-oro-1.6.2-3jpp.noarch.rpm). However, JPackage does not package proprietary software, and since some of the optional packages depend on proprietary jars, they must be handled as follows. This may violate the spirit of JPackage, but it is necessary if you need these proprietary packages. For example, suppose you want to install support for starteam, which jpackage does not support:

1. Decide where you want to deploy the extra jars. One option is in $ANT_HOME/lib, which, for JPackage is usually /usr/share/ant/lib. Another, less messy option is to create an .ant/lib subdirectory of your home directory and place your non-jpackage ant jars there, thereby avoiding mixing jpackage libraries with non-jpacakge stuff in the same folder. More information on where Ant finds its libraries is available here

2. Download a non-jpackage binary distribution from the regular Apache Ant site3. Unzip or untar the distribution into a temporary directory4. Copy the linking jar, in this case ant-starteam.jar, into the library directory you chose in step 1 above.5. Copy the proprietary jar itself into the same directory.

Finally, if for some reason you are running on a system with both the JPackage and Apache versions of Ant available, if you should want to run the Apache version (which will have to be specified with an absolute file name, not found on the path), you should use Ant's --noconfig command-line switch to avoid JPackage's classpath mechanism.

AdvancedThere are lots of variants that can be used to run Ant. What you need is at least the following:

The classpath for Ant must contain ant.jar and any jars/classes needed for your chosen JAXP-compliant XML parser.

Page 4: Ant

When you need JDK functionality (such as for the javac task or the rmic task), then tools.jar must be added. The scripts supplied with Ant, in the bin directory, will add the required JDK classes automatically, if the JAVA_HOME environment variable is set.

When you are executing platform-specific applications, such as the exec task or the cvs task, the property ant.home must be set to the directory containing where you installed Ant. Again this is set by the Ant scripts to the value of the ANT_HOME environment variable.

The supplied ant shell scripts all support an ANT_OPTS environment variable which can be used to supply extra options to ant. Some of the scripts also read in an extra script stored in the users home directory, which can be used to set such options. Look at the source for your platform's invocation script for details.

Library DependenciesThe following libraries are needed in Ant's classpath if you are using the indicated feature. Note that only one of the regexp libraries is needed for use with the mappers (and Java 1.4 and higher includes a regexp implementation which Ant will find automatically). You will also need to install the particular Ant optional

jar containing the task definitions to make these tasks available. Please refer to the Installing Ant / Optional Tasks section above.Jar Name Needed For Available At

An XSL transformer like Xalan

style taskIf you use JDK 1.4+, an XSL transformer is already included, so you need not do anything special.

XALAN : http://xml.apache.org/xalan-j/index.html

jakarta-regexp-1.3.jar regexp type with mappers http://jakarta.apache.org/regexp/

jakarta-oro-2.0.8.jar

regexp type with mappers and the perforce tasksTo use the FTP task, you need jakarta-oro 2.0.8 or later, and commons-net

http://jakarta.apache.org/oro/

junit.jar <junit> task. May be in classpath passed to task rather than Ant's classpath. http://www.junit.org/

xalan.jar junitreport task http://xml.apache.org/xalan-j/

stylebook.jar stylebook task SVN repository of http://xml.apache.org/svn.html

antlr.jar antlr task http://www.antlr.org/

bsf.jar

script task Note: Ant 1.6 and later require Apache BSF, not the IBM version. I.e. you need BSF 2.3.0-rc1 or later. Note: BSF 2.4.0 is needed to use a post 1.5R3 version of rhino's javascript. Note: BSF 2.4.0 uses jakarata-commons-logging so it needs the commons-logging.jar.

http://jakarta.apache.org/bsf/

Groovy jars

Groovy with script and scriptdef tasksYou need to get the groovy jar and two asm jars from a groovy installation. The jars are groovy-[version].jar, asm-[vesion].jar and asm-util-[version].jar and antlr-[version].jar. As of groovy version 1.0-JSR-06, the jars are groovy-1.0-JSR-06.jar, antlr-2.7.5.jar, asm-2.2.jar and asm-util-2.2.jar. Alternatively one may use the embedded groovy jar file. This is located in the embedded directory of the groovy distribution. This bundles all the needed jar files into one jar file. It is called groovy-all-[version].jar.

http://groovy.codehaus.org/ The asm jars are also available from the creators of asm - http://asm.objectweb.org/

netrexx.jar netrexx task, Rexx with the script task http://www.ibm.com/software/awdtools/netrexx/download.html

js.jarJavascript with script taskIf you use Apache BSF 2.3.0-rc1, you must use rhino 1.5R3 (later versions of BSF (e.g. version 2.4.0) work with 1.5R4 and higher).

http://www.mozilla.org/rhino/

jython.jarPython with script taskWarning : jython.jar also contains classes from jakarta-oro. Remove these classes if you are also using jakarta-oro.

http://jython.sourceforge.net/

jpython.jar Python with script task deprecated, jython is the prefered engine http://www.jpython.org/

jacl.jar and tcljava.jar

TCL with script task http://www.scriptics.com/software/java/

BeanShell JAR(s)

BeanShell with script task. Note: Ant requires BeanShell version 1.3 or later

http://www.beanshell.org/

jruby.jar Ruby with script task http://jruby.sourceforge.net/

judo.jar Judoscript with script task http://www.judoscript.com/index.html

commons-logging.jar

CommonsLoggingListener http://jakarta.apache.org/commons/logging/index.html

log4j.jar Log4jListener http://jakarta.apache.org/log4j/docs/index.html

commons-net.jar

ftp, rexec and telnet tasksjakarta-oro 2.0.8 or later is required together with commons-net 1.4.0.For all users, a minimum version of commons-net of 1.4.0 is recommended. Earlier versions did not support the full range of configuration options, and 1.4.0 is needed to compile Ant.

http://jakarta.apache.org/commons/net/index.html

Page 5: Ant

bcel.jarclassfileset data type, JavaClassHelper used by the ClassConstants filter reader and optionally used by ejbjar for dependency determination

http://jakarta.apache.org/bcel/

mail.jar Mail task with Mime encoding, and the MimeMail task http://java.sun.com/products/javamail/

jsse.jar Support for SMTP over TLS/SSL in the Mail task. Already included Java 1.4+ http://java.sun.com/products/jsse/

activation.jar Mail task with Mime encoding, and the MimeMail task http://java.sun.com/products/javabeans/glasgow/jaf.html

jdepend.jar jdepend task http://www.clarkware.com/software/JDepend.html

resolver.jar 1.1beta or later

xmlcatalog datatype only if support for external catalog files is desired http://xml.apache.org/commons/.

jsch.jar 0.1.29 or later

sshexec and scp tasks http://www.jcraft.com/jsch/index.html

JAI - Java Advanced Imaging

image task http://java.sun.com/products/java-media/jai/

Starteam SDK Starteam version management tasks http://www.borland.com/downloads/download_starteam.html

Troubleshooting ATENTION: run always ant -diagnostics when something doesn’t work!!!.Ant has a built in diagnostics feature. If you run ant -diagnostics ant will look at its internal state and print it out. This code will check and print the following things.

Where Ant is running from. Sometimes you can be surprised. The version of ant.jar and of the ant-*.jar containing the optional tasks - and whether they match Which JAR files are in ANT_HOME/lib Which optional tasks are available. If a task is not listed as being available, either it is not present, or libraries that it depends on are absent. XML Parser information JVM system properties The status of the temp directory. If this is not writeable, or its clock is horribly wrong (possible if it is on a network drive), a lot of tasks will fail with

obscure error messages. The current time zone as Java sees it. If this is not what it should be for your location, then dependency logic may get confused.

Running ant -diagnostics is a good way to check that ant is installed. It is also a first step towards self-diagnosis of any problem. Any configuration problem reported to the user mailing list will probably result ins someone asking you to run the command and show the results, so save time by using it yourself. For under-IDE diagostics, use the <diagnostics> task to run the same tests as an ant task. This can be added to a diagnostics target in a build file to see what tasks are available under the IDE, what the XML parser and classpath is, etc. Vezi ca este detaliat si despre task-ul de proxy si cum se configureaza proxy in manualul online.

Platform IssuesJava 1.5You may need a bigger stack than default, especially if you are using the built in XSLT engine. We recommend you use Apache Xalan; indeed, some tasks (JUnit report in XML, for example) may not work against the shipping XSL engine.

Unix and Linux Ant does not preserve file permissions when a file is copied, moved or archived, because

Java does not let it read or write the permissions!!!. Use <chmod> to set permissions, and when creating a tar archive, use the mode attribute of <tarfileset> to set the permissions in the tar file, or <apply> the real tar program.

Ant is not symbolic link aware in moves, deletes and when recursing down a tree of directories to build up a list of files. Unexpected things can happen.

Linux on IA-64: apparently you need a larger heap than the default one (64M) to compile big projects. If you get out of heap errors, either increase the heap or use a forking javac. Better yet, use jikes for extra compilation speed.

Microsoft Windows 2K, XP and Server 2K03 Windows 9x (win95, win98, win98SE and winME) has a batch file system which does not work fully with long file names,

so we recommend that ant and the JDK are installed into directories without spaces, and with 8.3 filenames!!!. The Perl and Python launcher scripts do not suffer from this limitation. All versions of windows are usually case insensitive, although mounted file systems (Unix drives, Clearcase views) can be case sensitive underneath, confusing patternsets.

ATENTIE: Ant can often not delete a directory which is open in an Explorer window (Mi se intampla la fel si in Eclipse cand nu mi se compila sin u genera class-urile din cauza ca nu putea sterge un director care era deja deschis!!!). There is nothing we can do about this short of spawning a program to kill the shell before deleting directories. Nor can files that are in use be overwritten.

Page 6: Ant

Finally, if any Ant task fails with an IOError=2, it means that whatever native program Ant is trying to run, it is not on the path.

Microsoft Windows VistaThere are reports of problems with Windows Vista security bringing up dialog boxes asking if the user wants to run an untrusted executable during an ant run, such as when the <signjar> task runs the jarsigner.exe program. This is beyond Ant's control, and stems from the OS trying to provide some illusion of security by being reluctant to run unsigned native

executables. The latest Java versions appear to resolve this problem by having signed binaries.

CygwinCygwin is not an operating system; rather it is an application suite running under Windows and providing some UNIX like functionality. Sun has not created any specific Java Development Kit or Java Runtime Environment for cygwin. See this link : http://www.inonit.com/cygwin/faq/ . Only Windows path names are supported by JDK and JRE tools under Windows or cygwin. Relative path names such as "src/org/apache/tools" are supported, but Java tools do not understand /cygdrive/c to mean c:\. The utility cygpath (used industrially in the ant script to support cygwin) can convert cygwin path names to Windows. You can use the <exec> task in ant to convert cygwin paths to Windows path, for instance like that : <property name="some.cygwin.path" value="/cygdrive/h/somepath"/><exec executable="cygpath" outputproperty="windows.pathname"> <arg value="--windows"/> <arg value="${some.cygwin.path}"/></exec><echo message="${windows.pathname}"/>We get lots of support calls from Cygwin users. Either it is incredibly popular, or it is trouble. If you do use it, remember that Java is a Windows application, so Ant is running in a Windows process, not a Cygwin one. This will save us having to mark your bug reports as invalid.

Writing a Simple BuildfileAnt's buildfiles are written in XML. Each buildfile contains one project and at least one (default) target. Targets

contain task elements. Each task element of the buildfile can have an id attribute and can later be referred to by the value supplied to this. The value has to be unique.

ProjectsA 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

No

Page 7: Ant

property have been set, the parent directory of the buildfile will be used.

Optionally, a description for the project can be provided as a top-level <description> element (see the description type). Ex:<description> This buildfile is used to build the Foo subproject within the large, complex Bar project.</description>

Each project defines one or more targets. A target is a set of tasks you want to be executed. 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.

Targets IS MADE FROM MULTIPE TASKS, identified by name.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 a distributable when you have compiled first, so the distribute target depends on the compile target. Ant resolves these dependencies. ATENTIE: It should be noted, however, that Ant's depends attribute only specifies the order in which targets should be executed - it does not affect whether the target that specifies the dependency(s) gets executed if the dependent target(s) did not (need to) run!!!.

Ant tries to execute the targets in the depends attribute in the order they appear (from left to right). Keep in mind that it is possible that a target can get executed earlier when an earlier target depends on it:

<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. From its depends attribute, you might think that first target C, then B and then A is executed. Wrong! C depends on B, and B depends on A, so first A is executed, then B, then C, and finally D. In a chain of dependencies stretching back from a given target such as D above, each target gets executed only once, even when more than one target depends on it. Thus, executing the D target will first result in C being called, which in turn will first call B, which in turn will first call A. After A, then B, then C have executed, execution returns to the dependency list of D, which will not call B and A, since they were already called in process of dependency resolution for C and B respectively as dependencies of D. Had no such dependencies been discovered in processing C and B, B and A would have been executed after C in processing D's dependency list.

A target also has the ability to perform its execution if (or unless) a property(see below attribute property) has been set. This allows, for example, better control on the building process depending on the state of the system (java version, OS, command-line property defines, etc.). To make a target sense this property, you should add the if (or unless ) attribute with the name of the property that the target should react to. Note: Ant will only check whether the property has been set, the value doesn't matter!!!. A property set to the empty string is still an existing property. For example:

<!-- Is executed only if the exists the property module-A-present.--><target name="build-module-A" if="module-A-present"/> <!-- Executed only if is NOT defined the module-A-present property.--><target name="build-own-fake-module-A" unless="module-A-present"/>

Page 8: Ant

Only one propertyname can be specified in the if/unless clause. If you want to check multiple conditions, you can use a dependend target for computing the result for the check (Vezi mai jos target-ul se identifica dupa name):<target name="myTarget" depends="myTarget.check" if="myTarget.run"> <echo>Files foo.txt and bar.txt are present.</echo></target>

<target name="myTarget.check"> <condition property="myTarget.run"> <and> <available file="foo.txt"/> <available file="bar.txt"/> </and> </condition></target>

If no if and no unless attribute is present, the target will always be executed!!!.Important: the if and unless attributes only enable or disable the target to which they are attached. They do not control whether or not targets that a conditional target depends upon get executed. In fact, they(adica atributele) do not even get evaluated until the target is about to be executed, and all its predecessors have already run. The optional description attribute can be used to provide a one-line description of this target, which is printed by the -projecthelp command-line option. Targets without such a description are deemed internal and will not be listed, unless either the -verbose or -debug option is used. Ex: Am doua fisiere bar.txt si foo.txt in directorul c:\test si fisierul build.xml urmator:<project name="MyProject" basedir="." default="myTarget"> <description> A web project </description> <target name="myTarget" depends="myTarget.check" if="myTarget.run"> <echo>Files foo.txt and bar.txt are present.</echo> </target> <target name="myTarget.check"> <condition property="myTarget.run"> <and> <available file="foo.txt"/> <available file="bar.txt"/> </and> </condition> </target></project>

Obs:1. Daca as fi dat alt nume proprietatii " myTarget.run " atunci n-ar mai fi rulat myTarget => nu s-ar mai fi afisat echo-

ul(desi build-ul ar fi fost tot successful).2. Daca as dat alt nume target-ului myTarget atunci ar fi fost BUILD FAILED intrucat nu ar fi gasit target-ul default

specificat in atributul default al tag-ului project. La fel daca as fi schimbat numele target-ului myTarget.check as fi avut eroare: BUILD FAILED Target "myTarget.check" does not exist in the project "MyProject". It is used from target "myTarget".

3. Se pot obtine informatii suplimentare cum ar fi ordinea target-urilor,etc cu tag-ul –verbose:

4. Mai multa informatie decat –verbose este oferita de –debug care poate fi folosita la debug-ul script-

ului. Ex:

Page 9: Ant

5. Pot specifica direct ca si parametru pentru ant numele unui anumit target care doresc sa-l rulez:

6. Atentie se pare ca se obisnuieste ca task-urile de care depind alte task-uri sa poarte ca si prefix numele acestora urmat de punct vezi myTarget.check .

It is a good practice to place your tstamp tasks in a so-called initialization target, on which all other targets

depend. Make sure that target is always the first one in the depends list of the other targets. In this manual, most initialization targets have the name "init" . If the depends attribute and the if/unless attribute are set, the depends attribute is executed first(vezi si in ex de mai sus)!!!.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 on which this target depends. Se executa inaintea if/unless.

No

if the name of the property that must be set in order for this target to execute. No

unless the name of the property that must not be set in order for this target to execute. No

description a short description of this target's function. No

A target name can be any alphanumeric string valid in the encoding of the XML file. The empty string "" is in this set, as is comma "," and space " ". Please avoid using these, as they will not be supported in future Ant versions because of all the confusion they cause. IDE support of unusual target names, or any target name containing spaces, varies with the IDE.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.

TasksA task is a piece of code that can be executed. Spre dosebire target-urile contin una sau mai multe task-uri adica sunt grupuri de task-uri.A task can have multiple attributes (or arguments, if you prefer). 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.There is a set of built-in tasks, along with a number of optional tasks, but it is also very easy to write your own.All tasks share a task name attribute. The value of this attribute will be used in the logging messages generated by Ant.

Tasks can be assigned an id attribute (se identifica astfel chiar instanta, spre exemplu poti avea mai multe task-uri jar dar ca sa le identifici separat folosesti atributul id!!!) : <taskname id="taskID" ... />

Page 10: Ant

where taskname is the name of the task, and taskID is a unique identifier for this task. You can refer to the corresponding 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 via project.getReference("task1"). Note1: If "task1" has not been run yet, then it has not been configured (ie., no attributes have been set), and if it is going to be configured later, anything you've done to the instance may be overwritten. Note2: Future versions of Ant will most likely not be backward-compatible with this behaviour, since there will likely be no task instances at all, only proxies.

PropertiesA 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 . In the event you should need to include this construct literally (i.e. without property substitutions), simply "escape" the '$' character by doubling it. To continue the previous example: <echo>$${builddir}=${builddir}</echo>will echo this message: ${builddir}=build/classesIn order to maintain backward compatibility with older Ant releases, a single '$' character encountered apart from a property-like construct (including a matched pair of french braces) will be interpreted literally; that is, as '$'. The "correct" way to specify this literal character, however, is by using the escaping mechanism unconditionally, so that "$$" is obtained by specifying "$$$$". Mixing the two approaches yields unpredictable results, as "$$$" results in "$$".

Built-in Properties (proprietatile JVM sunt accesibile ca si cum ar fi fost definite cu <property>)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: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 Antant.project.name the name of the project that is 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.2", "1.3",

"1.4" and "1.5".

There is also another property, but this is set by the launcher script and therefore maybe not set inside IDEs:ant.home home directory of Ant

Example Buildfile (se observa ca porneste cu ultimul target dist insa el depinde de compile care depinde de init deci init va fi executat primul dupa definirea task-urilor proprietate)

<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"/> <!--dist from distribution.-->

<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>

Page 11: Ant

<target name="dist" depends="compile" description="generate the distribution." > <!-- Create the distribution directory. --> <mkdir dir="${dist}/lib"/>

<!-- Put everything from ${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 of Ant 1.6 all tasks can be declared outside targets (earlier version only allowed <property>,<typedef> and <taskdef>).

ATENTIE: When you do this they are evaluated before any targets are executed!!!. Some tasks will generate build failures if they are used outside of targets as they may cause infinite loops otherwise (<antcall> for example).We have given some targets descriptions; this causes the projecthelp invocation option to list them as public targets with the descriptions; the other target is internal and not listed. Finally, for this target to work the source in the src subdirectory should be stored in a directory tree which matches the package names. Check the <javac> task for details.

Token FiltersA project can have a set of tokens that might be automatically expanded if found when a file is copied , when the filtering- copy behavior is selected in the tasks that support this. These might be set in the buildfile by the filter task.Since this can potentially be a very harmful behavior, the tokens in the files must be of the form @ token @ , where token is the token name that is set in the <filter> task. This token syntax matches the syntax of other build systems that perform such filtering and remains sufficiently orthogonal to most programming and scripting languages, as well as with documentation systems.Note: If a token with the format @token@ is found in a file, but no filter is associated with that token, no changes take place; therefore, no escaping method is available - but as long as you choose appropriate names for your tokens, this should not cause problems.Warning: If you copy binary files with filtering turned on, you can corrupt the files. This feature should be used with text files only.

Path-like Structures (CLASSPATH !!!)ATENTIE: <classpath> e totusi un task desi nu apare in lista de task-uri predefinite!!!.You can specify PATH- and CLASSPATH-type references using both " : " and " ; " as separator characters. Ant will convert the separator to the correct character of the current operating system.Wherever path-like values need to be specified, a nested element can be used. This takes the general form of: <classpath> <pathelement path="${classpath}"/> <pathelement location="lib/helper.jar"/> </classpath>

The location attribute specifies a single file or directory relative to the project's base directory (or an absolute filename), while the path attribute accepts colon- or semicolon-separated lists of locations. The path attribute is intended to be used with predefined paths - in any other case, multiple elements with location attributes should be preferred.As a shortcut, the <classpath> tag supports path and location attributes of its own, so: <classpath> <pathelement path="${classpath}"/> </classpath>

can be abbreviated to: <classpath path="${classpath}"/>

Page 12: Ant

In addition, one or more Resource Collections can be specified as nested elements (these must consist of file-type resources only). Additionally, it should be noted that although resource collections are processed in the order encountered, certain resource collection types such as fileset, dirset and files are 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 named classes under the apps subdirectory of ${build.dir} , except those that have the text Test in their name, and the 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 the SAME LEVEL as target s (ADICA NU INCLUSE IN TARGET-URI => le definesti cu <path>!!!), and reference them via their id attribute--see References (mai jos) for an example.

A path-like structure can include a reference to another path-like structure(self inclusion) (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"> <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 (convertirea intr-un string dependent de OS!!!)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="-Xbootstrap/p:${toString:lib.path.ref}"/> </javac>Exemple:

<javac srcdir="." source="1.4" debug="on" debuglevel="${debug.level}" includes="com/**,test/**" classpath="D:/Work/aiw_d1_win/UI_Web/WebContent/WEB-INF/classes"> <classpath refid="javac.classpath.path" /> <classpath location="../Interfaces/interfaces.jar" /> <classpath location="../Server/server.jar" /> <classpath location="../UI_Web/WebContent/WEB-INF/lib/ui_view_tags.jar" /> <classpath location="../UI_Web/WebContent/WEB-INF/lib/j2ee.jar" /> <classpath location="../UI_Web/WebContent/WEB-INF/lib/jstl.jar" /> <classpath location="../UI_Web/WebContent/WEB-INF/lib/struts.jar" /> <classpath> <pathelement path="../UI_Web/WebContent/WEB-INF/classes/**"/> </classpath>

Page 13: Ant

</javac> <javac srcdir="." debug="on" target="1.5" classpath=".:${baseFiles}:../base/webService.jar:../base/j2ee.jar:../base/interfaces.jar:../base/server.jar" includes="com/**/*.java"> <classpath> <fileset dir=".">

<include name="*.jar"/> </fileset>

</classpath> </javac>

Displaying %CLASSPATH% !!!: <property environment="env."/> <echo> $$claspath = ${env.CLASSPATH} </echo>

Command-line ArgumentsSeveral tasks take arguments that will be passed to another process on the command line. To make it easier to specify arguments that 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(vezi mai jos) to a path defined elsewhere. Ant will convert it to the platform's local conventions.

line a space-delimited list of command-line arguments.

It is highly recommended to avoid the line version when possible. Ant will try to split the command line in a way similar to what a (Unix) shell would do, but may create something that is 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 value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems. Obs: Dir. se separa cu : sau ; si vor fi convertite corect in forma acceptata de OS.

References (id, refid, used to eliminate duplicates and to transmit parameters)Any project element can be assigned an identifier using its id attribute. In most cases the element can subsequently be referenced by specifying the refid attribute on an element of the same type!!!. This can be useful if you are going to replicate 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>

Page 14: Ant

</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 PatternSet s, FileSet s, ZipFileSet s 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 tasksAnt 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 them2. 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"/> E.g.:<taskdef name="activateExtension" classname="com.extension.activation.anttask.ActivateExtension" classpath="${env.CLASSPATH}"/>

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 tasks2. have a look at the external task page in the manual (or better online)3. have a look at the external task wiki page4. ask on the Ant user list5. implement (and share) your own

Running AntCommand LineIf you've installed Ant as described in the Installing Ant section, running Ant from the command-line is simple: just type ant.When no arguments are specified, Ant looks for a build.xml file in the current directory and, if found, uses that file as the build file and runs the target specified in the default attribute of the <project> tag. To make Ant use a build file other than build.xml, use the command-line option -buildfile file, where file is the name of the build file you want to use. If you use the -find [file] option, Ant will search for a build file first in the current directory, then in the parent directory, and so on, until either a build file is found or the root of the filesystem has been reached. By default, it will look for a build file called build.xml. To have it search for a build file other than build.xml, specify a file argument. Note: If you include any other flags or arguments on the command line after the -find flag, you must include the file argument for the -find flag, even if the name of the build file you want to find is build.xml.

Page 15: Ant

You can also set properties on the command line. This can be done with the -Dproperty=value option, where property is the name of the property, and value is the value for that property. If you specify a property that is also set in the build file (see the property task), the value specified on the command line will override the value specified in the build file. Defining properties on the command line can also be used to pass in the value of environment variables; just pass -DMYVAR=%MYVAR% (Windows) or -DMYVAR=$MYVAR (Unix) to Ant. You can then access

these variables inside your build file as ${MYVAR}. You can also access environment variables using the property task's environment attribute!!!. Options that affect the amount of logging output by Ant are: -quiet, which instructs Ant to print less information to the console; -verbose, which causes Ant to print additional information to the console; and -debug, which causes Ant to print considerably more additional information. It is also possible to specify one or more targets that should be executed. When omitted, the target that is specified in the default attribute of the project tag is used.The -projecthelp option prints out a list of the build file's targets. Targets that include a description attribute are listed as "Main targets", those without a description are listed as "Other targets", then the "Default" target is listed ("Other targets" are only displayed if there are no main targets, or if Ant is invoked in -verbose or -debug mode).

Command-line Options Summaryant [options] [target [target2 [target3] ...]]Options: -help, -h print this message -projecthelp, -p print project help information -version print the version information and exit -diagnostics print information that might be helpful to diagnose or report problems. -quiet, -q be extra quiet -verbose, -v be extra verbose -debug, -d print debugging information -emacs, -e produce logging information without adornments -lib <path> specifies a path to search for jars and classes -logfile <file> use given file for log -l <file> '' -logger <classname> the class which is to perform logging -listener <classname> add an instance of class as a project listener -noinput do not allow interactive input -buildfile <file> use given buildfile -file <file> '' -f <file> '' -D<property>=<value> use value for given property -keep-going, -k execute all targets that do not depend on failed target(s) -propertyfile <name> load all properties from file with –D properties taking precedence -inputhandler <class> the class which will handle input requests -find <file> (s)earch for buildfile towards the root of -s <file> the filesystem and use it -nice number A niceness value for the main thread: 1 (lowest) to 10 (highest); 5 is the default -nouserlib Run ant without using the jar files from ${user.home}/.ant/lib -noclasspath Run ant without using CLASSPATH -autoproxy Java 1.5+ : use the OS proxies -main <class> override Ant's normal entry pointFor more information about -logger and -listener see Loggers & Listeners. For more information about -inputhandler see InputHandler. Easiest way of changing the exit-behaviour is subclassing the original main class: public class CustomExitCode extends org.apache.tools.ant.Main { protected void exit(int exitCode) { // implement your own behaviour, e.g. NOT exiting the JVM }}and starting Ant with access (-lib path-to-class) to this class.

Library DirectoriesPrior to Ant 1.6, all jars in the ANT_HOME/lib would be added to the CLASSPATH used to run Ant. This was done in the scripts that started Ant. From Ant 1.6, two directories are scanned by default and more can be added as required. The default directories scanned are ANT_HOME/lib and a user specific directory, ${user.home}/.ant/lib. This arrangement allows the Ant installation to be shared by many users while still allowing each user to deploy additional jars. Such additional jars could be support jars for Ant's optional tasks or jars containing third-party tasks to be used in the build. It also allows the main Ant installation to be locked down which will please system adminstrators.

Additional directories to be searched may be added by using the -lib option. The -lib option specifies a search path. Any jars or classes in the directories of the path will be added to Ant's classloader. The order in which jars are added to the classpath is as follows:

-lib jars in the order specified by the -lib elements on the command line jars from ${user.home}/.ant/lib (unless -nouserlib is set) jars from ANT_HOME/lib

Note that the CLASSPATH environment variable is passed to Ant using a -lib option. Ant itself is started with a very minimalistic classpath. Ant should work perfectly well with an empty CLASSPATH environment variable, something the the -noclasspath option actually enforces. We get many more support calls related to classpath problems (especially quoting problems) than we like. The location of ${user.home}/.ant/lib is somewhat dependent on the JVM. On Unix systems ${user.home} maps to the user's home directory whilst on recent versions of Windows it will be somewhere such as C:\Documents and Settings\username\.ant\lib. You should consult your JVM documentation for more details.

Examplesant

Page 16: Ant

runs Ant using the build.xml file in the current directory, on the default target.ant -buildfile test.xmlruns Ant using the test.xml file in the current directory, on the default target.ant -buildfile test.xml distruns Ant using the test.xml file in the current directory, on the target called dist.ant -buildfile test.xml -Dbuild=build/classes distruns Ant using the test.xml file in the current directory, on the target called dist, setting the build property to the value build/classes.ant -lib /home/ant/extrasruns Ant picking up additional task and support jars from the /home/ant/extras location

FilesThe Ant wrapper script for Unix will source (read and evaluate) the file ~/.antrc before it does anything. On Windows, the Ant wrapper batch-file invokes %HOME%\antrc_pre.bat at the start and %HOME%\antrc_post.bat at the end. You can use these files, for example, to set/unset environment variables that should only be visible during the execution of Ant. See the next section for examples.

Environment VariablesThe wrapper scripts use the following environment variables (if set):

JAVACMD - full path of the Java executable. Use this to invoke a different JVM than JAVA_HOME/bin/java(.exe) .

ANT_OPTS - command-line arguments that should be passed to the JVM. For example, you can define system properties or set the maximum Java heap size here.

ANT_ARGS - Ant command-line arguments. For example, set ANT_ARGS to point to a different logger, include a listener, and to include the -find flag.Note: If you include -find in ANT_ARGS, you should include the name of the build file to find, even if the file is called build.xml.

Java System PropertiesSome of Ant's core classes can be configured via system properties. Here is the result of a search through the codebase. Because system properties are available via Project instance, I searched for them with a grep -r -n "getPropert" * > ..\grep.txtcommand. After that I filtered out the often-used but not-so-important values (most of them read-only values): path.separator, ant.home, basedir, user.dir,

os.name, line.separator, java.home, java.version, java.version, user.home, java.class.path. And I filtered out the getPropertyHelper access.property name valid values /default value description

ant.build.javac.source Source-level version number Default source value for <javac>/<javadoc>

ant.build.javac.target Class-compatibility version number Default target value for <javac>

ant.executor.class classname; default is org. apache. tools. ant. helper. DefaultExecutor

Since Ant 1.6.3 Ant will delegate Target invocation to the org.apache.tools.ant.Executor implementation specified here.

ant.file read only: full filename of the build fileThis is set to the name of the build file. In <import>-ed files, this is set to the containing build file.

ant.file.* read only: full filename of the build file of Ant projects

This is set to the name of a file by project; this lets you determine the location of <import>-ed files,

ant.input.properties filename (required) Name of the file holding the values for the PropertyFileInputHandler.

ant.logger.defaults filename (optional, default '/org/ apache/ tools/ ant/ listener/ defaults.properties')

Name of the file holding the color mappings for the AnsiColorLogger.

ant.netrexxc.* several formats Use specified values as defaults for netrexxc.

ant.PropertyHelper ant-reference-name (optional)Specify the PropertyHelper to use. The object must be of the type org.apache.tools.ant.PropertyHelper. If not defined an object of org.apache.tools.ant.PropertyHelper will be used as PropertyHelper.

ant.regexp.regexpimpl classnameclassname for a RegExp implementation; if not set Ant tries to find another (JDK14+, Apache Oro...); RegExp-Mapper "Choice of regular expression implementation"

ant.reuse.loader boolean allow to reuse classloaders used in org.apache.tools.ant.util.ClasspathUtil

ant.XmlLogger.stylesheet.uri filename (default 'log.xsl') Name for the stylesheet to include in the logfile by XmlLogger.

build.compiler nameSpecify the default compiler to use. see javac, EJB Tasks (compiler attribute), javah

build.compiler.emacs boolean (default false) Enable emacs-compatible error messages. see javac "Jikes Notes"

build.compiler.fulldepend boolean (default false) Enable full dependency checking see javac "Jikes Notes"

build.compiler.jvc.extensions boolean (default true) enable Microsoft extensions of their java compiler see javac "Jvc Notes"

build.compiler.pedantic boolean (default false) Enable pedantic warnings. see javac "Jikes Notes"

build.compiler.warnings Deprecated flag see javac "Jikes Notes"

build.rmic name control the rmic compiler

build.sysclasspath "only", something else

only: current threads get the actual class loader (AntClassLoader.setThreadContextLoader()). else: use core loader as default (ComponentHelper.initTasks()). Disable changing the classloader (oata.taskdefs.Classloader.execute() experimental task).

file.encoding name of a supported character set (e.g. UTF-8, ISO-8859-1, US-ASCII)

use as default character set of email messages; use as default for source-, dest- and bundleencoding in translate see JavaDoc of java.nio.charset.Charset for more information about

Page 17: Ant

character sets (not used in Ant, but has nice docs).

jikes.class.path path The specified path is added to the classpath if jikes is used as compiler.

MailLogger.properties.file, MailLogger.*

filename (optional, defaults derived from Project instance)

Name of the file holding properties for sending emails by the MailLogger. Override properties set inside the buildfile or via command line.

org.apache.tools.ant.ProjectHelper

classname (optional, default 'org.apache.tools.ant.ProjectHelper')

specifies the classname to use as ProjectHelper. The class must extend org.apache.tools.ant.ProjectHelper.

p4.port, p4.client, p4.user several formats Specify defaults for port-, client- and user-setting of the perforce tasks.

websphere.home path Points to home directory of websphere. see EJB Tasks

XmlLogger.file filename (default 'log.xml') Name for the logfile for MailLogger.

If new properties get added (it happens), expect them to appear under the "ant." and "org.apache.tools.ant" prefixes, unless the developers have a very good reason to use another prefix. Accordingly, please avoid using properties that begin with these prefixes. This protects you from future Ant releases breaking your build file.

return codethe ant start up scripts (in their Windows and Unix version) return the return code of the java program. So a successful build returns 0, failed builds return other values.

Cygwin UsersThe Unix launch script that come with Ant works correctly with Cygwin. You should not have any problems launching Ant from the Cygwin shell. It is important to note, however, that once Ant is running it is part of the JDK which operates as a native Windows application. The JDK is not a Cygwin executable, and it therefore has no knowledge of Cygwin paths, etc. In particular when using the <exec> task, executable names such as "/bin/sh" will not work, even though these work from the Cygwin shell from which Ant was launched. You can use an executable name such as "sh" and rely on that command being available in the Windows path.

OS/2 UsersThe OS/2 launch script was developed to perform complex tasks. It has two parts: ant.cmd which calls Ant and antenv.cmd which sets the environment for Ant. Most often you will just call ant.cmd using the same command line options as described above. The behaviour can be modified by a number of ways explained below.Script ant.cmd first verifies whether the Ant environment is set correctly. The requirements are:

1. Environment variable JAVA_HOME is set.2. Environment variable ANT_HOME is set.3. Environment variable CLASSPATH is set and contains at least one element from JAVA_HOME and at least one element from ANT_HOME.

If any of these conditions is violated, script antenv.cmd is called. This script first invokes configuration scripts if there exist: the system-wide configuration antconf.cmd from the %ETC% directory and then the user configuration antrc.cmd from the %HOME% directory. At this moment both JAVA_HOME and ANT_HOME must be defined because antenv.cmd now adds classes.zip or tools.jar (depending on version of JVM) and everything from %ANT_HOME%\lib except ant-*.jar to CLASSPATH. Finally ant.cmd calls per-directory configuration antrc.cmd. All settings made by ant.cmd are local and are undone when the script ends. The settings made by antenv.cmd are persistent during the lifetime of the shell (of course unless called automatically from ant.cmd). It is thus possible to call antenv.cmd manually and modify some settings before calling ant.cmd.Scripts envset.cmd and runrc.cmd perform auxiliary tasks. All scripts have some documentation inside.

Running Ant via Java (se foloseste task-ul <java>)If you have installed Ant in the do-it-yourself way, Ant can be started from one of two entry points:java -Dant.home=c:\ant org.apache.tools.ant.Main [options] [target]java -Dant.home=c:\ant org.apache.tools.ant.launch.Launcher [options] [target]The first method runs Ant's traditional entry point. The second method uses the Ant Launcher introduced in Ant 1.6. The former method does not support the -lib option and all required classes are loaded from the CLASSPATH. You must ensure that all required jars are available. At a minimum the CLASSPATH should include:

ant.jar and ant-launcher.jar jars/classes for your XML parser the JDK's required jar/zip files

The latter method supports the -lib, -nouserlib, -noclasspath options and will load jars from the specified ANT_HOME. You should start the latter with the most minimal classpath possible!!!, generally just the ant-launcher.jar.

Ant can be started in Ant via the <java> command. Here is an example: <java classname="org.apache.tools.ant.launch.Launcher" fork="true" failonerror="true" dir="${sub.builddir}" timeout="4000000" taskname="startAnt"> <classpath> <pathelement location="${ant.home}/lib/ant-launcher.jar"/> </classpath> <arg value="-buildfile"/> <arg file="${sub.buildfile}"/> <arg value="-Dthis=this"/> <arg value="-Dthat=that"/> <arg value="-Dbasedir=${sub.builddir}"/> <arg value="-Dthe.other=the.other"/>

Page 18: Ant

<arg value="${sub.target}"/></java>

Overview of Ant TasksGiven the large number of tasks available with Ant, it may be difficult to get an overall view of what each task can do. The following tables provide a short description of each task and a link to the complete documentation.

Archive Tasks Task Name Description

BUnzip2 Expands a file packed using GZip or BZip2.

BZip2 Packs a file using the GZip or BZip2 algorithm. This task does not do any dependency checking; the output file is always generated

Cab Creates Microsoft CAB archive files. It is invoked similar to the Jar or Zip tasks. This task will work on Windows using the external cabarc tool (provided by Microsoft), which must be located in your executable path.

Ear An extension of the Jar task with special treatment for files that should end up in an Enterprise Application archive.

GUnzip Expands a GZip file.

GZip GZips a set of files.

Jar Jars a set of files.

Jlink Deprecated. Use the zipfileset and zipgroupfileset attributes of the Jar or Zip tasks instead.

Manifest Creates a manifest file.

Rpm Invokes the rpm executable to build a Linux installation file. This task currently only works on Linux or other Unix platforms with RPM support.

SignJar Signs a jar or zip file with the javasign command-line tool.

Tar Creates a tar archive.

Unjar Unzips a jarfile.

Untar Untars a tarfile.

Unwar Unzips a warfile.

Unzip Unzips a zipfile.

War An 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.

Zip Creates a zipfile.

Audit/Coverage Tasks Task Name Description

JDepend Invokes the JDepend parser. This parser "traverses a set of Java source-file directories and generates design-quality metrics for each Java package".

Compile Tasks Task Name Description

Depend Determines which classfiles are out-of-date with respect to their source, removing the classfiles of any other classes that depend on the out-of-date classes, forcing the re-compile of the removed classfiles. Typically used in conjunction with the Javac task.

Javac Compiles the specified source file(s) within the running (Ant) VM, or in another VM if the fork attribute is specified.

Apt Runs the annotation processor tool (apt), and then optionally compiles the original code, and any generated source code.

JspC Runs the JSP compiler. It can be used to precompile JSP pages for fast initial invocation of JSP pages, deployment on a server without the full JDK installed, or simply to syntax-check the pages without deploying them. The Javac task can be used to compile the generated Java source. (For Weblogic JSP compiles, see the Wljspc task.)

NetRexxC Compiles a NetRexx source tree within the running (Ant) VM.

Rmic Runs the rmic compiler on the specified file(s).

Wljspc Compiles JSP pages using Weblogic's JSP compiler, weblogic.jspc. (For non-Weblogic JSP compiles, see the JspC task.

Page 19: Ant

Deployment Tasks Task Name Description

ServerDeploy Task to run a "hot" deployment tool for vendor-specific J2EE server. Documentation Tasks

Task Name Description

Javadoc/ Javadoc2 Generates code documentation using the javadoc tool. The Javadoc2 task is deprecated; use the Javadoc task instead.

Stylebook Executes the Apache Stylebook documentation generator. Unlike the command-line version of this tool, all three arguments are required to run the Stylebook task.

EJB Tasks Task Name Description

EJB Tasks (See the documentation describing the EJB tasks.)

Execution Tasks Task Name Description

Ant Runs Ant on a supplied buildfile, optionally passing properties (with possibly new values). This task can be used to build sub-projects.

AntCall Runs another target within the same buildfile, optionally passing properties (with possibly new values).

Apply/ ExecOn Executes a system command. When the os attribute is specified, the command is only executed when Ant is run on one of the specified operating systems.

Dependset This task compares a set of source files with a set of target files. If any of the source files is newer than any of the target files, all the target files are removed.

Exec Executes a system command. When the os attribute is specified, the command is only executed when Ant is run on one of the specified operating systems.

Java Executes a Java class within the running (Ant) VM, or in another VM if the fork attribute is specified.

Parallel A container task that can contain other Ant tasks. Each nested task specified within the <parallel> tag will be executed in its own thread.

Sequential A container task that can contain other Ant tasks. The nested tasks are simply executed in sequence. Its primary use is to support the sequential execution of a subset of tasks within the <parallel> tag.

Sleep A task for suspending execution for a specified period of time. Useful when a build or deployment process requires an interval between tasks.

Subant Calls a given target for all defined sub-builds. This is an extension of ant for bulk project execution.

Waitfor Blocks execution until a set of specified conditions become true. This task is intended to be used with the Parallel task to synchronize a set of processes.

File Tasks

Task Name Description

Attrib Changes the permissions and/or attributes of a file or all files inside the specified directories. Currently, it has effect only under Windows.

Checksum Generates a checksum for a file or set of files. This task can also be used to perform checksum verifications.

Chgrp Changes the group ownership of a file or all files inside the specified directories. Currently, it has effect only under Unix.

Chmod Changes the permissions of a file or all files inside the specified directories. Currently, it has effect only under Unix. The permissions are also UNIX style, like the arguments for the chmod command.

Chown Changes the owner of a file or all files inside the specified directories. Currently, it has effect only under Unix.

Concat Concatenates multiple files into a single one or to Ant's logging system.

Copy Copies a file or Fileset to a new file or directory.

Copydir Deprecated. Use the Copy task instead.

Copyfile Deprecated. Use the Copy task instead.

Delete Deletes either a single file, all files and sub-directories in a specified directory, or a set of files specified by one or more FileSet s.

Page 20: Ant

Deltree Deprecated. Use the Delete task instead.

Filter Sets a token filter for this project, or reads multiple token filters from a specified file and sets these as filters. Token filters are used by all tasks that perform file-copying operations.

FixCRLF Modifies a file to add or remove tabs, carriage returns, linefeeds, and EOF characters.

Get Gets a file from a URL.

Mkdir Creates a directory. Non-existent parent directories are created, when necessary.

Move Moves a file to a new file or directory, or a set(s) of file(s) to a new directory.

Patch Applies a "diff" file to originals.

Rename Deprecated. Use the Move task instead.

RenameExtensions Deprecated. Use the Move task 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 Directory-based task for replacing the occurrence of a given regular expression with a substitution pattern in a file or set of files.

Sync Synchronize two directory trees.

Tempfile Generates a name for a new temporary file and sets the specified property to that name.

Touch Changes the modification time of a file and possibly creates it at the same time.

Java2 Extensions Tasks Task Name Description

Jarlib-available Check whether an extension is present in a FileSet or an ExtensionSet. If the extension is present, the specified property is set.

Jarlib-display Display the "Optional Package" and "Package Specification" information contained within the specified jars.

Jarlib-manifest Task to generate 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 Try to locate a jar to satisfy an extension, and place the location of the jar into the specified property.

Logging Tasks Task Name Description

Record Runs a listener that records the logging output of the build-process events to a file. Several recorders can exist at the same time. Each recorder is associated with a file.

Mail Tasks Task Name Description

Mail A task to send SMTP email.

MimeMail Deprecated. Use the Mail task instead.

Miscellaneous Tasks Task Name Description

Defaultexcludes Modify the list of default exclude patterns from within your build file.

Echo Echoes text to System.out or to a file!!!.Fail Exits the current build by throwing a BuildException, optionally printing additional information.

GenKey Generates a key in keystore.

Input Allows user interaction during the build process by displaying a message and reading a line of input from the console.

Script Executes a script in a Apache BSF-supported language.

Sound Plays a sound file at the end of the build, according to whether the build failed or succeeded.

Splash Displays a splash screen.

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.

Taskdef Adds a task definition to the current project, such that this new task can be used in the current project.

Page 21: Ant

TStamp Sets the DSTAMP, TSTAMP, and TODAY properties in the current project, based on the current date and time. <tstamp/> <echo> Today is ${TODAY} hour is ${TSTAMP}.</echo> Daca ar fi lipsit <tstamp/> atunci variab. de mai sus nu ar fi fost initializate =>:

Typedef Adds a data-type definition to the current project, such that this new type can be used in the current project.

XmlValidate Checks that XML files are valid (or only well-formed). This task uses the XML parser that is currently used by Ant by default, but any SAX1/2 parser can be specified, if needed.

.NET Tasks Task Name Description

.NET Tasks (See the documentation describing the .NET tasks.)

Pre-process Tasks Task Name Description

ANTLR Invokes the ANTLR Translator generator on a grammar file.

AntStructure Generates a DTD for Ant buildfiles that contains information about all tasks currently known to Ant.

Import Import another build file and potentially override targets in it with targets of your own.

JavaCC Invokes the JavaCC compiler-compiler on a grammar file.

Javah Generates JNI headers from a Java class.

JJDoc Invokes the JJDoc documentation generator for the JavaCC compiler-compiler. JJDoc takes a JavaCC parser specification and produces documentation for the BNF grammar. It can operate in three modes, determined by command line options. This task only invokes JJDoc if the grammar file is newer than the generated BNF grammar documentation.

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. This task only invokes JJTree if the grammar file is newer than the generated JavaCC file.

Macrodef Define a new task as a macro built-up upon other tasks.

Native2Ascii Converts files from native encodings to ASCII with escaped Unicode. A common usage is to convert source files maintained in a native operating system encoding to ASCII, prior to compilation.

Presetdef Define a new task by instrumenting an existing task with default values for attributes or child elements.

Translate Identifies keys in files, delimited by special tokens, and translates them with values read from resource bundles.

XSLT Processes a set of documents via XSLT. VEZI SI XmlVALIDATE mai sus.

Property Tasks Task Name Description

Available Sets a property if a specified file, directory, class in the classpath, or JVM system resource is available at runtime.

Basename Sets a property to the last element of a specified path.

BuildNumber Task that can be used to track build numbers.

Condition Sets a property if a certain condition holds true; this is a generalization of Available and Uptodate.

Dirname Sets a property to the value of the specified file up to, but not including, the last path element.

Echoproperties Lists the current properties.

LoadFile Loads a file into a property.

LoadProperties Load a file's contents as Ant properties. This task is equivalent to using <property file="..."/> except that it supports nested <filterchain> elements, and it cannot be specified outside a target.

MakeURL Creates a URL (list) from a file/fileset or path

PathConvert Converts a nested path, path reference, filelist reference, or fileset reference to the form usable on a specified

Page 22: Ant

platform and/or to a list of items separated by the specified separator and stores the result in the specified property.

Property Sets a property (by name and value), or set of properties (from a file or resource) in the project.

PropertyFile Creates or modifies property files. Useful when wanting to make unattended modifications to configuration files for application servers and applications. Typically used for things such as automatically generating a build number and saving it to a build properties file, or doing date manipulation.

Uptodate Sets a property if a given target file is newer than a set of source files.

Whichresource Find a class or resource.

XmlProperty Loads property values from a well-formed XML file.

Remote Tasks Task Name Description

FTP Implements a basic FTP client that can send, receive, list, and delete files, and create directories.

Rexec Task to automate a remote rexec session.

Scp Copy files to or from a remote server using SSH.

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.

Sshexec Execute a command on a remote server using SSH.

Telnet Task to automate a remote telnet session. This task uses nested <read> and <write> tags to indicate strings to wait for and specify text to send.

SCM Tasks Task Name Description

Cvs Handles packages/modules retrieved from a CVS repository.

CvsChangeLog Generates an XML report of the changes recorded in 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.

ClearCase Tasks to perform the ClearCase cleartool checkin, checkout, uncheckout, update, lock, unlock, mklbtype, rmtype, mklabel, mkattr, mkdir, mkelem, and mkbl commands.

Continuus/Synergy Tasks to perform the Continuus ccmcheckin, ccmcheckout, ccmcheckintask, ccmreconfigure, and ccmcreateTask commands.

Microsoft Visual SourceSafe

Tasks to perform the Visual SourceSafe vssget, vsslabel, vsshistory, vsscheckin, vsscheckout, vssadd, vsscp, and vsscreate commands.

Perforce Tasks to perform the Perforce p4sync, p4change, p4edit, p4submit, p4have, p4label, p4counter, p4reopen, p4revert, and p4add commands.

Pvcs Allows the user extract the latest edition of the source code from a PVCS repository.

SourceOffSite Tasks to perform the SourceOffSite sosget, soslabel, soscheckin, and soscheckout commands.

StarTeam Tasks to perform the StarTeam stcheckout, stcheckin, stlabel, and stlist commands. The Starteam task is deprecated; use STCheckout instead.

Testing Tasks Task Name Description

Junit Runs tests from the Junit testing framework. This task has been tested with JUnit 3.0 up to JUnit 3.7; it won't work with versions prior to JUnit 3.0.

JunitReport Merges the individual XML files generated by the Junit task and applies a stylesheet on the resulting merged document to provide a browsable report of the testcases results.

Page 23: Ant

OthersImage, SchemaValidate, Scriptdef, Symlink.

Some of the core tasksAntRuns 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. When the antfile attribute is omitted, the file "build.xml" in the supplied directory ( dir attribute) is used. If no target attribute is supplied, the default target of the new project(cel din fisierul de rulat) is used.By default, all of the properties of the current project will be available in the new project. Alternatively, you can set the inheritAll attribute to false and only "user" properties (i.e., those passed on the command-line) will be passed to the new project. In either case, the set of properties passed to the new project will override the properties that are set in the new project (See also the property task).

You can also set properties in the new project from the old project by using nested property tags. These properties are always passed to the new project and any project created in that project regardless of the setting of inheritAll . This allows you to parameterize your subprojects. Properties defined on the command line cannot be overridden by nested <property> elements.

References to data types can also be passed to the new project, but by default they are not. If you set the inheritrefs attribute to true, all references will be copied, but they will not override references defined in the new project.Nested <reference> elements can also be used to copy references from the calling project to the new project, optionally under a different id. References taken

from nested elements will override existing references that have been defined outside of targets in the new project - but not those defined inside of targets!!!.

ParametersAttribute Description Required

antfile the buildfile to use. Defaults to "build.xml". This file is expected to be a filename relative to the dir attribute given. No

dir the directory to use as a basedir for the new Ant project. Defaults to the current project's basedir, unless inheritall has been set to false, in which case it doesn't have a default value. This will override the basedir setting of the called project.

No

target the target of the new Ant project that should be executed. Defaults to the new project's default target. No

output Filename to write the ant output to. This is relative to the value of the dir attribute if it has been set or to the base directory of the current project otherwise.

No

inheritAll If true, pass all properties to the new Ant project. Defaults to true. No

inheritRefs If true, pass all references to the new Ant project. Defaults to false. No

Parameters specified as nested elementspropertySee the description of the property task.

These properties become equivalent to properties you define on the command line. These are special properties and they will always get passed down, even through additional <*ant*> tasks with inheritall set to false (see above). Note that the refid attribute points to a reference in the calling project, not in the new one.reference

Used to choose references that shall be copied into the new project, optionally changing their id.Attribute Description Required

refid The id of the reference in the calling project. Yes

torefid The id of the reference in the new project. No, defaults to the value of refid.

propertysetYou can specify a set of properties to be copied into the new project with propertysets.since Ant 1.6.target

You can specify multiple targets using nested <target> elements instead of using the target attribute. These will be executed as if Ant had been invoked with a single target whose dependencies are the targets so specified, in the order specified.Attribute Description Required

name The name of the called target. Yes

since Ant 1.6.3.Basedir of the new project

The basedir value of the new project is affected by the two attributes dir and inheritall, see the following table for details:dir attribute inheritAll attribute new project's basedir

Page 24: Ant

value provided true value of dir attribute

value provided false value of dir attribute

omitted true basedir of calling project (the one whose build file contains the <ant> task).

omitted false basedir attribute of the <project> element of the new project

Examples<ant antfile="subproject/subbuild.xml" target="compile"/>

<ant dir="subproject"/>

<ant antfile="subproject/property_based_subbuild.xml"> <property name="param1" value="version 1.x"/> <property file="config/subproject/default.properties"/></ant>

<ant inheritAll="false" antfile="subproject/subbuild.xml"> <property name="output.type" value="html"/></ant>These lines invoke the same build file:<ant antfile="sub1/sub2/build.xml" /><ant antfile="sub2/build.xml" dir="sub1" /><ant antfile="build.xml" dir="sub1/sub2" />The build file of the calling project defines some <path> elements like this:<path id="path1"> ...</path><path id="path2"> ...</path>and the called build file (subbuild.xml) also defines a <path> with the id path1, but path2 is not defined:<ant antfile="subbuild.xml" inheritrefs="true"/>

will not(ca si in Java mostenirea nu overwrite-uie) override subbuild's definition of path1, but make the parent's definition of path2 available in the subbuild!!!.<ant antfile="subbuild.xml"/>as well as<ant antfile="subbuild.xml" inheritrefs="false"/>

will neither override path1 nor copy path2 pentru ca nu specific referinte prin care sa pasez(ca si in Java).<ant antfile="subbuild.xml" inheritrefs="false"> <reference refid="path1"/></ant>will override subbuild's definition of path1.<ant antfile="subbuild.xml" inheritrefs="false"> <reference refid="path1" torefid="path2"/></ant>

will copy the parent's definition of path1 into the new project using the id path2.

AntCallCall another target within the same buildfile optionally specifying some properties (params in this context). This task must not be used outside of a target.By default, all of the properties of the current project will be available in the new project. Alternatively, you can set

the inheritAll attribute to false and only "user" properties (i.e., those passed on the command-line) will be passed to the new project. In either case, the set of properties passed to the new project will override the properties that are set in the new project (See also the property task).

You can also set properties in the new project from the old project by using nested param tags. These properties are always passed to the new project and any project created in that project regardless of the setting of inheritAll. This allows you to parameterize your subprojects. Properties defined on the command line can not be overridden by nested <param> elements.

Nested <reference> ; elements can be used to copy references from the calling project to the new project, optionally under a different id. References taken from nested elements will override existing references that have been defined outside of targets in the new project - but not those defined inside of targets.

When a target is invoked by antcall, all of its dependent targets will also be called!!! within the context of any new parameters. For example. if the target "doSomethingElse" depended on the target "init", then the antcall of "doSomethingElse" will call "init" during the call. Of course, any properties defined in the antcall task or inherited from the calling target will be fixed and not overridable in the init task --or indeed in the "doSomethingElse" task. If the build file changes after you've started the build, the behavior of this task is undefined.

Page 25: Ant

ParametersAttribute Description Required

target The target to execute. Yes

inheritAll If true, pass all properties to the new Ant project. Defaults to true. No

inheritRefs If true, pass all references to the new Ant project. Defaults to false. No

Note on inheritRefs<antcall> will not override existing references, even if you set inheritRefs to true. As the called build files is the same build file as the calling one, this

means it will not override any reference set via an id attribute at all. The only references that can be inherited by the child project are those defined by nested <reference> elements or references defined by tasks directly (not using the id attribute).Parameters specified as nested elements

paramSpecifies the properties to set before running the specified target. See property for usage guidelines.These properties become equivalent to properties you define on the command line . These are special properties and they will always get passed down, even through additional <*ant*> tasks with inheritall set to false (see above). reference

Used to choose references that shall be copied into the new project, optionally changing their id.Attribute Description Required

Refid The id of the reference in the calling project. Yes

Torefid The id of the reference in the new project. No, defaults to the value of refid.

propertysetYou can specify a set of properties to be copied into the new project with propertysets.since Ant 1.6.targetYou can specify multiple targets using nested <target> elements. These will be executed as if Ant had been invoked with a single target whose dependencies are the targets so specified, in the order specified.Attribute Description Required

Name The name of the called target. Yes

since Ant 1.6.3.Examples<target name="default"> <antcall target="doSomethingElse"> <param name="param1" value="value"/> </antcall></target><target name="doSomethingElse"> <echo message="param1=${param1}"/></target>Will run the target 'doSomethingElse' and echo 'param1=value'.<antcall ... > <reference refid="path1" torefid="path2"/></antcall>

will copy the parent's definition of path1 into the new project using the id path2.

Page 26: Ant

Obs:

Cu echo poti scrie si intr-un fisier.

Concepts and Typesant.build.clonevmSince Ant 1.7The value of the ant.build.clonevm system property controls how Ant instruments forked Java Virtual Machines. The java and junit tasks support clonevm attributes to control the VMs on a task-by-task basis while the system property applies to all forked Java VMs.If the value of the property is true, then all system properties of the forked Java Virtual Machine will be the same as those of the Java VM running Ant. In addition, if you set ant.build.clonevm to true and build.sysclasspath has not been set, the bootclasspath of forked Java VMs gets constructed as if build.sysclasspath had the value "last".Note that this has to be a system property, so it cannot be specified on the Ant command line. Use the ANT_OPTS environment variable instead.

build.sysclasspathThe value of the build.sysclasspath property control how the system classpath, ie. the classpath in effect when Ant is run, affects the behaviour of classpaths in Ant. The default behavior varies from Ant to Ant task.

The values and their meanings are: only Only the system classpath is used and classpaths specified in build files, etc are ignored. This situation could be considered as the person running

the build file knows more about the environment than the person writing the build file ignore The system classpath is ignored. This situation is the reverse of the above. The person running the build trusts the build file writer to get the build file

right last The classpath is concatenated to any specified classpaths at the end. This is a compromise, where the build file writer has priority. first Any specified classpaths are concatenated to the system classpath. This is the other form of compromise where the build runner has priority.

Since Ant 1.7 the value of this property also affects the bootclasspath settings--it combines the bootclasspath that has been specified for a task with the bootclasspath of the Java VM running Ant. If the property has not been set, it defaults to "ignore" in this case.

Ant properties controlling javacThe source and target attributes of <javac> don't have any default values for historical reasons. Since the underlying javac compiler's default depends on the JDK you use, you may encounter build files that don't explicitly set those attributes and that will no longer compile using a newer JDK. If you cannot change the build file, Ant provides two properties that help you setting default values for these attributes. If the attributes have been set explicitly, the properties listed here will be ignored.ant.build.javac.source Since Ant 1.7Provides a default value for <javac>'s and <javadoc>'s source attribute.ant.build.javac.target Since Ant 1.7Provides a default value for <javac>'s target attribute.

Common Attributes of all TasksAll tasks share the following attributes:Attribute Description Required

id Unique identifier for this task instance, can be used to reference this task in scripts. No

taskname A different name for this task instance - will show up in the logging output!!!. No

description Room for your comments!!! No

ResourcesA file-like entity can be abstracted to the concept of a resource . In addition to providing access to file-like attributes, a resource implementation should, when possible, provide the means to read content from and/or write content to the underlying entity. Resources are available for explicit use beginning in Ant 1.7. The built-in resource types are:

resource - a basic resource, bzip2resource - a BZip2 compressed resource, file - a file, gzipresource - a GZip compressed resource, javaresource - a resource loadable via a Java classloader, propertyresource - an Ant property, string - a text string, tarentry - an entry in a tar file, url - a URL, zipentry - an entry in a zip file.

resourceA basic resource. Other resource types derive from this basic type; as such all its attributes are available, though in most cases irrelevant attributes will

be ignored. This and all resource implementations are also usable as single-element Resource Collections . Attribute Description Required

name The name of this resource No

exists Whether this resource exists No, default true

lastmodified The last modification time of this resource No

directory Whether this resource is directory-like No, default false

Page 27: Ant

size The size of this resource No

fileRepresents a file accessible via local filesystem conventions.Attribute Description Required

file The file represented by this resource Yes

basedir The base directory of this resource. When this attribute is set, attempts to access the name of the resource

will yield a path relative to this location.No

javaresourceRepresents a resource loadable via a Java classloader.Attribute Description Required

name The name of the resource. Yes

classpath the classpath to use when looking up a resource. No

classpathref the classpath to use when looking up a resource, given as reference to a <path> defined elsewhere.

No

loaderRef the name of the loader that is used to load the resource, constructed from the specified classpath. No

The classpath can also be specified as nested classpath element, where <classpath> is a path-like structure.zipentryRepresents an entry in a ZIP archive. The archive can be specified using the archive attribute or a nested single-element resource collection.

zipentry only supports file system resources as nested elements.Attribute Description Required

zipfile or its alias name archive The zip file containing this resource Yes, unless a nested resource collection has been specified.

name The name of the archived resource Yes

encoding The encoding of the zipfile No; platform default used if unspecified

tarentryRepresents an entry in a TAR archive. The archive can be specified using the archive attribute or a nested single-element resource collection.Attribute Description Required

archive The tar archive containing this resource Yes, unless a nested resource collection has been specified.

name The name of the archived resource Yes

gzipresourceThis is not a stand-alone resource, but a wrapper around another resource providing compression of the resource's contents on the fly. A single element resource collection must be specified as a nested element.bzip2resourceThis is not a stand-alone resource, but a wrapper around another resource providing compression of the resource's contents on the fly. A single element resource collection must be specified as a nested element.

urlRepresents a URL.Attribute Description Required

url The url to exposeExactly one of these

file The file to expose as a file: url

stringRepresents a Java String!!!. It can be written to, but only once, after which it will be an error to write to again.Attribute Description Required

value The value of this resource No

The resource also supports nested text, which can only be supplied if the value attribute is unset:

<string> self.log("Ant version =${ant.version}"); </string>propertyresourceRepresents an Ant property.Attribute Description Required

name The property name Yes

Resource Collections

Page 28: Ant

A Resource Collection is an abstraction of an entity that groups together a number of resources. Several of Ant's "legacy" datatypes have been modified to behave as Resource Collections:

fileset , dirset, filelist, and path (and derivative types) expose file resources tarfileset can expose file or tarentry resources depending on configuration zipfileset can expose file or zipentry resources depending on configuration propertyset exposes property resources

Strangely, some tasks can even legitimately behave as resource collections: concat exposes a concatenated resource, and adds e.g. filtering to Ant's resource-related capabilities.

The additional built-in resource collections are: resources - generic resource collection.

files - collection of files similar to fileset. restrict - restrict a resource collection to include only resources meeting specified criteria. sort - sorted resource collection. first - first n resources from a nested collection. last - last n resources from a nested collection. tokens - string tokens gathered from a nested collection. union - set union of nested resource collections. intersect - set intersection of nested resource collections. difference - set difference of nested resource collections.

resourcesA generic resource collection, designed for use with references. For example, if a third-party Ant task generates a Resource Collection of an unknown type, it can still be accessed via a <resources> collection. The secondary use of this collection type is as a container of other resource collections, preserving the order of nested collections as well as duplicate resources (contrast with union).

filesA group of files. These files are matched by absolute patterns taken from a number of PatternSets. These can be specified as nested <patternset> elements. In addition, <files> holds an implicit PatternSet and supports the nested <include> , <includesfile> , <exclude> and <excludesfile> elements of PatternSet directly, as well as PatternSet's attributes.

File Selectors are available as nested elements. A file must be selected by all selectors in order to be included; <files> is thus equivalent to an <and> file selector container.

More simply put, this type is equivalent to a fileset with no base directory!!!. ATENTIE: Without a base directory , filesystem scanning is based entirely on include and exclude patterns . A filename (or any) selector can only influence the scanning process after the file has been included based on pattern-based selection. Attribute Description Required

includes comma- or space-separated list of patterns of files that must be includedAt least one of these

includesfile the name of a file; each line of this file is taken to be an include pattern.

excludes comma- or space-separated list of patterns of files that must be excluded No, default none (except default excludes when true)excludesfile the name of a file; each line of this file is taken to be an exclude pattern.

defaultexcludes Whether default excludes should be used No, default true

casesensitive Whether patterns are case-sensitive No, default true

followsymlinks Whether to follow symbolic links (see note below) No, default true

Note: All files/directories for which the canonical path is different from its path are considered symbolic links. On Unix systems this usually means the file really is a symbolic link but it may lead to false results on other platforms.

restrictRestricts a nested resource collection using resource selectors: Attribute Description Required

cache Whether to cache results; disabling may seriously impact performance No, default true

Parameters specified as nested elements(ADICA SUNT NISTE PARAMETRII SPECIFICATI CA NESTED ELEMENTS din cauza ca pot avea copii.)A single resource collection is required.

Page 29: Ant

Nested resource selectors are used to "narrow down" the included resources. These are patterned after file selectors but are, unsurprisingly, targeted to resources. Several built-in resource selectors are available in the internal antlib org.apache.tools.ant.types.resources.selectors:

name - select resources by name. exists - select existing resources. date - select resources by date. type - select resources by type. size - select resources by size. instanceof - select resources by class or Ant datatype. and - "and" nested resource selectors. or - "or" nested resource selectors. not - "not" a nested resource selector. none - select resources selected by no nested resource selectors. majority - select resources selected by a majority of nested resource selectors. modified - select resources which content has changed. contains - select resources containing a particular text string. containsregexp - select resources whose contents match a particular regular expression. compare - select resources based on comparison to other resources.

nameSelects resources by name.Attribute Description Required

name The name pattern to test Yes

casesensitive Whether name comparisons are case-sensitive No, default true

existsSelects existing resources.dateSelects resources by date.Attribute Description Required

millis The comparison date/time in ms since January 1, 1970One of these

datetime The formatted comparison date/time

pattern SimpleDateFormat-compatible pattern for use with the datetime attribute No, default is "MM/DD/YYYY HH:MM AM_or_PM"

granularity The number of milliseconds leeway to use when comparing file modification times. This is needed because not every file system supports tracking the last modified time to the millisecond level.

No; default varies by platform: FAT filesystems = 2 sec; Unix = 1 sec; NTFS = 1

ms.

when One of "before", "after", "equal" No, default "equal"

typeSelects resources by type (file or directory).Attribute Description Required

type One of "file", "dir" Yes

sizeSelects resources by size.Attribute Description Required

size The size to compare Yes

when One of "equal", "eq", "greater", "gt", "less", "lt", "ge" (greater or equal), "ne" (not equal), "le" (less or equal)

No, default "equal"

instanceofSelects resources by type.Attribute Description Required

class The class of which the resource must be an instance One of thesetype The Ant type that must be assignable from the resource

uri The uri in which type must be defined No

and

Selects a resource if it is selected by all nested resource selectors!!!.orSelects a resource if it is selected by at least one nested resource selector.

Page 30: Ant

notNegates the selection result of the single nested resource selector allowed.noneSelects a resource if it is selected by no nested resource selectors.majoritySelects a resource if it is selected by the majority of nested resource selectors.Attribute Description Required

allowtie Whether a tie (when there is an even number of nested resource selectors) is considered a majority No, default true

compareSelects a resource based on its comparison to one or more "control" resources using nested resource comparators .Attribute Description Required

when Comparison ("equal"/"eq", "greater"/"gt", "less"/"lt", "le" (less or equal), "ge" (greater or equal), "ne" (not equal).

No, default "equal"

against Quantifier ("all"/"each"/"every", "any"/"some", (exactly) "one", "most"/"majority", "none". No, default "all"

Parameters specified as nested elementsThe resources against which comparisons will be made must be specified using the nested <control> element, which denotes a resources collection.

ExamplesAssuming the namespace settings rsel="antlib:org.apache.tools.ant.types.resources.selectors" rcmp="antlib:org.apache.tools.ant.types.resources.comparators"

The following selects files a, b, c, and d:<restrict> <fileset dir="src" includes="a,b,c,d,e,f,g" /> <rsel:compare when="le" against="all"> <control> <resource name="d" /> </control> <rcmp:name /> </rsel:compare></restrict>

sortSorts a nested resource collection according to the resources' natural order, or by one or more nested resource comparators:Attribute Description Required

cache Whether to cache results; disabling may seriously impact performance No, default true

Parameters specified as nested elementsA single resource collection is required.The sort can be controlled and customized by specifying one or more resource comparators. Resources can be sorted according to multiple criteria; the first specified is the "outermost", while the last specified is the "innermost". Several built-in resource comparators are available in the internal antlib org.apache.tools.ant.types.resources.comparators: Resource Comparators:

name - sort resources by name exists - sort resources by existence date - sort resources by date type - sort resources by type size - sort resources by size content - sort resources by content reverse - reverse the natural sort order, or that of a single nested resource comparator

nameSort resources by name.existsSort resources by existence. Not existing is considered "less than" existing.dateSort resources by date.typeSort resources by type (file or directory). Because directories contain files, they are considered "greater".sizeSort resources by size.content

Sort resources by content.

Page 31: Ant

Attribute Description Required

binary Whether content should be compared in binary mode. If false, content will be compared without regard to platform-specific line-ending conventions.

No, default true

reverseReverse the natural sort order, or that of a single nested comparator.

Examples <property name="eol" value="${line.separator}"/> <pathconvert property="sorted" pathsep="${eol}"> <sort> <tokens> <string value="foo bar etc baz" /> <stringtokenizer /> </tokens> </sort> </pathconvert>

The resource of type string "foo bar etc baz" is split into four tokens by the stringtokenizer. These tokens are sorted and there sorted gets the value of "bar baz etc foo". <sort> <fileset dir="foo" /> <reverse xmlns="antlib:org.apache.tools.ant.types.resources.

comparators"> <date /> </reverse> </sort>

This takes all files from foo and sorts them by modification date in reverse order. Because the resource

comparators used (<reverse> and <date>) are in an internal antlib their namespace must be set explicitly.

firstIncludes the first count resources from a nested resource collection. This can be used in conjunction with the sort collection, for example, to select the first few oldest, largest, etc. resources from a larger collection.Attribute Description Required

count The number of resources to include No, default 1

cache Whether to cache results; disabling may seriously impact performance No, default true

Parameters specified as nested elementsA single resource collection is required.

lastIncludes the last count resources from a nested resource collection. This can be used in conjunction with the sort collection, for example, to select the

last few oldest, largest, etc. resources from a larger collection. Since Ant 1.7.1.Attribute Description Required

count The number of resources to include No, default 1

cache Whether to cache results; disabling may seriously impact performance No, default true

Parameters specified as nested elementsA single resource collection is required.

tokensIncludes the string tokens gathered from a nested resource collection. Uses the same tokenizers supported by the TokenFilter . Hint: imaginative use of this resource collection can implement equivalents for such Unix functions as sort , grep -c , wc and wc -l .

Attribute Description Required

encoding The encoding of the nested resources No, default is platform default

cache Whether to cache results; disabling may seriously impact performance No, default true

Parameters specified as nested elements A single resource collection is required. One nested tokenizer may be specified. If omitted, a LineTokenizer will be used.

Set operationsThe following resource collections implement set operations:

union intersect difference

Page 32: Ant

unionUnion of nested resource collections.

intersectIntersection of nested resource collections.

differenceDifference of nested resource collections.The following attributes apply to all set-operation resource collections: Attribute Description Required

cache Whether to cache results; disabling may seriously impact performance No, default true

FileSetA FileSet is a group of files. These files can be found in a directory tree starting in a base directory and are matched by patterns taken from a number of PatternSets and Selectors .

PatternSets can be specified as nested <patternset> elements. In addition, FileSet holds an implicit PatternSet and supports the nested <include> , <includesfile> , <exclude> and <excludesfile> elements of PatternSet directly, as well as PatternSet's attributes.Selectors are available as nested elements within the FileSet. If any of the selectors within the FileSet do not select the file, the file is not considered part of the FileSet. This makes a FileSet equivalent to an <and> selector container(de aceea se poate folosii in exemplul de mai jos spre exemplu <not>).

Attribute Description Required

dir the root of the directory tree of this FileSet. Either dir or file must be specifiedfile shortcut for specifying a single-file fileset

defaultexcludes indicates whether default excludes should be used or not (yes | no); default excludes are used when omitted.

No

includes comma- or space-separated list of patterns of files that must be included; all files are included when omitted.

No

includesfile the name of a file; each line of this file is taken to be an include pattern. No

excludes comma- or space-separated list of patterns of files that must be excluded; no files (except default excludes) are excluded when omitted.

No

excludesfile the name of a file; each line of this file is taken to be an exclude pattern. No

casesensitive Must the include and exclude patterns be treated in a case sensitive way? Defaults to true.

No

followsymlinks Shall symbolic links be followed? Defaults to true. See the note below. No

erroronmissingdir Specify what happens if the base directory does not exist. If true a build error will happen, if false, the fileset will be ignored/empty. Defaults to true. Since Ant 1.7.1 (default is true for backward compatibility reasons.)

No

Note: All files/directories for which the canonical path is different from its path are considered symbolic links. On Unix systems this usually means the file really is a symbolic link but it may lead to false results on other platforms.Examples

** merge in adancime pe fisierele din tree!!!<fileset dir="${server.src}" casesensitive="yes"> <include name="**/*.java"/> <exclude name="**/*Test*"/></fileset>

Groups all files in directory ${server.src} that are Java source files and don't have the text Test in their name.<fileset dir="${server.src}" casesensitive="yes"> <patternset id="non.test.sources"> <!--In acest caz am un pattern explicit nu cel default.--> <include name="**/*.java"/> <exclude name="**/*Test*"/> </patternset></fileset>

Groups the same files as the above example, but also establishes a PatternSet that can be referenced in other <fileset> elements, rooted at a different directory.<fileset dir="${client.src}" > <patternset refid="non.test.sources"/></fileset>

Groups all files in directory ${client.src}, using the same patterns as the above example.

Page 33: Ant

<fileset dir="${server.src}" casesensitive="yes"> <filename name="**/*.java"/> <filename name="**/*Test*" negate="true"/></fileset>

Groups the same files as the top example, but using the <filename> selector.<fileset dir="${server.src}" casesensitive="yes"> <filename name="**/*.java"/> <not> <filename name="**/*Test*"/> </not></fileset>

Groups the same files as the previous example using a combination of the <filename> selector and the <not> selector container.<fileset dir="src" includes="main/" />

Selects all files in src/main (e.g. src/main/Foo.java or src/main/application/Bar.java).

DirSetA DirSet is a group of directories. These directories can be found in a directory tree starting in a base directory and are matched by patterns taken from a number of PatternSets and Selectors. PatternSets can be specified as nested <patternset> elements. In addition, DirSet holds an implicit PatternSet and supports the nested <include>, <includesfile>, <exclude> and <excludesfile> elements of <patternset> directly, as well as <patternset>'s attributes.Selectors are available as nested elements within the DirSet. If any of the selectors within the DirSet do not select the directory, it is not considered part of the DirSet. This makes a DirSet equivalent to an <and> selector container.Attribute Description Required

dir The root of the directory tree of this DirSet. Yes

includes A comma- or space-separated list of patterns of directories that must be included; all directories are included when omitted.

No

includesfile The name of a file; each line of this file is taken to be an include pattern. No

excludes A comma- or space-separated list of patterns of directories that must be excluded; no directories are excluded when omitted.

No

excludesfile The name of a file; each line of this file is taken to be an exclude pattern. No

casesensitive Specifies whether case-sensitivity should be applied (true|yes|on or false|no|off). No; defaults to true.

followsymlinks Shall symbolic links be followed? Defaults to true. See fileset's documentation. No

Examples<dirset dir="${build.dir}"> <include name="apps/**/classes"/> <exclude name="apps/**/*Test*"/></dirset>

Groups all directories named classes found under the apps subdirectory of ${build.dir}, except those that have the text Test in their name.<dirset dir="${build.dir}"> <patternset id="non.test.classes"> <include name="apps/**/classes"/> <exclude name="apps/**/*Test*"/> </patternset></dirset>Groups the same directories as the above example, but also establishes a PatternSet that can be referenced in other <dirset> elements, rooted at a different directory.<dirset dir="${debug_build.dir}"> <patternset refid="non.test.classes"/></dirset>

Groups all directories in directory ${debug_build.dir}, using the same patterns as the above example.

FileListFileLists are explicitly named lists of files. Whereas FileSets act as filters, returning only those files that exist in the file system and match specified patterns, FileLists are useful for specifying files that may or may not exist. Multiple files are specified as a list of files, relative to the specified directory, with no support for wildcard expansion (filenames with wildcards will be included in the list unchanged). FileLists can appear inside tasks that support this feature or as stand-alone types.

Page 34: Ant

Attribute Description Required

dir The base directory of this FileList. Yes

files The list of file names. This is a list of file name separated by whitespace, or by commas.

Yes, unless there is a nested file element

Nested Element: <file>This represents a file name. The nested element allows filenames containing white space and commas. Since Ant 1.6.2

Attribute Description Required

name The name of the file. Yes

Examples<filelist id="docfiles" dir="${doc.src}" files="foo.xml,bar.xml"/>

The files ${doc.src}/foo.xml and ${doc.src}/bar.xml. Note that these files may not (yet) actually exist. <filelist id="docfiles" dir="${doc.src}" files="foo.xml bar.xml"/>

Same files as the example above.<filelist refid="docfiles"/>

Same files as the example above.<filelist id="docfiles" dir="${doc.src}"> <file name="foo.xml"/> <file name="bar.xml"/></filelist>

Same files as the example above.

PatternSetPatterns can be grouped to sets and later be referenced by their id attribute. They are defined via a patternset

element, which can appear nested into a FileSet!!! or a directory-based task that constitutes an implicit FileSet. In

addition, patternsets can be defined as a stand alone element at the SAME LEVEL as target — i.e., as children of project as well as as children of target.Patterns can be specified by nested <include>, or <exclude> elements or the following attributes.Attribute Description

includes comma- or space-separated list of patterns of files that must be included. All files are included when omitted.

includesfile the name of a file; each line of this file is taken to be an include pattern. You can specify more than one include file by using a nested includesfile elements.

excludes comma- or space-separated list of patterns of files that must be excluded; no files (except default excludes) are excluded when omitted.

excludesfile the name of a file; each line of this file is taken to be an exclude pattern. You can specify more than one exclude file by using a nested excludesfile elements.

Parameters specified as nested elementsinclude and excludeEach such element defines a single pattern for files to include or exclude.Attribute Description Required

name the pattern to in/exclude. Yes

if Only use this pattern if the named property is set. No

unless Only use this pattern if the named property is not set. No

includesfile and excludesfileIf you want to list the files to include or exclude external to your build file , you should use the includesfile/ excludesfile attributes or elements. Using the attribute, you can only specify a single file of each type , while the nested elements can be specified more than once - the nested elements also support if/unless attributes you can use to test the existance of a property.Attribute Description Required

name the name of the file holding the patterns to in/exclude. Yes

if Only read this file if the named property is set. No

unless Only read this file if the named property is not set. No

Page 35: Ant

patternsetPatternsets may be nested within one another, adding the nested patterns to the parent patternset.invertA nested patternset can be inverted using the <invert> element. Since Ant 1.7.1

Examples<patternset id="non.test.sources"> <include name="**/*.java"/> <exclude name="**/*Test*"/></patternset>

Builds a set of patterns that matches all .java files that do not contain the text Test in their name . This set can be referred to via <patternset refid="non.test.sources"/>, by tasks that support this feature, or by FileSets.

Note that while the includes and excludes attributes accept multiple elements separated by commas or spaces, the nested <include> and <exclude> elements expect their name attribute to hold a single pattern. The nested elements allow you to use if and unless arguments to specify that the element should only be used if a property is set, or that it should be used only if a property is not set. For example:<patternset id="sources"> <include name="std/**/*.java"/> <include name="prof/**/*.java" if="professional"/> <exclude name="**/*Test*"/></patternset>

will only include the files in the sub-directory prof if the property professional is set to some value.The two sets<patternset includesfile="some-file"/>

and<patternset> <includesfile name="some-file"/> <patternset/>

are identical. The include patterns will be read from the file some-file, one pattern per line!!!.<patternset> <includesfile name="some-file"/> <includesfile name="${some-other-file}" if="some-other-file"/> <patternset/>

will also read include patterns from the file the property some-other-file points to, if a property of that name has been defined.

SelectorsSelectors are a mechanism whereby the files that make up a <fileset> can be selected based on criteria other than filename as provided by the <include> and <exclude> tags.

How to use a SelectorA selector is an element of FileSet, and appears within it. It can also be defined outside of any target by using the <selector> tag and then using it as a reference. Different selectors have different attributes. Some selectors can contain other selectors, and these are called Selector Containers. There is also a category of selectors that allow user-defined extensions, called Custom Selectors. The ones built in to Ant are called Core Selectors.

Core SelectorsCore selectors are the ones that come standard with Ant. They can be used within a fileset and can be contained within Selector Containers.The core selectors are:

<contains> - Select files that contain a particular text string <date> - Select files that have been modified either before or after a particular date and time <depend> - Select files that have been modified more recently than equivalent files elsewhere <depth> - Select files that appear so many directories down in a directory tree <different> - Select files that are different from those elsewhere <filename> - Select files whose name matches a particular pattern. Equivalent to the include and exclude

elements of a patternset. <present> - Select files that either do or do not exist in some other location < containsregexp > - Select files that match a regular expression <size> - Select files that are larger or smaller than a particular number of bytes. <type> - Select files that are either regular files or directories. <modified> - Select files if the return value of the configured algorithm is different from that stored in a cache. <signedselector> - Select files if they are signed, and optionally if they have a signature of a certain name.

Page 36: Ant

<scriptselector> - Use a BSF or JSR 223 scripting language to create your own selector Contains SelectorThe <contains> tag in a FileSet limits the files defined by that fileset to only those which contain the string specified by the text attribute. .The <contains> selector can be used as a ResourceSelector (see the <restrict> ResourceCollection).

Attribute Description Required

text Specifies the text that every file must contain Yes

casesensitive Whether to pay attention to case when looking for the string in the text attribute. Default is true. No

ignorewhitespace Whether to eliminate whitespace before checking for the string in the text attribute. Default is false. No

Here is an example of how to use the Contains Selector:<fileset dir="${doc.path}" includes="**/*.html"> <contains text="script" casesensitive="no"/></fileset>Selects all the HTML files that contain the string script.Date Selector

The <date> tag in a FileSet will put a limit on the files specified by the include tag, so that tags whose last modified date does not meet the date limits specified by the selector will not end up being selected.Attribute Description Required

datetime Specifies the date and time to test for. Should be in the format MM/DD/YYYY HH:MM AM_or_PM, or an alternative pattern specified via the pattern attribute.

At least one of the two.

millis The number of milliseconds since 1970 that should be tested for. It is usually much easier to use the datetime attribute.

when Indicates how to interpret the date, whether the files to be selected are those whose last modified times should be before, after, or equal to the specified value. Acceptable values for this attribute are:

before - select files whose last modified date is before the indicated date after - select files whose last modified date is after the indicated date equal - select files whose last modified date is this exact date

The default is equal.

No

granularity The number of milliseconds leeway to use when comparing file modification times. This is needed because not every file system supports tracking the last modified time to the millisecond level. Default is 0 milliseconds, or 2 seconds on DOS systems.

No

pattern The SimpleDateFormat-compatible pattern to use when interpreting the datetime attribute. Since Ant 1.6.2 No

checkdirs Indicates whether or not to check dates on directories. No, defaults to false

Here is an example of how to use the Date Selector:<fileset dir="${jar.path}" includes="**/*.jar"> <date datetime="01/01/2001 12:00 AM" when="before"/></fileset>Selects all JAR files which were last modified before midnight January 1, 2001.Depend SelectorThe <depend> tag selects files whose last modified date is later than another, equivalent file in another location.The <depend> tag supports the use of a contained <mapper> element to define the location of the file to be compared against. If no <mapper> element is specified, the identity type mapper is used.

The <depend> selector is case-sensitive.Attribute Description Required

targetdir The base directory to look for the files to compare against. The precise location depends on a combination of this attribute and the <mapper> element, if any.

Yes

granularity The number of milliseconds leeway to give before deciding a file is out of date. This is needed because not every file system supports tracking the last modified time to the millisecond level. Default is 0 milliseconds, or 2 seconds on DOS systems.

No

Here is an example of how to use the Depend Selector:<fileset dir="${ant.1.5}/src/main" includes="**/*.java"> <depend targetdir="${ant.1.4.1}/src/main"/></fileset>Selects all the Java source files which were modified in the 1.5 release. Depth Selector

The <depth> tag selects files based on how many directory levels deep they are in relation to the base directory of the fileset. Attribute Description Required

min The minimum number of directory levels below the base directory that a file must be in order to be selected. Default is no limit.

At least one of the

two.max The maximum number of directory levels below the base directory that a file can be and still be selected. Default is no limit.

Here is an example of how to use the Depth Selector:

Page 37: Ant

<fileset dir="${doc.path}" includes="**/*"> <depth max="1"/></fileset>

Selects all files in the base directory and one directory below that!!!.Different Selector

The <different> selector will select a file if it is deemed to be 'different' from an equivalent file in another location!!!. The rules for determining difference between the two files are as follows:

1. If there is no 'other' file, it's different. 2. Files with different lengths are different. 3. If ignoreFileTimes is turned off, then differing file timestamps will cause files to be regarded as different. 4. Unless ignoreContents is set to true, a byte-for-byte check is run against the two files.

This is a useful selector to work with programs and tasks that don't handle dependency checking properly; even if a predecessor task always creates its output files, followup tasks can be driven off copies made with a different selector, so their dependencies are driven on the absolute state of the files, not just a timestamp. For example: anything fetched from a web site, or the output of some program. To reduce the amount of checking, when using this task inside a <copy> task, set preservelastmodified to true to propagate the timestamp from the source file to the destination file.The <different> selector supports the use of a contained <mapper> element to define the location of the file to be compared against. If

no <mapper> element is specified, the identity type mapper is used.Attribute Description Required

targetdir The base directory to look for the files to compare against. The precise location depends on a combination of this attribute and the <mapper> element, if any.

Yes

ignoreFileTimes Whether to use file times in the comparison or not. Default is true (time differences are ignored). No

ignoreContents Whether to do a byte per byte compare. Default is false (contents are compared). Since Ant 1.6.3 No

granularity The number of milliseconds leeway to give before deciding a file is out of date. This is needed because not every file system supports tracking the last modified time to the millisecond level. Default is 0 milliseconds, or 2 seconds on DOS systems.

No

Here is an example of how to use the Different Selector:<fileset dir="${ant.1.5}/src/main" includes="**/*.java"> <different targetdir="${ant.1.4.1}/src/main" ignoreFileTimes="true"/></fileset>Compares all the Java source files between the 1.4.1 and the 1.5 release and selects those who are different, disregarding file times. Filename SelectorThe <filename> tag acts like the <include> and <exclude> tags within a fileset. By using a selector instead, however, one can combine it with all the other selectors using whatever selector container is desired.

The <filename> selector is case-sensitive.Attribute Description Required

name The name of files to select. The name parameter can contain the standard Ant wildcard characters. Yes

casesensitive Whether to pay attention to case when looking at file names. Default is "true". No

negate Whether to reverse the effects of this filename selection, therefore emulating an exclude rather than include tag. Default is "false".

No

Here is an example of how to use the Filename Selector:<fileset dir="${doc.path}" includes="**/*"> <filename name="**/*.css"/></fileset>Selects all the cascading style sheet files.Present SelectorThe <present> tag selects files that have an equivalent file in another directory tree.The <present> tag supports the use of a contained <mapper> element to define the location of the file to be tested against. If no <mapper> element is specified, the identity type mapper is used.

The <present> selector is case-sensitive.Attribute Description Required

targetdir The base directory to look for the files to compare against. The precise location depends on a combination of this attribute and the <mapper> element, if any.

Yes

present Whether we are requiring that a file is present in the src directory tree only, or in both the src and the target directory tree. Valid values are:

srconly - select files only if they are in the src directory tree but not in the target directory tree both - select files only if they are present both in the src and target directory trees

Default is both. Setting this attribute to "srconly" is equivalent to wrapping the selector in the <not> selector container.

No

Here is an example of how to use the Present Selector:<fileset dir="${ant.1.5}/src/main" includes="**/*.java"> <present present="srconly" targetdir="${ant.1.4.1}/src/main"/></fileset>

Page 38: Ant

Selects all the Java source files which are new in the 1.5 release. Regular Expression Selector

The <containsregexp> tag in a FileSet limits the files defined by that fileset to only those which contain a match to the regular expression specified by the expression attribute.

The <containsregexp> selector can be used as a ResourceSelector (see the <restrict> ResourceCollection).Attribute Description Required

expression Specifies the regular expression that must match true in every file Yes

Here is an example of how to use the regular expression Selector:<fileset dir="${doc.path}" includes="*.txt"> <containsregexp expression="[4-6]\.[0-9]"/></fileset>Selects all the text files that match the regular expression (have a 4,5 or 6 followed by a period and a number from 0 to 9). Size Selector

The <size> tag in a FileSet will put a limit on the files specified by the include tag, so that tags which do not meet the size limits specified by the selector will not end up being selected.Attribute Description Required

value The size of the file which should be tested for. Yes

units The units that the value attribute is expressed in. When using the standard single letter SI designations, such as "k","M", or "G", multiples of 1000 are used. If you want to use power of 2 units, use the IEC standard: "Ki" for 1024, "Mi" for 1048576, and so on. The default is no units, which means the value attribute expresses the exact number of bytes.

No

when Indicates how to interpret the size, whether the files to be selected should be larger, smaller, or equal to that value. Acceptable values for this attribute are:

less - select files less than the indicated size more - select files greater than the indicated size equal - select files this exact size

The default is equal.

No

Here is an example of how to use the Size Selector:<fileset dir="${jar.path}"> <patternset> <include name="**/*.jar"/> </patternset> <size value="4" units="Ki" when="more"/></fileset>Selects all JAR files that are larger than 4096 bytes.Type SelectorThe <type> tag selects files of a certain type: directory or regular.

Attribute Description Required

type The type of file which should be tested for. Acceptable values are: file - regular files dir - directories

Yes

Here is an example of how to use the Type Selector to select only directories in ${src}<fileset dir="${src}"> <type type="dir"/></fileset>The Type Selector is often used in conjunction with other selectors. For example, to select files that also exist in a template directory, but avoid selecting empty directories, use: <fileset dir="${src}"> <and> <present targetdir="template"/> <type type="file"/> </and></fileset>

Modified Selector (face un hashvalue pe care-l compara cu altul tinut intr-un cache)The <modified> selector computes a value for a file, compares that to the value stored in a cache and select the file, if these two values differ.Because this selector is highly configurable the order in which the selection is done is:

1. get the absolute path for the file 2. get the cached value from the configured cache (absolute path as key) 3. get the new value from the configured algorithm 4. compare these two values with the configured comparator 5. update the cache if needed and requested 6. do the selection according to the comparison result

The comparison, computing of the hashvalue and the store is done by implementation of special interfaces. Therefore they may provide additional parameters.

Page 39: Ant

The <modified> selector can be used as a ResourceSelector (see the <restrict> ResourceCollection). In that case it maps simple file resources to

files and does its job. If the resource is from another type, the <modified> selector tries to (attention!) copy the content into a local file for computing the hashvalue.Attribute Description Required

algorithm The type of algorithm should be used. Acceptable values are (further information see later): hashvalue - HashvalueAlgorithm digest - DigestAlgorithm checksum - ChecksumAlgorithm

No, defaults to digest

cache The type of cache should be used. Acceptable values are (further information see later): propertyfile - PropertyfileCache

No, defaults to propertyfile

comparator The type of comparator should be used. Acceptable values are (further information see later): equal - EqualComparator rule - java.text.RuleBasedCollator (see note for restrictions)

No, defaults to equal

algorithmclass Classname of custom algorithm implementation. Lower priority than algorithm. No

cacheclass Classname of custom cache implementation. Lower priority than cache. No

comparatorclass Classname of custom comparator implementation. Lower priority than comparator. No

update Should the cache be updated when values differ? (boolean) No, defaults to true

seldirs Should directories be selected? (boolean) No, defaults to true

selres Should Resources whithout an InputStream, and therefore without checking, be selected? (boolean) No, defaults to true. Only relevant when used

as ResourceSelector.

delayupdate If set to true, the storage of the cache will be delayed until the next finished BuildEvent; task finished, target finished or build finished, whichever comes first. This is provided for increased performance. If set to false, the storage of the cache will happen with each change. This attribute depends upon the update attribute. (boolean)

No, defaults to true

These attributes can be set with nested <param/> tags. With <param/> tags you can set other values too - as long as they are named according to the following rules:

algorithm : same as attribute algorithm cache : same as attribute cache comparator : same as attribute comparator algorithmclass : same as attribute algorithmclass cacheclass : same as attribute cacheclass comparatorclass : same as attribute comparatorclass update : same as attribute update seldirs : same as attribute seldirs algorithm.* : Value is transfered to the algorithm via its setXX-methods cache.* : Value is transfered to the cache via its setXX-methods

comparator.* : Value is transfered to the comparator via its setXX-methods Algorithm options

Name Description

hashvalue Reads the content of a file into a java.lang.String and use thats hashValue(). No additional configuration required.

digest Uses java.security.MessageDigest. This Algorithm supports the following attributes: algorithm.algorithm (optional): Name of the Digest algorithm (e.g. 'MD5' or 'SHA', default = MD5) algorithm.provider (optional): Name of the Digest provider (default = null)

checksum Uses java.util.zip.Checksum. This Algorithm supports the following attributes: algorithm.algorithm (optional): Name of the algorithm (e.g. 'CRC' or 'ADLER', default = CRC)

Cache options

propertyfile Use the java.util.Properties class and its possibility to load and store to file. This Cache implementation supports the following attributes:

cache.cachefile (optional): Name of the properties-file (default = cache.properties)

Comparator options

equal Very simple object comparison.

rule Uses java.text.RuleBasedCollator for Object comparison. (see note for restrictions)

The <modified> selector supports a nested <classpath> element that represents a PATH like structure for finding custom interface implementations. Here are some examples of how to use the Modified Selector: <copy todir="dest"> <fileset dir="src"> <modified/> </fileset> </copy>

Page 40: Ant

This will copy all files from src to dest which content has changed. Using an updating PropertyfileCache with cache.properties and MD5-DigestAlgorithm. <copy todir="dest"> <fileset dir="src"> <modified update="true" seldirs="true" cache="propertyfile" algorithm="digest" comparator="equal"> <param name="cache.cachefile" value="cache.properties"/> <param name="algorithm.algorithm" value="MD5"/> </modified> </fileset> </copy>This is the same example rewritten as CoreSelector with setting the all the values (same as defaults are). <copy todir="dest"> <fileset dir="src"> <custom class="org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector"> <param name="update" value="true"/> <param name="seldirs" value="true"/> <param name="cache" value="propertyfile"/> <param name="algorithm" value="digest"/> <param name="comparator" value="equal"/> <param name="cache.cachefile" value="cache.properties"/> <param name="algorithm.algorithm" value="MD5"/> </custom> </fileset> </copy>And this is the same rewritten as CustomSelector. <target name="generate-and-upload-site"> <echo> generate the site using forrest </echo> <antcall target="site"/>

<echo> upload the changed file </echo> <ftp server="${ftp.server}" userid="${ftp.user}" password="${ftp.pwd}"> <fileset dir="htdocs/manual"> <modified/> </fileset> </ftp> </target>A useful scenario for this selector inside a build environment for homepage generation (e.g. with Apache Forrest). Here all changed files are uploaded to the server. The CacheSelector saves therefore much upload time. <modified cacheclassname="com.mycompany.MyCache"> <classpath> <pathelement location="lib/mycompony-antutil.jar"/> </classpath> </modified>Uses com.mycompany.MyCache from a jar outside of Ants own classpath as cache implementationNote on RuleBasedCollatorThe RuleBasedCollator needs a format for its work, but its needed while instantiation. There is a problem in the initialization algorithm for this case. Therefore you should not use this (or tell me the workaround :-).Signed Selector

The <signedselector> tag selects signed files and optionaly signed with a certain name. This selector has been added in Apache Ant 1.7. Attribute Description Required

name The signature name to check for. no

Script Selector

The <scriptselector> element enables you to write a complex selection algorithm in any Apache BSF or JSR 223 supported language.See the Script task for an explanation of scripts and dependencies. This selector was added in Apache Ant 1.7. Attribute Description Required

language language of the script. yes

manager The script engine manager to use. See the script task for using this attribute. No - default is "auto"

src filename of the script no

Page 41: Ant

setbeans whether to have all properties, references and targets as global variables in the script. No, default is "true".

classpath The classpath to pass into the script. No

classpathref The classpath to use, given as a reference to a path defined elsewhere. No

This selector can take a nested <classpath> element. See the script task on how to use this element. If no src attribute is supplied, the script must be nested inside the selector declaration.

The embedded script is invoked for every test, with the bean self is bound to the selector. It has an attribute selected must can be set using setSelected(boolean) to select that file.

The following beans are configured for every script, alongside the classic set of project, properties, and targets. Bean Description Type

self selector instance org.apache.tools.ant.types.optional

filename filename of the selection String

file file of the selection java.io.File

basedir Fileset base directory java.io.File

The self bean maps to the selector, which has the following attributes. Only the selected flag is writeable, the rest are read only via their getter methods. Attribute Description Type

selected writeable flag to select this file boolean

filename filename of the selection String

file file of the selection java.io.File

basedir Fileset base directory java.io.File

Example <scriptselector language="javascript"> self.setSelected(true); </scriptselector>Selects every file. <scriptselector language="javascript"> self.setSelected((filename.length%2)==0); </scriptselector>Select files whose filename length is even.

Selector ContainersTo create more complex selections, a variety of selectors that contain other selectors are available for your use. They

combine the selections of their child selectors in various ways.The selector containers are:

<and> - select a file only if all the contained selectors select it. < majority > - select a file if a majority of its selectors select it. <none > - select a file only if none of the contained selectors select it. < not > - can contain only one selector, and reverses what it selects and doesn't select. < or > - selects a file if any one of the contained selectors selects it. < selector > - contains only one selector and forwards all requests to it without alteration, provided that any "if"

or "unless" conditions are met. This is the selector to use if you want to define a reference. It is usable as an element of <project>. It is also the one to use if you want selection of files to be dependent on Ant property settings.

All selector containers can contain any other selector, including other containers, as an element. Using containers, the selector tags can be arbitrarily deep. Here is a complete list of allowable selector elements within a container:

<and> <contains> <custom> <date> <depend> <depth> <filename> <majority> <none> <not> <or> <present> <selector> <size>

And SelectorThe <and> tag selects files that are selected by all of the elements it contains. It returns as soon as it finds a selector that does not select the file, so it is not guaranteed to check every selector. Here is an example of how to use the And Selector:<fileset dir="${dist}" includes="**/*.jar"> <and> <size value="4" units="Ki" when="more"/> <date datetime="01/01/2001 12:00 AM" when="before"/> </and></fileset>

Selects all the JAR file larger than 4096 bytes which haven't been update since the last millenium.

Page 42: Ant

Majority SelectorThe <majority> tag selects files provided that a majority of the contained elements also select it. Ties are dealt with as specified by the allowtie attribute. Attribute Description Required

allowtie Whether files should be selected if there are an even number of selectors selecting them as are not selecting them. Default is true.

No

Here is an example of how to use the Majority Selector:<fileset dir="${docs}" includes="**/*.html"> <majority> <contains text="project" casesensitive="false"/> <contains text="taskdef" casesensitive="false"/> <contains text="IntrospectionHelper" casesensitive="true"/> </majority></fileset>Selects all the HTML files which contain at least two of the three phrases "project", "taskdef", and "IntrospectionHelper" (this last phrase must match case exactly).

None SelectorThe <none> tag selects files that are not selected by any of the elements it contains. It returns as soon as it finds a selector that selects the file, so it is not guaranteed to check every selector. Here is an example of how to use the None Selector:<fileset dir="${src}" includes="**/*.java"> <none> <present targetdir="${dest}"/> <present targetdir="${dest}"> <mapper type="glob" from="*.java" to="*.class"/> </present> </none></fileset>

Selects only Java files which do not have equivalent java or class files in the dest directory.

Not SelectorThe <not> tag reverses the meaning of the single selector it contains. Here is an example of how to use the Not Selector:<fileset dir="${src}" includes="**/*.java"> <not> <contains text="test"/> </not></fileset>

Selects all the files in the src directory that do not contain the string "test".

Or SelectorThe <or> tag selects files that are selected by any one of the elements it contains. It returns as soon as it finds a selector that selects the file, so it is not guaranteed to check every selector. Here is an example of how to use the Or Selector:<fileset dir="${basedir}"> <or> <depth max="0"/> <filename name="*.png"/> <filename name="*.gif"/> <filename name="*.jpg"/> </or></fileset>

Selects all the files in the top directory along with all the image files below it.

Selector ReferenceThe <selector> tag is used to create selectors that can be reused!!! through references. It is the only selector which can be used outside of any target, as an element of the <project> tag. It can contain only one other selector, but of course that selector can be a container. The <selector> tag can also be used to select files conditionally based on whether an Ant property exists or not. This functionality is realized using the "if" and "unless" attributes in exactly the same way they are used on targets or on the <include> and <exclude> tags within a <patternset>.Attribute Description Required

if Allow files to be selected only if the named property is set. No

Page 43: Ant

unless Allow files to be selected only if the named property is not set. No

Here is an example of how to use the Selector Reference:<project default="all" basedir="./ant"> <selector id="completed"> <none> <depend targetdir="build/classes"> <mapper type="glob" from="*.java" to="*.class"/> </depend> <depend targetdir="docs/manual/api"> <mapper type="glob" from="*.java" to="*.html"/> </depend> </none> </selector>

<target> <zip> <fileset dir="src/main" includes="**/*.java"> <selector refid="completed"/> </fileset> </zip> </target>

</project>

Zips up all the Java files which have an up-to-date equivalent class file and javadoc file associated with them.

And an example of selecting files conditionally, based on whether properties are set:<fileset dir="${working.copy}"> <or> <selector if="include.tests"> <filename name="**/*Test.class"> </selector> <selector if="include.source"> <and> <filename name="**/*.java"> <not> <selector unless="include.tests"> <filename name="**/*Test.java"> </selector> </not> </and> </selector> </or></fileset>

A fileset that conditionally contains Java source files and Test source and class files.

Custom SelectorsYou can write your own selectors and use them within the selector containers by specifying them within the <custom> tag.First, you have to write your selector class in Java. The only requirement it must meet in order to be a selector is that it implements the org.apache.tools.ant.types.selectors.FileSelector interface, which contains a single method. See Programming Selectors in Ant for more information.Once that is written, you include it in your build file by using the <custom> tag. Attribute Description Required

classname The name of your class that implements org.apache.tools.ant.types.selectors.FileSelector.

Yes

classpath The classpath to use in order to load the custom selector class. If neither this classpath nor the classpathref are specified, the class will be loaded from the classpath that Ant uses.

No

classpathref A reference to a classpath previously defined. If neither this reference nor the classpath above are specified, the class will be loaded from the classpath that Ant uses.

No

Here is how you use <custom> to use your class as a selector: <fileset dir="${mydir}" includes="**/*"> <custom classname="com.mydomain.MySelector"> <param name="myattribute" value="myvalue"/> </custom></fileset>

A number of core selectors can also be used as custom selectors by specifying their attributes using <param> elements. These are

Contains Selector with classname org.apache.tools.ant.types.selectors.ContainsSelector

Page 44: Ant

Date Selector with classname org.apache.tools.ant.types.selectors.DateSelector Depth Selector with classname org.apache.tools.ant.types.selectors.DepthSelector Filename Selector with classname org.apache.tools.ant.types.selectors.FilenameSelector Size Selector with classname org.apache.tools.ant.types.selectors.SizeSelector

Here is the example from the Depth Selector section rewritten to use the selector through <custom> . <fileset dir="${doc.path}" includes="**/*"> <custom classname="org.apache.tools.ant.types.selectors.DepthSelector"> <param name="max" value="1"/> </custom> </fileset>

Selects all files in the base directory and one directory below that.

For more details concerning writing your own selectors, consult Programming Selectors in Ant!!!.

FilterChains and FilterReadersConsider the flexibility of Unix pipes. If you wanted, for example, to copy just those lines that contained the string blee from the first 10 lines of a text file 'foo' (you wouldn't want to filter a binary file) to a file 'bar', you would do something like:cat foo|head -n10|grep blee > bar Ant was not flexible enough. There was no way for the <copy> task to do something similar. If you wanted the <copy> task to get the first 10 lines, you would have had to create special attributes:<copy file="foo" tofile="bar" head="10" contains="blee"/> The obvious problem thus surfaced: Ant tasks would not be able to accommodate such data transformation attributes as they would be endless. The task would also not know in which order these attributes were to be interpreted. That is, must the task execute the contains attribute first and then the head attribute or vice-versa? What Ant tasks needed was a mechanism to allow pluggable filter (data transformer) chains. Ant would provide a few filters for which there have been repeated requests. Users with special filtering needs would be able to easily write their own and plug them in.The solution was to refactor data transformation oriented tasks to support FilterChains. A FilterChain is a group of ordered FilterReaders. Users can define their own FilterReaders by just extending the java.io.FilterReader class. Such custom FilterReaders can be easily plugged in as nested elements of <filterchain> by using <filterreader> elements. Example: <copy file="${src.file}" tofile="${dest.file}"> <filterchain> <filterreader classname="your.extension.of.java.io.FilterReader"> <param name="foo" value="bar"/> </filterreader> <filterreader classname="another.extension.of.java.io.FilterReader"> <classpath> <pathelement path="${classpath}"/> </classpath> <param name="blah" value="blee"/> <param type="abra" value="cadabra"/> </filterreader> </filterchain></copy>

Ant provides some built-in filter readers. These filter readers can also be declared using a syntax similar to the above syntax. However, they can be declared using some simpler syntax also.Example: <loadfile srcfile="${src.file}" property="src.file.head"> <filterchain> <headfilter lines="15"/> </filterchain></loadfile>

is equivalent to: <loadfile srcfile="${src.file}" property="src.file.head"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.HeadFilter"> <param name="lines" value="15"/> </filterreader> </filterchain></loadfile>

The following built-in tasks support nested <filterchain> elements.

Concat, Copy, LoadFile, LoadProperties, MoveA FilterChain is formed by defining zero or more of the following nested elements.

Page 45: Ant

FilterReader, ClassConstants, EscapeUnicode, ExpandProperties, HeadFilter, LineContains, LineContainsRegExp, PrefixLines, ReplaceTokens, StripJavaComments, StripLineBreaks, StripLineComments, TabsToSpaces, TailFilter, DeleteCharacters, ConcatFilter, TokenFilter, FixCRLF

FilterReaderThe filterreader element is the generic way to define a filter. User defined filter elements are defined in the build file using this. Please note that built in filter readers can also be defined using this syntax. A FilterReader element must be supplied with a class name as an attribute value. The class resolved by this name must extend java.io.FilterReader. If the custom filter reader needs to be parameterized, it must implement org.apache.tools.type.Parameterizable.

Attribute Description Required

classname The class name of the filter reader. Yes

Nested Elements:<filterreader> supports <classpath> and <param> as nested elements. Each <param> element may take in the following attributes - name, type and value.

The following FilterReaders are supplied with the default distribution.

ClassConstantsThis filters basic constants defined in a Java Class, and outputs them in lines composed of the format name=value.

This filter uses the bcel library to understand the Java Class file. See Library Dependencies. Important: This filter is different from most of the other filters. Most of the filters operate on a sequence of characters. This filter operates on the sequence of bytes that makes up a class. However the bytes arrive to the filter as a sequence of characters. This means that one must be careful on the choice of character encoding to use. Most encoding lose information on conversion from an arbitary sequence of bytes to characters and back again to bytes. In particular the usual default

character encodings (CP152 and UTF-8) do. For this reason, since Ant 1.7, the character encoding ISO-8859-1 is used to convert from characters back to bytes, so one has to use this encoding for reading the java class file. Example:This loads the basic constants defined in a Java class as Ant properties. <loadproperties srcfile="foo.class" encoding="ISO-8859-1"> <filterchain> <classconstants/> </filterchain></loadproperties>

This loads the constants from a Java class file as Ant properties, prepending the names with a prefix. <loadproperties srcfile="build/classes/org/acme/bar.class" encoding="ISO-8859-1"> <filterchain> <classconstants/> <prefixlines prefix="ini."/> </filterchain></loadproperties>

EscapeUnicodeThis filter converts its input by changing all non US-ASCII characters into their equivalent unicode escape backslash u plus 4 digits.since Ant 1.6Example:This loads the basic constants defined in a Java class as Ant properties. <loadproperties srcfile="non_ascii_property.properties"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.EscapeUnicode"/> </filterchain></loadproperties>

Convenience method: <loadproperties srcfile="non_ascii_property.properties"> <filterchain> <escapeunicode/> </filterchain></loadproperties>ExpandPropertiesIf the data contains data that represents Ant properties (of the form ${...}), that is substituted with the property's actual value. Example:This results in the property modifiedmessage holding the value(ADICA IN EL SE RETINE) "All these moments will be lost in time, like teardrops in the rain" <echo message="All these moments will be lost in time, like teardrops in the ${weather}"

Page 46: Ant

file="loadfile1.tmp" /><property name="weather" value="rain"/><loadfile property="modifiedmessage" srcFile="loadfile1.tmp"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.ExpandProperties"/> </filterchain></loadfile>

Convenience method: <echo message="All these moments will be lost in time, like teardrops in the ${weather}" file="loadfile1.tmp" /><property name="weather" value="rain"/><loadfile property="modifiedmessage" srcFile="loadfile1.tmp"> <filterchain> <expandproperties/> </filterchain></loadfile>

HeadFilterThis filter reads the first few lines from the data supplied to it. Parameter Name Parameter Value Required

lines Number of lines to be read. Defaults to "10" A negative value means that all lines are passed (useful with skip)

No

skip Number of lines to be skipped (from the beginning). Defaults to "0" No

Example:This stores the first 15 lines of the supplied data in the property src.file.head!!! <loadfile srcfile="${src.file}" property="src.file.head"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.HeadFilter"> <param name="lines" value="15"/> </filterreader> </filterchain></loadfile>

Convenience method: <loadfile srcfile="${src.file}" property="src.file.head"> <filterchain> <headfilter lines="15"/> </filterchain></loadfile>This stores the first 15 lines, skipping the first 2 lines, of the supplied data in the property src.file.head. (Means: lines 3-17) <loadfile srcfile="${src.file}" property="src.file.head"> <filterchain> <headfilter lines="15" skip="2"/> </filterchain></loadfile>

See the testcases for more examples (src\etc\testcases\filters\head-tail.xml in the source distribution).

LineContainsThis filter includes only those lines that contain all the user-specified strings. Parameter Type Parameter Value Required

contains Substring to be searched for. Yes

negate Whether to select non-matching lines only. Since Ant 1.7 No

Example:This will include only those lines that contain foo and bar. <filterreader classname="org.apache.tools.ant.filters.LineContains"> <param type="contains" value="foo"/> <param type="contains" value="bar"/></filterreader>

Convenience method: <linecontains> <contains value="foo"/> <contains value="bar"/></linecontains>Negation: <filterreader classname="org.apache.tools.ant.filters.LineContains"> <param type="negate" value="true"/>

Page 47: Ant

<param type="contains" value="foo"/> <param type="contains" value="bar"/></filterreader>

or <linecontains negate="true"> <contains value="foo"/> <contains value="bar"/></linecontains>

LineContainsRegExpFilter which includes only those lines that contain the user-specified regular expression matching strings. Parameter Type Parameter Value Required

regexp Regular expression to be searched for. Yes

negate Whether to select non-matching lines only. Since Ant 1.7 No

See Regexp Type for the description of the nested element regexp and of the choice of regular expression implementation. Example:This will fetch all those lines that contain the pattern foo <filterreader classname="org.apache.tools.ant.filters.LineContainsRegExp"> <param type="regexp" value="foo*"/></filterreader>

Convenience method: <linecontainsregexp> <regexp pattern="foo*"/></linecontainsregexp>Negation: <filterreader classname="org.apache.tools.ant.filters.LineContainsRegExp"> <param type="negate" value="true"/> <param type="regexp" value="foo*"/></filterreader>

or <linecontainsregexp negate="true"> <regexp pattern="foo*"/></linecontainsregexp>

PrefixLinesAttaches a prefix to every line. Parameter Name Parameter Value Required

prefix Prefix to be attached to lines. Yes

Example:This will attach the prefix Foo to all lines. <filterreader classname="org.apache.tools.ant.filters.PrefixLines"> <param name="prefix" value="Foo"/></filterreader>

Convenience method: <prefixlines prefix="Foo"/>

ReplaceTokensThis filter reader replaces all strings that are sandwiched between begintoken and endtoken with user defined values. Parameter Type Parameter Name Parameter Value Required

tokenchar begintoken Character marking the beginning of a token. Defaults to @ No

tokenchar endtoken Character marking the end of a token. Defaults to @ No

token User defined String. User defined search String. Yes

propertiesfile Not applicable. Properties file to take tokens from. No

Example:This replaces occurrences of the string @DATE@ in the data with today's date and stores it in the property ${src.file.replaced} <tstamp/><loadfile srcfile="${src.file}" property="${src.file.replaced}"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens"> <param type="token" name="DATE" value="${TODAY}"/> </filterreader> </filterchain></loadfile>

Page 48: Ant

Convenience method: <tstamp/><loadfile srcfile="${src.file}" property="${src.file.replaced}"> <filterchain> <replacetokens> <token key="DATE" value="${TODAY}"/> </replacetokens> </filterchain></loadfile>

This will treat each properties file entry in sample.properties as a token/key pair : <loadfile srcfile="${src.file}" property="${src.file.replaced}"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.ReplaceTokens"> <param type="propertiesfile" value="sample.properties"/> </filterreader> </filterchain></loadfile></filterchain>

StripJavaCommentsThis filter reader strips away comments from the data, using Java syntax guidelines. This filter does not take in any parameters. Example:<loadfile srcfile="${java.src.file}" property="${java.src.file.nocomments}"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.StripJavaComments"/> </filterchain></loadfile>Convenience method: <loadfile srcfile="${java.src.file}" property="${java.src.file.nocomments}"> <filterchain> <stripjavacomments/> </filterchain></loadfile>

StripLineBreaksThis filter reader strips away specific characters from the data supplied to it. Parameter Name Parameter Value Required

linebreaks Characters that are to be stripped out. Defaults to "\r\n" No

Examples:This strips the '\r' and '\n' characters. <loadfile srcfile="${src.file}" property="${src.file.contents}"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.StripLineBreaks"/> </filterchain></loadfile>Convenience method: <loadfile srcfile="${src.file}" property="${src.file.contents}"> <filterchain> <striplinebreaks/> </filterchain></loadfile>This treats the '(' and ')' characters as line break characters and strips them. <loadfile srcfile="${src.file}" property="${src.file.contents}"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.StripLineBreaks"> <param name="linebreaks" value="()"/> </filterreader> </filterchain></loadfile>

StripLineCommentsThis filter removes all those lines that begin with strings that represent comments as specified by the user. Parameter Type Parameter Value Required

comment Strings that identify a line as a comment when they appear at the start of the line. Yes

Examples:This removes all lines that begin with #, --, REM, rem and // <filterreader classname="org.apache.tools.ant.filters.StripLineComments"> <param type="comment" value="#"/> <param type="comment" value="--"/> <param type="comment" value="REM "/> <param type="comment" value="rem "/> <param type="comment" value="//"/></filterreader>

Page 49: Ant

Convenience method: <striplinecomments> <comment value="#"/> <comment value="--"/> <comment value="REM "/> <comment value="rem "/> <comment value="//"/></striplinecomments>

TabsToSpacesThis filter replaces tabs with spaces Parameter Name Parameter Value Required

tablength Defaults to "8" No

Examples:This replaces tabs in ${src.file} with spaces. <loadfile srcfile="${src.file}" property="${src.file.notab}"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.TabsToSpaces"/> </filterchain></loadfile>Convenience method: <loadfile srcfile="${src.file}" property="${src.file.notab}"> <filterchain> <tabstospaces/> </filterchain></loadfile>

TailFilterThis filter reads the last few lines from the data supplied to it. Parameter Name Parameter Value Required

lines Number of lines to be read. Defaults to "10" A negative value means that all lines are passed (useful with skip)

No

skip Number of lines to be skipped (from the end). Defaults to "0" No

Background:With HeadFilter and TailFilter you can extract each part of a text file you want. This graphic shows the dependencies:

Examples:This stores the last 15 lines of the supplied data in the property ${src.file.tail} <loadfile srcfile="${src.file}" property="${src.file.tail}"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.TailFilter"> <param name="lines" value="15"/> </filterreader> </filterchain></loadfile>Convenience method: <loadfile srcfile="${src.file}" property="${src.file.tail}"> <filterchain> <tailfilter lines="15"/> </filterchain></loadfile>This stores the last 5 lines of the first 15 lines of the supplied data in the property ${src.file.mid}

Page 50: Ant

<loadfile srcfile="${src.file}" property="${src.file.mid}"> <filterchain> <filterreader classname="org.apache.tools.ant.filters.HeadFilter"> <param name="lines" value="15"/> </filterreader> <filterreader classname="org.apache.tools.ant.filters.TailFilter"> <param name="lines" value="5"/> </filterreader> </filterchain></loadfile>Convenience method: <loadfile srcfile="${src.file}" property="${src.file.mid}"> <filterchain> <headfilter lines="15"/> <tailfilter lines="5"/> </filterchain></loadfile>This stores the last 10 lines, skipping the last 2 lines, of the supplied data in the property src.file.head. (Means: if supplied data contains 60 lines, lines 49-58 are extracted) <loadfile srcfile="${src.file}" property="src.file.head"> <filterchain> <tailfilter lines="10" skip="2"/> </filterchain></loadfile>

DeleteCharactersThis filter deletes specified characters. This filter is only available in the convenience form.Parameter Name Parameter Value Required

chars The characters to delete. This attribute is backslash enabled. Yes

Examples:Delete tabs and returns from the data. <deletecharacters chars="\t\r"/>

ConcatFilterThis filter prepends or appends the content file to the filtered files.since Ant 1.6

Parameter Name Parameter Value Required

prepend The name of the file which content should be prepended to the file. No

append The name of the file which content should be appended to the file. No

Examples:Do nothing: <filterchain> <concatfilter/></filterchain>

Adds a license text before each java source: <filterchain> <concatfilter prepend="apache-license-java.txt"/></filterchain>

TokenFilterThis filter tokenizes the inputstream into strings and passes these strings to filters of strings!!!. Unlike the other filterreaders, this does not support params, only convenience methods are implemented. The tokenizer and the string filters are defined by nested elements.

Only one tokenizer element may be used, the LineTokenizer is the default!!! if none are specified. A tokenizer splits the input into token strings and trailing delimiter strings.

ATENTIE: There may be zero or more string filters!!!. A string filter processes a token and either returns a string or a null. It the string is not null it is passed to the next filter . This proceeds until all the filters are called. If a string is returned after all the filters, the string is outputs with its associated token delimitier (if one is present). The trailing delimiter may be overridden by the delimOutput attribute. blackslash interpretation A number of attributes (including delimOutput) interpret backslash escapes. The following are understood: \n, \r, \f, \t and \\.

Attribute Description Required

delimOutput This overrides the tokendelimiter returned by the tokenizer if it is not empty. This attribute is backslash enabled.

No

Page 51: Ant

The following tokenizers are provided by the default distribution. LineTokenizer, FileTokenizer, StringTokenizerThe following string filters are provided by the default distribution. ReplaceString , ContainsString, ReplaceRegex, ContainsRegex, Trim, IgnoreBlank, DeleteCharactersThe following string filters are provided by the optional distribution. ScriptFilterSome of the filters may be used directly within a filter chain. In this case a tokenfilter is created implicitly. An extra attribute "byline" is added to the filter to specify whether to use a linetokenizer (byline="true") or a filetokenizer (byline="false"). The default is "true". LineTokenizerThis tokenizer splits the input into lines. The tokenizer delimits lines by "\r", "\n" or "\r\n". This is the default tokenizer. Attribute Description Required

includeDelims Include the line endings in the token. Default is false. No

Examples:Convert input current line endings to unix style line endings (by default avem un LineTokenizer). <tokenfilter delimoutput="\n"/>

Remove blank lines. <tokenfilter> <ignoreblank/></tokenfilter>

FileTokenizer

This tokenizer treats all the input as a token. So be careful not to use this on very large input. Examples:Replace the first occurrence of package with //package. <tokenfilter> <filetokenizer/> <!--Filtrele se aplica unul dupa altul!!! --> <replaceregex pattern="([\n\r]+[ \t]*|^[ \t]*)package" flags="s" replace="\1//package"/></tokenfilter>StringTokenizerThis tokenizer is based on java.util.StringTokenizer. It splits up the input into strings separated by white space, or by a specified list of delimiting characters. If the stream starts with delimiter characters, the first token will be the empty string (unless the delimsaretokens attribute is used). Attribute Description Required

delims The delimiter characters. White space is used if this is not set. (White space is defined in this case by java.lang.Character.isWhitespace()).

No

delimsaretokens If this is true, each delimiter character is returned as a token. Default is false. No

suppressdelims If this is true, delimiters are not returned. Default is false. No

includeDelims Include the delimiters in the token. Default is false. No

Examples:Surround each non space token with a "[]". <tokenfilter> <stringtokenizer/> <replaceregex pattern="(.+)" replace="[\1]"/> <!--Iata backreferences de la expr. Regulate --></tokenfilter>

FiltreReplaceStringThis is a simple filter to replace strings. This filter may be used directly within a filterchain. Attribute Description Required

from The string that must be replaced. Yes

to The new value for the replaced string. When omitted an empty string is used. No

Examples:Replace "sun" with "moon". <tokenfilter>

Page 52: Ant

<replacestring from="sun" to="moon"/></tokenfilter>ContainsStringThis is a simple filter to filter tokens that contains a specified string. Attribute Description Required

contains The string that the token must contain. Yes

Examples:Include only lines( pentru ca token-ul default este linetokenizer!!! ) that contain "foo"; <tokenfilter> <containsstring contains="foo"/></tokenfilter>

ReplaceRegexThis string filter replaces regular expressions. This filter may be used directly within a filterchain. See Regexp Type concerning the choice of the implementation. Attribute Description Required

pattern The regular expression pattern to match in the token. Yes

replace The substitution pattern to replace the matched regular expression. When omitted an empty string is used.

No

flags See ReplaceRegexp for an explanation of regex flags. No

Examples:Replace all occurrences of "hello" with "world", ignoring case. <tokenfilter> <replaceregex pattern="hello" replace="world" flags="gi"/></tokenfilter>

ContainsRegexThis filters strings that match regular expressions. The filter may optionally replace the matched regular expression. This filter may be used directly within a filterchain. See Regexp Type concerning the choice of regular expression implementation. Attribute Description Required

pattern The regular expression pattern to match in the token. Yes

replace The substitution pattern to replace the matched regular expression. When omitted the orignal token is returned.

No

flags See ReplaceRegexp for an explanation of regex flags. No

Examples:Filter lines that contain "hello" or "world", ignoring case. <tokenfilter> <containsregex pattern="(hello|world)" flags="i"/></tokenfilter>

This example replaces lines like "SUITE(TestSuite, bits);" with "void register_bits();" and removes other lines. <tokenfilter> <containsregex pattern="^ *SUITE\(.*,\s*(.*)\s*\).*" replace="void register_\1();"/></tokenfilter>

TrimThis filter trims whitespace from the start and end of tokens. This filter may be used directly within a filterchain. IgnoreBlankThis filter removes empty tokens. This filter may be used directly within a filterchain. DeleteCharactersThis filter deletes specified characters from tokens. Attribute Description Required

chars The characters to delete. This attribute is backslash enabled. Yes

Examples:

Delete tabs from lines, trim the lines and removes empty lines. <tokenfilter>

Page 53: Ant

<deletecharacters chars="\t"/> <trim/> <ignoreblank/></tokenfilter>

ScriptFilter

This is an optional filter that executes a script in a Apache BSF or JSR 223 supported language!!!.See the Script task for an explanation of scripts and dependencies. The script is provided with an object self that has getToken() and setToken(String) methods. The getToken() method returns the current token. The setToken(String) method replaces the current token. This filter may be used directly within a filterchain.Attribute Description Required

language The programming language the script is written in. Must be a supported Apache BSF or JSR 223 language

Yes

manager The script engine manager to use. See the script task for using this attribute. No - default is "auto"

src The location of the script as a file, if not inline No

setbeans whether to have all properties, references and targets as global variables in the script.

No, default is "true".

classpath The classpath to pass into the script. No

classpathref The classpath to use, given as a reference to a path defined elsewhere. No

This filter can take a nested <classpath> element. See the script task on how to use this element. Examples:Convert to uppercase: <tokenfilter> <scriptfilter language="javascript"> self.setToken(self.getToken().toUpperCase()); </scriptfilter></tokenfilter>

Remove lines containing the string "bad" while copying text files: <copy todir="dist"> <fileset dir="src" includes="**/*.txt"/> <filterchain> <scriptfilter language="beanshell"> if (self.getToken().indexOf("bad") != -1) { self.setToken(null); } </scriptfilter> </filterchain></copy>

Custom tokenizers and string filtersCustom string filters and tokenizers may be plugged in by extending the interfaces org.apache.tools.ant.filters.TokenFilter.Filter and org.apache.tools.ant.util.Tokenizer respectly. They are defined the build file using <typedef/>. For example a string filter that capitalizes words may be declared as: package my.customant;import org.apache.tools.ant.filters.TokenFilter;

public class Capitalize implements TokenFilter.Filter{ public String filter(String token) { if (token.length() == 0) return token; return token.substring(0, 1).toUpperCase() + token.substring(1); }}

This may be used as follows: <typedef type="capitalize" classname="my.customant.Capitalize" classpath="my.customant.path"/> <copy file="input" tofile="output"> <filterchain> <tokenfilter>

Page 54: Ant

<stringtokenizer/> <capitalize/> </tokenfilter> </filterchain> </copy>

RegexpRegexp represents a regular expression. ParametersAttribute Description Required

pattern regular expression pattern Yes

Ex: <regexp id="myregexp" pattern="alpha(.+)beta"/>Defines a regular expression for later use with id myregexp. <regexp refid="myregexp"/>Use the regular expression with id myregexp.

Choice of regular expression implementationAnt comes with wrappers for the java.util.regex package of JDK 1.4, jakarta-regexp and jakarta-ORO, See installation dependencies concerning the supporting libraries.The property ant.regexp.regexpimpl governs which regular expression implementation will be chosen. Possible values for this property are :

org.apache.tools.ant.util.regexp.Jdk14RegexpRegexp org.apache.tools.ant.util.regexp.JakartaOroRegexp org.apache.tools.ant.util.regexp.JakartaRegexpRegexp

It can also be another implementation of the interface org.apache.tools.ant.util.regexp.Regexp. If ant.regexp.regexpimpl is not defined, ant checks in the order Jdk14Regexp, JakartaOroRegexp, JakartaRegexp for the availability of the corresponding library. The first of these 3 which is found will be used.There are cross-platform issues for matches related to line terminator. For example if you use $ to anchor your regular expression on the end of a line the results might be very different depending on both your platform and the regular expression library you use. It is

'highly recommended' that you test your pattern on both Unix and Windows platforms before you rely on it.

Jakarta Oro defines a line terminator as '\n' and is consistent with Perl. Jakarta RegExp uses a system-dependant line terminator. JDK 1.4 uses '\n', '\r\n', '\u0085', '\u2028', '\u2029' as a default but is configured in the wrapper to use only '\n'

(UNIX_LINE)We strongly recommend that you use Jakarta Oro. UsageThe following tasks and types use the Regexp type :

ReplaceRegExp task LineContainsRegexp filter

These string filters also use the mechanism of regexp to choose a regular expression implementation : ContainsRegex string filter ReplaceRegex string filter

Directory-based TasksSome tasks use directory trees for the actions they perform. For example, the javac task, which compiles a directory tree with .java files into .class files, is one of these directory-based tasks. Because some of these tasks do so much work with a directory tree, the task itself can act as an implicit FileSet.Whether the fileset is implicit or not, it can often be very useful to work on a subset of the directory tree. This section describes how you can select a subset of such a directory tree when using one of these directory-based tasks.Ant gives you two ways to create a subset of files in a fileset, both of which can be used at the same time:

Only include files and directories that match any include patterns and do not match any exclude patterns in a given PatternSet.

Select files based on selection criteria defined by a collection of selector nested elements.

PatternsetWe said that Directory-based tasks can sometimes act as an implicit <fileset>, but in addition to that, a FileSet acts as an implicit <patternset>!!!.The inclusion and exclusion elements of the implicit PatternSet can be specified inside the directory-based task (or explicit fileset) via either:

the attributes includes and excludes.

Page 55: Ant

nested elements <include> and <exclude>. external files specified with the attributes includesfile and excludesfile. external files specified with the nested elements <includesfile> and <excludesfile>.

When dealing with an external file, each line of the file is taken as a pattern that is added to the list of include or exclude patterns.When both inclusion and exclusion are used, only files/directories that match at least one of the include patterns and don't match any of the exclude patterns are used. If no include pattern is given, all files are assumed to match the include pattern (with the possible exception of the default excludes).

PatternsAs described earlier, patterns are used for the inclusion and exclusion of files. These patterns look very much like the patterns used in DOS and UNIX:

'*' matches zero or more characters, '?' matches one character.In general, patterns are considered relative paths, relative to a task dependent base directory (the dir attribute in the case of <fileset>). Only files found below that base directory are considered. So while a pattern like ../foo.java is possible, it will not match anything when applied since the base directory's parent is never scanned for files.Examples:*.java  matches  .java, x.java and FooBar.java, but not FooBar.xml (does not end with .java).?.java  matches  x.java, A.java, but not .java or xyz.java (both don't have one character before .java).Combinations of *'s and ?'s are allowed.Matching is done per-directory. This means that first the first directory in the pattern is matched against the first directory in the path to match. Then the second directory is matched, and so on. For example, when we have the pattern /?abc/*/*.java and the path /xabc/foobar/test.java, the first ?abc is matched with xabc, then * is matched with foobar, and finally *.java is matched with test.java. They all match, so the path matches the pattern.To make things a bit more flexible, we add one extra feature, which makes it possible to match multiple directory levels. This can be used to match a complete directory tree, or a file anywhere in the directory tree. To do this, ** must be used as the name of a directory. When ** is used as the name of a directory in the pattern, it matches zero or more directories. For example: /test/** matches all files/directories under /test/, such as /test/x.java, or /test/foo/bar/xyz.html, but not /xyz.xml.There is one "shorthand": if a pattern ends with / or \, then ** is appended. For example, mypackage/test/ is interpreted as if it were mypackage/test/**.Example patterns:**/CVS/* Matches all files in CVS directories that can be located anywhere in the directory tree. Matches:

CVS/Repository org/apache/CVS/Entries org/apache/jakarta/tools/ant/CVS/Entries

But not: org/apache/CVS/foo/bar/Entries (foo/bar/ part does not match)

org/apache/jakarta/** Matches all files in the org/apache/jakarta directory tree. Matches: org/apache/jakarta/tools/ant/docs/index.html org/apache/jakarta/test.xml

But not: org/apache/xyz.java (jakarta/ part is missing).

org/apache/**/CVS/* Matches all files in CVS directories that are located anywhere in the directory tree under org/apache. Matches: org/apache/CVS/Entries org/apache/jakarta/tools/ant/CVS/EntriesBut not: org/apache/CVS/foo/bar/Entries

(foo/bar/ part does not match)**/test/** Matches all files that have a test element in their path, including test as a filename.

When these patterns are used in inclusion and exclusion, you have a powerful way to select just the files you want.

Page 56: Ant

SelectorsThe <fileset>, whether implicit or explicit in the directory-based task, also acts as an <and> selector container. This can be used to create arbitrarily complicated selection criteria for the files the task should work with. See the Selector documentation for more information.Standard Tasks/FilesetsMany of the standard tasks in ant take one or more filesets which follow the rules given here. This list, a subset of those, is a list of standard ant tasks that can act as an implicit fileset:

<checksum>

<copydir> (deprecated) <delete> <dependset> <fixcrlf> <javac> <replace> <rmic>

<style> (aka <xslt> ) <tar> <zip> <ddcreator> <ejbjar> <ejbc> <cab> <native2ascii> <netrexxc>

<renameextensions> <depend> <ilasm> <csc> <vbc> <translate> <image>

<jlink> (deprecated) <jspc> <wljspc>

Examples<copy todir="${dist}"> <fileset dir="${src}" includes="**/images/*" excludes="**/*.gif" /></copy>

This copies all files in directories called images that are located in the directory tree defined by ${src} to the destination directory defined by ${dist}, but excludes all *.gif files from the copy.<copy todir="${dist}"> <fileset dir="${src}"> <include name="**/images/*"/> <exclude name="**/*.gif"/> </fileset></copy>

The same as the example above, but expressed using nested elements.<delete dir="${dist}"> <include name="**/images/*"/> <exclude name="**/*.gif"/></delete>

Deleting the original set of files, the delete task can act as an implicit fileset.Default ExcludesThere are a set of definitions that are excluded by default from all directory-based tasks. They are: **/*~ **/#*# **/.#* **/%*% **/._*

Page 57: Ant

**/CVS **/CVS/** **/.cvsignore **/SCCS **/SCCS/** **/vssver.scc **/.svn **/.svn/** **/.DS_Store

If you do not want these default excludes applied, you may disable them with the defaultexcludes="no" attribute.This is the default list; note that you can modify the list of default excludes by using the defaultexcludes task.

Mapping File NamesSome tasks take source files and create target files. Depending on the task, it may be quite obvious which name a target file will have (using javac, you know there will be .class files for your .java files) - in other cases you may want to specify the target files, either to help Ant or to get an extra bit of functionality.While source files are usually specified as filesets, you don't specify target files directly - instead, you tell Ant how to find the target file(s) for one source file. An instance of org.apache.tools.ant.util.FileNameMapper is responsible for this. It constructs target file names based on rules that can be parameterized with from and to attributes - the exact meaning of which is implementation-dependent.These instances are defined in <mapper> elements with the following attributes:

Attribute Description Required

type specifies one of the built-in implementations.Exactly one of these

classname specifies the implementation by class name.

classpath the classpath to use when looking up classname. No

classpathref the classpath to use, given as reference to a path defined elsewhere. No

from the from attribute for the given implementation. Depends on implementation.

to the to attribute for the given implementation. Depends on implementation.

Note that Ant will not automatically convert / or \ characters in the to and from attributes to the correct directory separator of your current platform. If you need to specify this separator, use ${file.separator} instead. For the regexpmapper, ${file.separator} will not work, as on windows it is the '\' character, and this is an escape character for regular expressions, one should use the handledirsep attribute instead. Parameters specified as nested elementsThe classpath can be specified via a nested <classpath>, as well - that is, a path-like structure.Since Ant 1.6.2, nested File Mappers can be supplied via either <mapper> elements or <typedef>'d implementations of org.apache.tools.ant.util.FileNameMapper. If nested File Mappers are specified by either means, the mapper will be implicitly configured as a composite mapper.

The built-in mapper types are:All built-in mappers are case-sensitive.As of Ant 1.6.2, each of the built-in mapper implementation types is directly accessible using a specific tagname. This makes it possible for filename mappers to support attributes in addition to the generally available to and from.The <mapper type|classname="..."> usage form remains valid for reasons of backward compatibility.

Page 58: Ant

identityThe target file name is identical to the source file name. Both to and from will be ignored.Examples: <mapper type="identity"/><identitymapper/>

Source file name Target file name

A.java A.java

foo/bar/B.java foo/bar/B.java

C.properties C.properties

Classes/dir/dir2/A.properties Classes/dir/dir2/A.properties

flattenThe target file name is identical to the source file name, with all leading directory information stripped off. Both to and from will be ignored.Examples: <mapper type="flatten"/><flattenmapper/>

Source file name Target file name

A.java A.java

foo/bar/B.java B.java

C.properties C.properties

Classes/dir/dir2/A.properties A.properties

mergeThe target file name will always be the same, as defined by to - from will be ignored.Examples:<mapper type="merge" to="archive.tar"/><mergemapper to="archive.tar"/>

Source file name Target file name

A.java archive.tar

foo/bar/B.java archive.tar

C.properties archive.tar

Classes/dir/dir2/A.properties archive.tar

globBoth to and from define patterns that may contain at most one *. For each source file that matches the from pattern, a target file name will be constructed from the to pattern by substituting the * in the to pattern with the text that matches the * in the from pattern. Source file names that don't match the from pattern will be ignored.Examples: <mapper type="glob" from="*.java" to="*.java.bak"/><globmapper from="*.java" to="*.java.bak"/>

Source file name Target file name

A.java A.java.bak

foo/bar/B.java foo/bar/B.java.bak

C.properties ignored

Classes/dir/dir2/A.properties ignored<mapper type="glob" from="C*ies" to="Q*y"/><globmapper from="C*ies" to="Q*y"/>

Source file name Target file name

A.java ignored

Page 59: Ant

foo/bar/B.java ignored

C.properties Q.property

Classes/dir/dir2/A.properties Qlasses/dir/dir2/A.property

The globmapper mapper can take the following extra attributes.

Attribute Description Required

casesensitive If this is false, the mapper will ignore case when matching the glob pattern. This attribute can be true or false, the default is true. Since Ant 1.6.3.

No

handledirsep If this is specified, the mapper will ignore the difference between the normal directory separator characters - \ and /. This attribute can be true or false, the default is false. This attribute is useful for cross-platform build files. Since Ant 1.6.3.

No

An example: <pathconvert property="x" targetos="unix"> <path path="Aj.Java"/> <mapper> <chainedmapper> <flattenmapper/> <globmapper from="a*.java" to="*.java.bak" casesensitive="no"/> </chainedmapper> </mapper> </pathconvert> <echo>x is ${x}</echo>

will output "x is j.java.bak". and <pathconvert property="x" targetos="unix"> <path path="d/e/f/j.java"/> <mapper> <globmapper from="${basedir}\d/e\*" to="*" ignoredirchar="yes"/> </mapper> </pathconvert> <echo>x is ${x}</echo>

will output "x is f/j.java". regexpBoth to and from define regular expressions. If the source file name matches the from pattern, the target file name will be constructed from the to pattern, using \0 to \9 as back-references for the full match (\0) or the matches of the subexpressions in parentheses. Source files not matching the from pattern will be ignored.Note that you need to escape a dollar-sign ($) with another dollar-sign in Ant.The regexp mapper needs a supporting library and an implementation of org.apache.tools.ant.util.regexp.RegexpMatcher that hides the specifics of the library. Ant comes with implementations for the java.util.regex package of JDK 1.4 or higher, jakarta-regexp and jakarta-ORO. If you compile from sources and plan to use one of them, make sure the libraries are in your CLASSPATH. For information about using gnu.regexp or gnu.rex with Ant, see this article.This means, you need one of the supported regular expression libraries and the corresponding ant-[jakarta-oro, jakarta-regexp, apache-oro, apache-regexp}.jar from the Ant release you are using. Make sure, both will be loaded from the same classpath, that is either put them into your CLASSPATH, ANT_HOME/lib directory or a nested <classpath> element of the mapper - you cannot have ant-[jakarta-oro, jakarta-regexp, apache-oro, apache-regexp].jar in ANT_HOME/lib and the library in a nested <classpath>.Ant will choose the regular-expression library based on the following algorithm:

If the system property ant.regexp.matcherimpl has been set, it is taken as the name of the class implementing org.apache.tools.ant.util.regexp.RegexpMatcher that should be used.

If it has not been set, first try the JDK 1.4 classes, then jakarta-ORO and finally try jakarta-regexp.Examples: <mapper type="regexp" from="^(.*)\.java$$" to="\1.java.bak"/><regexpmapper from="^(.*)\.java$$" to="\1.java.bak"/>

Page 60: Ant

Source file name Target file name

A.java A.java.bak

foo/bar/B.java foo/bar/B.java.bak

C.properties ignored

Classes/dir/dir2/A.properties ignored<mapper type="regexp" from="^(.*)/([^/]+)/([^/]*)$$" to="\1/\2/\2-\3"/><regexpmapper from="^(.*)/([^/]+)/([^/]*)$$" to="\1/\2/\2-\3"/>

Source file name Target file name

A.java ignored

foo/bar/B.java foo/bar/bar-B.java

C.properties ignored

Classes/dir/dir2/A.properties Classes/dir/dir2/dir2-A.properties

<mapper type="regexp" from="^(.*)\.(.*)$$" to="\2.\1"/><regexpmapper from="^(.*)\.(.*)$$&" to="\2.\1"/>

Source file name Target file name

A.java java.A

foo/bar/B.java java.foo/bar/B

C.properties properties.C

Classes/dir/dir2/A.properties properties.Classes/dir/dir2/A

<mapper type="regexp" from="^(.*?)(\$$[^/\\\.]*)?\.class$$" to="\1.java"/><regexpmapper from="^(.*?)(\$$[^/\\\.]*)?\.class$$" to="\1.java"/>

Source file name Target file name

ClassLoader.class ClassLoader.java

java/lang/ClassLoader.class java/lang/ClassLoader.java

java\lang\ClassLoader$1.class java\lang\ClassLoader.java

java/lang/ClassLoader$foo$1.class java/lang/ClassLoader.java

The regexpmapper mapper can take the following extra attributes.

Attribute Description Required

casesensitive If this is false, the mapper will ignore case when matching the pattern. This attribute can be true or false, the default is true. Since Ant 1.6.3.

No

handledirsep If this is specified, the mapper will treat a \ character in a filename as a / for the purposes of matching. This attribute can be true or false, the default is false. This attribute is useful for cross-platform build files. Since Ant 1.6.3.

No

An example: <pathconvert property="x" targetos="unix"> <path path="Aj.Java"/> <chainedmapper> <flattenmapper/> <regexpmapper from="a(.*)\.java" to="\1.java.bak" casesensitive="no"/> </chainedmapper> </pathconvert> <echo>x is ${x}</echo>

will output "x is j.java.bak". and <pathconvert property="hd.prop" targetos="windows"> <path path="d\e/f\j.java"/> <chainedmapper> <regexpmapper from="${basedir}/d/e/(.*)" to="\1" handledirsep="yes"/> </chainedmapper>

Page 61: Ant

</pathconvert>

will set hd.prop to "f\j.java". packageSharing the same syntax as the glob mapper, the package mapper replaces directory separators found in the matched source pattern with dots in the target pattern placeholder. This mapper is particularly useful in combination with <uptodate> and <junit> output.Example: <mapper type="package" from="*Test.java" to="TEST-*Test.xml"/><packagemapper from="*Test.java" to="TEST-*Test.xml"/>

Source file name Target file name

org/apache/tools/ant/util/PackageMapperTest.java TEST-org.apache.tools.ant.util.PackageMapperTest.xml

org/apache/tools/ant/util/Helper.java ignored

unpackage (since Ant 1.6.0)This mapper is the inverse of the package mapper. It replaces the dots in a package name with directory separators. This is useful for matching XML formatter results against their JUnit test test cases. The mapper shares the sample syntax as the glob mapper. Example: <mapper type="unpackage" from="TEST-*Test.xml" to="${test.src.dir}/*Test.java"><unpackagemapper from="TEST-*Test.xml" to="${test.src.dir}/*Test.java">

Source file name Target file name

TEST-org.acme.AcmeTest.xml ${test.src.dir}/org/acme/AcmeTest.java

composite (since Ant 1.6.2)This mapper implementation can contain multiple nested mappers. File mapping is performed by passing the source filename to each nested <mapper> in turn, returning all results. The to and from attributes are ignored.Examples: <compositemapper> <identitymapper/> <packagemapper from="*.java" to="*"/></compositemapper>

Source file name Target file names

foo/bar/A.javafoo/bar/A.java

foo.bar.A

The composite mapper has no corresponding <mapper type> attribute. chained (since Ant 1.6.2)This mapper implementation can contain multiple nested mappers. File mapping is performed by passing the source filename to the first nested mapper, its results to the second, and so on. The target filenames generated by the last nested mapper comprise the ultimate results of the mapping operation. The to and from attributes are ignored.Examples: <chainedmapper> <flattenmapper/> <globmapper from="*" to="new/path/*"/> <mapper> <globmapper from="*" to="*1"/> <globmapper from="*" to="*2"/> </mapper></chainedmapper>

Source file name Target file names

foo/bar/A.javanew/path/A.java1

new/path/A.java2

boo/far/B.java new/path/B.java1

Page 62: Ant

new/path/B.java2

The chained mapper has no corresponding <mapper type> attribute. filtermapper (since Ant 1.6.3)This mapper implementation applies a filterchain to the source file name. Examples: <filtermapper> <replacestring from="\" to="/"/></filtermapper>

Source file name Target file names

foo\bar\A.java foo/bar/A.java

<filtermapper> <scriptfilter language="beanshell"> self.setToken(self.getToken().toUpperCase()); </scriptfilter></filtermapper>

Source file name Target file names

foo\bar\A.java FOO\BAR\A.JAVA

The filtermapper has no corresponding <mapper type> attribute. scriptmapper (since Ant 1.7)This mapper executes a script written in Apache BSF or JSR 223 supported language, once per file to map.The script can be declared inline or in a specified file. See the Script task for an explanation of scripts and dependencies.

Attribute Description Required

language Scripting language Yes

manager The script engine manager to use. See the script task for using this attribute. No - default is "auto"

src File containing the script No

setbeans whether to have all properties, references and targets as global variables in the script. No, default is "true".

classpath The classpath to pass into the script. No

classpathref The classpath to use, given as a reference to a path defined elsewhere. No

This filename mapper can take a nested <classpath> element. See the script task on how to use this element. Example: <scriptmapper language="javascript"> self.addMappedName(source.toUpperCase()); self.addMappedName(source.toLowerCase());</scriptmapper>

Source file name Target file names

foo\bar\A.javaFOO\BAR\A.JAVA

foo\bar\a.java

To use this mapper, the scripts need access to the source file, and the ability to return multiple mappings. Here are the relevant beans and their methods. The script is called once for every source file, with the list of mapped names reset after every invocation.

Script bean Description

source: String The file/path to map

self the scriptmapper itself

self.addMappedName(String name) Add a new mapping

self.clear() Reset the list of files.

The scriptmapper has no corresponding <mapper type> attribute.

Page 63: Ant

PropertySetSince Ant 1.6Groups a set of properties to be used by reference in a task that supports this.

Attribute Description Required

dynamic Whether to reevaluate the set everytime the set is used. Default is "true". No

negate Whether to negate results. If "true", all properties not selected by nested elements will be returned. Default is "false". Since Ant 1.6.2

No

Parameters specified as nested elementspropertyrefSelects properties from the current project to be included in the set.

Attribute Description Required

name Select the property with the given name. Exactly one of these.prefix Select the properties whose name starts with the given string.

regex Select the properties that match the given regular expression. Similar to regexp type mappers, this requires a supported regular expression library.

builtin Selects a builtin set of properties. Valid values for this attribute are all for all Ant properties, system for the system properties and commandline for all properties specified on the command line when invoking Ant (plus a number of special internal Ant properties).

propertysetA propertyset can be used as the set union of more propertysets.For example:<propertyset id="properties-starting-with-foo"> <propertyref prefix="foo"/></propertyset><propertyset id="properties-starting-with-bar"> <propertyref prefix="bar"/></propertyset><propertyset id="my-set"> <propertyset refid="properties-starting-with-foo"/> <propertyset refid="properties-starting-with-bar"/></propertyset>

collects all properties whose name starts with either "foo" or "bar" in the set named "my-set".

Page 64: Ant

mapperA mapper - at maximum one mapper can be specified. The mapper is used to change the names of the property keys, for example: <propertyset id="properties-starting-with-foo"> <propertyref prefix="foo"/> <mapper type="glob" from="foo*" to="bar*"/></propertyset>

collects all properties whose name starts with "foo", but changes the names to start with "bar" instead.If supplied, the nested mapper will be applied subsequent to any negation of matched properties.

Technologies: Hibernate, Spring, Lucene, OSCache, Tomcat, Dojo, DOJO-Ajax, DWR, SOLR, MySQL pt hotnews.rohttp://blog.tremend.ro/

De cautat pe net cartea: download Effective Java Second Edition

http://ant.apache.org/manual/tutorial-writing-tasks.html

There is a set of built-in tasks, along with a number of optional tasks, but it is also very easy to write your own.

Scrie si la bat-urile de build din Java doc daca se vrea sa se faca bat-uri profesionale sa se uite in directorul bin a lui ant.

Page 65: Ant

Java1.5+ proxy support (new for Ant1.7)When Ant starts up, if the -autoproxy command is supplied, Ant sets the java.net.useSystemProxies system property. This tells a Java1.5+ JVM to use the current set of property settings of the host environment. Other JVMs, such as the Kaffe and Apache Harmony runtimes, may also use this property in future. It is ignored on the Java1.4 and earlier runtimes. How Autoproxy worksWe are grateful for some input from Sun as to how the proxy code works under Java 1.5 and up. The java.net.useSystemProxies is checked only once, at startup time, the other checks (registry, gconf, system properties) are done dynamically whenever needed (socket connection, URL connection etc..). WindowsThe JVM goes straight to the registry, bypassing WinInet, as it is not present/consistent on all supported Windows platforms (it is part of IE, really). Java 7 may use the Windows APIs on the platforms when it is present. LinuxThe JVM uses the gconf library to look at specific entries. The GConf-2 settings used are: - /system/http_proxy/use_http_proxy boolean - /system/http_proxy/use_authentication boolean - /system/http_proxy/host string - /system/http_proxy/authentication_user string - /system/http_proxy/authentication_password string - /system/http_proxy/port int - /system/proxy/socks_host string - /system/proxy/mode string - /system/proxy/ftp_host string - /system/proxy/secure_host string - /system/proxy/socks_port int - /system/proxy/ftp_port int - /system/proxy/secure_port int - /system/proxy/no_proxy_for list - /system/proxy/gopher_host string - /system/proxy/gopher_port int

If you are using KDE or another GUI than Gnome, you can still use the gconf-editor tool to add these entries. Manual JVM optionsAny JVM can have its proxy options explicitly configured by passing the appropriate -D system property options to the runtime. Ant can be configured through all its shell scripts via the ANT_OPTS environment variable, which is a list of options to supply to Ant's JVM: For bash: export ANT_OPTS="-Dhttp.proxyHost=proxy -Dhttp.proxyPort=8080"

For csh/tcsh: setenv ANT_OPTS "-Dhttp.proxyHost=proxy -Dhttp.proxyPort=8080"

If you insert this line into the Ant shell script itself, it gets picked up by all continuous integration tools running on the system that call Ant via the command line. For Windows, set the ANT_OPTS environment variable in the appropriate "My Computer" properties dialog box (winXP), "Computer" properties (Vista) This mechanism works across Java versions, is cross-platform and reliable. Once set, all build files run via the command line will automatically have their proxy setup correctly, without needing any build file changes. It also apparently overrides Ant's automatic proxy settings options. It is limited in the following ways:

1. Does not work under IDEs. These need their own proxy settings changed2. Not dynamic enough to deal with laptop configuration changes.

Pune acest link in webservices.doc:

Page 66: Ant

http://java.sun.com/webservices/ vezi ca zice si de JAXP

Vezi ca in directoru.l ANT poti gasi modele de license, fisiere bat, etc.

http://ant.apache.org/faq.htmlhttp://ant.apache.org/problems.htmlhttp://wiki.apache.org/ant/EclipseAnthttp://wiki.apache.org/ant/FrontPage

Pune la final exemple de build files in speta cele din proiectul IPPD si mai pune sip e cel din exemplu primul.

<?xml version="1.0" encoding="UTF-8"?><!-- In production environments, this script depends on the following environment variables and parameters: --><!-- Must export ANT_OPTS="-Duser.install.root=$AIW/ws/profiles/aiw" --><!-- ${env.AIWHOME} set to Peak process user's home directory --><!-- ${env.AIW} set to root of Peak installation -->

<!-- Development Environment: To run this script in a development environment, --><!-- use the dev project target --><!-- This will set the dev property to enable the development targets and disable the production ones. --><!-- ant -factivate.xml dev -->

<!-- There are three targets: primary, secondary, and aixsecondary.The System Activator will run the appropriate target based on which kind of node we are installing on.

The tasks for production environments:Run database script to create tables and initialize rowsCopy server resources to the classpath areaDeploy the web resources to the web serverCopy the help resources to the help areaRun activation utility Update the system classpath

The tasks for development environments:Run database script to create tables and initialize rowsCopy the web resources to ../UI_Web/WebContentRun activation utility

Page 67: Ant

-->

<project name="ReportsExtensionActivation" default="primary" basedir=".">

<description>Ant script for activation of reports</description>

<taskdef name="chown" classname="org.apache.tools.ant.taskdefs.optional.unix.Chown"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar" /> </classpath> </taskdef>

<taskdef name="chgrp" classname="org.apache.tools.ant.taskdefs.optional.unix.Chgrp"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar" /> </classpath> </taskdef>

<!--================ Define Project Targets ================--> <target name="primary" depends="installAlphablox,stopServers,setProperties,activationTaskDef,runDBScript,copyServerResources,copyWebResources,copyHelpResources,activateServerAndWeb,runDBImportScript,activateHelp,addCrontabEntry,wsReportsConfig" description="Activate on a Primary installation">

<echo>Activating on Primary</echo></target>

<target name="secondary" depends="copyServerResources" description="Activate on a Secondary installation">

<echo>Activating on Secondary</echo></target>

<target name="aixsecondary" depends="copyServerResources" description="Activate on an AIX secondary">

<echo>No action taken</echo></target>

<target name="dev" depends="dev_setProperties,dev_activationTaskDef,dev_RunDBScript,copyWebResources,activateServerAndWeb" description="Activate within the RAD development environment">

<echo>Activating within RAD environment</echo></target>

<!--================ Set Properties ================--><!-- Set global properties --><property environment="env" /><property name="shortname" value="reports"/><property name="manifest" value="extension.xml" /><property name="AIW" value="${env.AIW}" /><property name="aiwUsr" value="aiw1" /><property name="abDir" value="/opt/IBM/DB2Alphablox" />

Page 68: Ant

<!-- Install Alphablox --><target name="installAlphablox"

description="Install Alphablox for reports"><echo message="Installing Alphablox..."/><exec executable="installAlphablox.sh" dir="${AIW}/workflowsystem" vmlauncher="false"

failonerror="true"/><echo message="Copying datasource properites file..."/><mkdir dir="${abDir}/repository/data/rptdb"/><copy todir="${abDir}/repository/data/rptdb" file="${AIW}/extensions/reports/rptdb.properties"

overwrite="yes" /><chmod file="${abDir}/repository/data/rptdb/rptdb.properties" perm="777"/>

</target>

<!-- Add crontab entry --><target name="addCrontabEntry"

description="Add a crontab entry for reports"><echo message="Copying crontab files..."/><copy todir="${AIW}/bin" file="${AIW}/extensions/reports/clean_reports_database.pl"

overwrite="yes" /><copy todir="${AIW}/bin" file="${AIW}/extensions/reports/reports.cron" overwrite="yes" /><copy todir="${AIW}/bin" file="${AIW}/extensions/reports/reports.cron.sh" overwrite="yes" /><echo message="Adding crontab entry..."/><chmod file="${AIW}/bin/reports.cron.sh" perm="775"/><chmod file="${AIW}/bin/clean_reports_database.pl" perm="775"/><exec executable="reports.cron.sh" vmlauncher="false" dir="${AIW}/bin">

<arg value="${aiwUsr}"/></exec>

</target>

<!-- Stop servers --><target name="stopServers"

description="Prepare the IPPD Servers for installation by stopping all but the DB manager"><echo message="Stopping Servers..."/><echo message="${AIW}"/><exec executable="server.pl" dir="${AIW}/bin" >

<arg line="-u${aiwUsr} stop"/></exec>

<exec executable="su" dir="${AIW}/extensions/reports/db" failonerror="false"><arg line ="- ${aiwUsr} -c 'db2start ' " />

</exec><echo message="db2started"/>

</target>

<!-- Set local properties --> <target name="setProperties" description="Set properties required for activating on a server"> <echo>Setting properties</echo> <property name="resource.root" value="${AIW}/ws/profiles/aiw/installedApps/DefaultNode/aiw.ear.ear/UI_Web.war" /> </target>

<target name="dev_setProperties" description="Set properties required for activating within RAD"> <echo>Setting properties</echo> <property name="resource.root" value="../UI_Web/WebContent" />

Page 69: Ant

</target>

<!--================ Define Ant Tasks, used by the targets ================--><!-- Extension Activation Utility task --><target name="activationTaskDef" description="Define the Activation Ant Task for activating on a server"> <echo>Establishing Activation Ant task</echo>

<taskdef name="activateAIWExtension" classname="com.ibm.aiw.extension.activation.anttask.ActivateAIWExtension" classpath="${env.CLASSPATH}"/>

</target>

<target name="dev_activationTaskDef" description="Define the Activation Ant task for activating within RAD"> <echo>Establishing Activation Ant task</echo>

<property name="activationClassPath" value="./bin:../FacadeImpl:../Instance:../Instance/afpUtil.jar:../Server:../Secondary:../Util:../Primary:../Interfaces:../Extension:../Server_API:../Server_API/bin:../UI_Reporting:../Reports_Server:${env.CLASSPATH}:${env.DB2_DRIVER_PATH}" />

<taskdef name="activateAIWExtension" classname="com.ibm.aiw.extension.activation.anttask.ActivateAIWExtension"

classpath="${activationClassPath}"/></target>

<!--================ Database Targets ================--><target name="runDBScript"

description="Create database tables with SQL script"><echo>Running Database Script</echo>

<exec dir="${AIW}/extensions/reports/db/" executable="perl" failonerror="false"><arg line="setDB2ForUDF.pl"/>

</exec> <exec executable="su" dir="${AIW}/extensions/reports/db" failonerror="false"> <arg line ="- ${aiwUsr} -c '/opt/IBM/aiw/V1.0/extensions/reports/db/dbUtilForReports.pl y n /opt/IBM/aiw/V1.0/extensions/reports/db/ ' " />

</exec>

<exec executable="su" dir="${AIW}/extensions/reports/db" failonerror="false"> <arg line ="- ${aiwUsr} -c '/opt/IBM/aiw/V1.0/extensions/reports/db/migrateToPTF1.pl' " />

</exec>

<exec executable="su" dir="${AIW}/workflowsystem" failonerror="false"><arg line ="- ${aiwUsr} -c '${AIW}/workflowsystem/alterTableVolatile.pl rptdb' " />

</exec></target>

<target name="dev_RunDBScript" description="Create database tables with SQL script">

<echo>Running Database Script</echo><exec executable="db2cmd" failonerror="true" >

<arg value ="/c"/><arg value="perl.exe"/><arg value="../extension/bin/runSQL.pl"/><arg value="db/sampext.sql"/>

</exec></target>

Page 70: Ant

<!--================ Activation Targets ================--><target name="activateServerAndWeb"

description="Activate database, server, and web components by calling the activateAIWExtension Task"><!-- Run the AIW Extension Activation Utility --><echo>Activating Extension</echo><activateAIWExtension manifest="${manifest}"

resourceRoot="${resource.root}"

requestedActivators="com.ibm.aiw.extension.activation.activators.model.ModelActivator,com.ibm.aiw.extension.activation.activators.view.ViewActivator,com.ibm.aiw.extension.activation.activators.controller.ControllerActivator"/>

<echo>SUCCESSFUL</echo></target>

<target name="activateHelp" description="Activate help components (plugin.xml, topic files, etc) by calling the activateAIWExtension

Task"><echo>Activating Help</echo><activateAIWExtension manifest="${manifest}"

resourceRoot="${AIW}/help/plugins/com.ibm.printers.aiw.nl1/nl"

requestedActivators="com.ibm.aiw.extension.activation.activators.help.HelpActivator"/><delete dir="${AIW}/help/configuration/org.eclipse.core.runtime"/><delete dir="${AIW}/help/configuration/org.eclipse.osgi"/><delete dir="${AIW}/help/configuration/org.eclipse.help.base"/><delete dir="${AIW}/help/configuration/org.eclipse.update"/>

</target>

<!--================ Copy Targets ================--><target name="copyServerResources"

description="Copy server-related resources to the appropriate place"> <echo>Copying new Server files</echo>

<copy todir="/aiw/${aiwUsr}/lib" file="${AIW}/extensions/reports/UI_Web.war/WEB-INF/lib/reports_server.jar" overwrite="yes" />

<copy todir="/aiw/${aiwUsr}/lib" file="${AIW}/extensions/reports/UI_Web.war/WEB-INF/lib/ui_reporting.jar" overwrite="yes" />

<chown file="/aiw/${aiwUsr}/lib/reports_server.jar" owner="${aiwUsr}"/> <chgrp file="/aiw/${aiwUsr}/lib/reports_server.jar" group="aiwgrp1"/>

<chown file="/aiw/${aiwUsr}/lib/ui_reporting.jar" owner="${aiwUsr}"/><chgrp file="/aiw/${aiwUsr}/lib/ui_reporting.jar" group="aiwgrp1"/>

</target>

<target name="copyWebResources" description="Copy web resources (jars, jsp, graphics, etc) into WebSphere's installation

directory"><copy todir="${resource.root}" overwrite="yes">

<fileset dir="UI_Web.war"/></copy>

<mkdir dir="${resource.root}/reports/tagImages"/><mkdir dir="${resource.root}/reports/tagScripts"/>

<!-- copy tag resources to the reporting context. This is a work around because the tag scripts use relative paths that don't work correctly with struts modules paths. -->

<copy todir="${resource.root}/reports/tagImages/" >

Page 71: Ant

<fileset dir="${resource.root}/tagImages" /> </copy>

<copy todir="${resource.root}/reports/tagScripts/" ><fileset dir="${resource.root}/tagScripts" />

</copy></target>

<target name="copyHelpResources" description="Copy help resources (xml, html) into the help installation directories"><echo>Making new Help directories</echo><mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt"/><mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/de"/>

<mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/en"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/es"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/fr"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/it"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/ja"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/ru"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/zh/TW"/>

<echo>Copying new Help resources</echo><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt">

<fileset dir="help/en" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/de">

<fileset dir="help/de/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/en">

<fileset dir="help/en/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/es">

<fileset dir="help/es/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/fr">

<fileset dir="help/fr/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/it">

<fileset dir="help/it/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/ja">

<fileset dir="help/ja/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/ru">

<fileset dir="help/ru/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/zh/TW">

<fileset dir="help/zh/TW" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/"

file="help/fragment.xml" /></target>

<target name="wsReportsConfig"><exec executable="su" dir="${AIW}/extensions/reports/db" failonerror="false">

Page 72: Ant

<arg line ="- ${aiwUsr} -c 'db2start ' " /></exec><echo message="db2started"/>

<exec executable="su" dir="${AIW}/ws/bin/" ><arg line="- ${aiwUsr} -c 'LIBPATH=/usr/opt/db2_08_01/lib:$LIBPATH ;

startServer.sh aiwServer'"/></exec>

<exec executable="wsadmin.sh" dir="${AIW}/ws/bin/" failonerror="true"> <arg line ="-f ${AIW}/extensions/reports/wsReportsConfig.jacl" /></exec>

<exec executable="su" dir="${AIW}/bin" ><arg line="- ${aiwUsr} -c 'stopaiw'"/>

</exec>

<exec executable="su" dir="${AIW}/extensions/reports/db" failonerror="false"><arg line ="- ${aiwUsr} -c 'db2start ' " />

</exec><echo message="db2started"/>

</target>

<!--================ NLS Targets ================--><target name="runDBImportScript"

description="Import translated descriptions with SQL script"><echo>Running Database Script</echo>

<exec executable="su" dir="${AIW}/extensions/reports" failonerror="false"> <arg line ="- ${aiwUsr} -c 'cd ${AIW}/extensions/reports/db; ${AIW}/extensions/reports/db/importDescriptions.pl ' " />

</exec></target>

<!--================ Clean Targets ================--><target name="dev_cleanWebResources" depends="dev_setProperties"

description="Remove copied web resources and undo changes to modified web resources within RAD"><echo message="Cleaning activated resources from ${resource.root}" />

<!-- Run 2 XSL transformations, the first to generate the second, and the second, which cleans the resources specified by

../Extension/resources/webresources.cfg of all changes made by this extension --><xslt in="${manifest}" out="clean.xsl" style="../Extension/resources/genclean.xsl"/><xslt basedir="${resource.root}" destdir="WebContent"

includesfile="../Extension/resources/webresources.cfg" style="clean.xsl"> <mapper type="identity"/></xslt>

<!-- Copy the cleaned files into the resource root, overwriting the old files --><copy todir="${resource.root}" overwrite="yes">

<fileset dir="WebContent"/></copy>

<!-- Cleanup temp files used in the above transformations -->

Page 73: Ant

<delete file="clean.xsl"/><delete dir="WebContent"/>

<!-- Cleanup files previously copied to the resource root by this extension --><delete dir="${resource.root}/${shortname}"/><delete dir="${resource.root}/WEB-INF/${shortname}"/><delete file="${resource.root}/WEB-INF/lib/${shortname}.jar"/>

</target>

</project>

_____________________________<?xml version="1.0" encoding="UTF-8"?><!-- In production environments, this script depends on the following environment variables and parameters: --><!-- Must export ANT_OPTS="-Duser.install.root=$AIW/ws/profiles/aiw" --><!-- ${env.AIWHOME} set to Peak process user's home directory --><!-- ${env.AIW} set to root of Peak installation -->

<!-- Development Environment: To run this script in a development environment, --><!-- use the dev project target --><!-- This will set the dev property to enable the development targets and disable the production ones. --><!-- ant -factivate.xml dev -->

<!-- There are three targets: primary, secondary, and aixsecondary.The System Activator will run the appropriate target based on which kind of node we are installing on.

The tasks for production environments:Run database script to create tables and initialize rowsCopy server resources to the classpath areaDeploy the web resources to the web serverCopy the help resources to the help areaRun activation utility Update the system classpath

The tasks for development environments:Run database script to create tables and initialize rowsCopy the web resources to ../UI_Web/WebContentRun activation utility

-->

<project name="ReportsExtensionActivation" default="primary" basedir=".">

<description>Ant script for activation of reports</description>

<taskdef name="chown" classname="org.apache.tools.ant.taskdefs.optional.unix.Chown"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar" /> </classpath> </taskdef>

<taskdef name="chgrp" classname="org.apache.tools.ant.taskdefs.optional.unix.Chgrp"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar" /> </classpath> </taskdef>

<!--================ Define Project Targets ================--> <target name="primary" depends="installAlphablox,stopServers,setProperties,activationTaskDef,runDBScript,copyServerResou

Page 74: Ant

rces,copyWebResources,copyHelpResources,activateServerAndWeb,runDBImportScript,activateHelp,addCrontabEntry,wsReportsConfig" description="Activate on a Primary installation">

<echo>Activating on Primary</echo></target>

<target name="secondary" depends="copyServerResources" description="Activate on a Secondary installation">

<echo>Activating on Secondary</echo></target>

<target name="aixsecondary" depends="copyServerResources" description="Activate on an AIX secondary">

<echo>No action taken</echo></target>

<target name="dev" depends="dev_setProperties,dev_activationTaskDef,dev_RunDBScript,copyWebResources,activateServerAndWeb" description="Activate within the RAD development environment">

<echo>Activating within RAD environment</echo></target>

<!--================ Set Properties ================--><!-- Set global properties --><property environment="env" /><property name="shortname" value="reports"/><property name="manifest" value="extension.xml" /><property name="AIW" value="${env.AIW}" /><property name="aiwUsr" value="aiw1" /><property name="abDir" value="/opt/IBM/DB2Alphablox" />

<!-- Install Alphablox --><target name="installAlphablox"

description="Install Alphablox for reports"><echo message="Installing Alphablox..."/><exec executable="installAlphablox.sh" dir="${AIW}/workflowsystem" vmlauncher="false"

failonerror="true"/><echo message="Copying datasource properites file..."/><mkdir dir="${abDir}/repository/data/rptdb"/><copy todir="${abDir}/repository/data/rptdb"

file="${AIW}/extensions/reports/rptdb.properties" overwrite="yes" /><chmod file="${abDir}/repository/data/rptdb/rptdb.properties" perm="777"/>

</target>

<!-- Add crontab entry --><target name="addCrontabEntry"

description="Add a crontab entry for reports"><echo message="Copying crontab files..."/><copy todir="${AIW}/bin"

file="${AIW}/extensions/reports/clean_reports_database.pl" overwrite="yes" /><copy todir="${AIW}/bin" file="${AIW}/extensions/reports/reports.cron"

overwrite="yes" /><copy todir="${AIW}/bin" file="${AIW}/extensions/reports/reports.cron.sh"

overwrite="yes" /><echo message="Adding crontab entry..."/><chmod file="${AIW}/bin/reports.cron.sh" perm="775"/><chmod file="${AIW}/bin/clean_reports_database.pl" perm="775"/><exec executable="reports.cron.sh" vmlauncher="false" dir="${AIW}/bin">

<arg value="${aiwUsr}"/></exec>

</target>

<!-- Stop servers -->

Page 75: Ant

<target name="stopServers"description="Prepare the IPPD Servers for installation by stopping all but the DB

manager"><echo message="Stopping Servers..."/><echo message="${AIW}"/><exec executable="server.pl" dir="${AIW}/bin" >

<arg line="-u${aiwUsr} stop"/></exec>

<exec executable="su" dir="${AIW}/extensions/reports/db" failonerror="false"><arg line ="- ${aiwUsr} -c 'db2start ' " />

</exec><echo message="db2started"/>

</target>

<!-- Set local properties --> <target name="setProperties" description="Set properties required for activating on a server"> <echo>Setting properties</echo> <property name="resource.root" value="${AIW}/ws/profiles/aiw/installedApps/DefaultNode/aiw.ear.ear/UI_Web.war" /> </target>

<target name="dev_setProperties" description="Set properties required for activating within RAD"> <echo>Setting properties</echo> <property name="resource.root" value="../UI_Web/WebContent" /> </target>

<!--================ Define Ant Tasks, used by the targets ================--><!-- Extension Activation Utility task --><target name="activationTaskDef" description="Define the Activation Ant Task for activating on a server"> <echo>Establishing Activation Ant task</echo>

<taskdef name="activateAIWExtension" classname="com.ibm.aiw.extension.activation.anttask.ActivateAIWExtension" classpath="${env.CLASSPATH}"/>

</target>

<target name="dev_activationTaskDef" description="Define the Activation Ant task for activating within RAD"> <echo>Establishing Activation Ant task</echo>

<property name="activationClassPath" value="./bin:../FacadeImpl:../Instance:../Instance/afpUtil.jar:../Server:../Secondary:../Util:../Primary:../Interfaces:../Extension:../Server_API:../Server_API/bin:../UI_Reporting:../Reports_Server:${env.CLASSPATH}:${env.DB2_DRIVER_PATH}" />

<taskdef name="activateAIWExtension" classname="com.ibm.aiw.extension.activation.anttask.ActivateAIWExtension"

classpath="${activationClassPath}"/></target>

<!--================ Database Targets ================--><target name="runDBScript"

description="Create database tables with SQL script"><echo>Running Database Script</echo>

<exec dir="${AIW}/extensions/reports/db/" executable="perl" failonerror="false"><arg line="setDB2ForUDF.pl"/>

</exec> <exec executable="su" dir="${AIW}/extensions/reports/db" failonerror="false"> <arg line ="- ${aiwUsr} -c '/opt/IBM/aiw/V1.0/extensions/reports/db/dbUtilForReports.pl y n /opt/IBM/aiw/V1.0/extensions/reports/db/ ' " />

</exec>

<exec executable="su" dir="${AIW}/extensions/reports/db" failonerror="false"> <arg line ="- ${aiwUsr} -c

'/opt/IBM/aiw/V1.0/extensions/reports/db/migrateToPTF1.pl' " />

Page 76: Ant

</exec>

<exec executable="su" dir="${AIW}/workflowsystem" failonerror="false"><arg line ="- ${aiwUsr} -c '${AIW}/workflowsystem/alterTableVolatile.pl rptdb'

" /></exec>

</target>

<target name="dev_RunDBScript" description="Create database tables with SQL script">

<echo>Running Database Script</echo><exec executable="db2cmd" failonerror="true" >

<arg value ="/c"/><arg value="perl.exe"/><arg value="../extension/bin/runSQL.pl"/><arg value="db/sampext.sql"/>

</exec></target>

<!--================ Activation Targets ================--><target name="activateServerAndWeb"

description="Activate database, server, and web components by calling the activateAIWExtension Task">

<!-- Run the AIW Extension Activation Utility --><echo>Activating Extension</echo><activateAIWExtension manifest="${manifest}"

resourceRoot="${resource.root}"

requestedActivators="com.ibm.aiw.extension.activation.activators.model.ModelActivator,com.ibm.aiw.extension.activation.activators.view.ViewActivator,com.ibm.aiw.extension.activation.activators.controller.ControllerActivator"/>

<echo>SUCCESSFUL</echo></target>

<target name="activateHelp" description="Activate help components (plugin.xml, topic files, etc) by calling the

activateAIWExtension Task"><echo>Activating Help</echo><activateAIWExtension manifest="${manifest}"

resourceRoot="${AIW}/help/plugins/com.ibm.printers.aiw.nl1/nl"

requestedActivators="com.ibm.aiw.extension.activation.activators.help.HelpActivator"/><delete dir="${AIW}/help/configuration/org.eclipse.core.runtime"/><delete dir="${AIW}/help/configuration/org.eclipse.osgi"/><delete dir="${AIW}/help/configuration/org.eclipse.help.base"/><delete dir="${AIW}/help/configuration/org.eclipse.update"/>

</target>

<!--================ Copy Targets ================--><target name="copyServerResources"

description="Copy server-related resources to the appropriate place"> <echo>Copying new Server files</echo>

<copy todir="/aiw/${aiwUsr}/lib" file="${AIW}/extensions/reports/UI_Web.war/WEB-INF/lib/reports_server.jar" overwrite="yes" />

<copy todir="/aiw/${aiwUsr}/lib" file="${AIW}/extensions/reports/UI_Web.war/WEB-INF/lib/ui_reporting.jar" overwrite="yes" />

<chown file="/aiw/${aiwUsr}/lib/reports_server.jar" owner="${aiwUsr}"/> <chgrp file="/aiw/${aiwUsr}/lib/reports_server.jar" group="aiwgrp1"/>

<chown file="/aiw/${aiwUsr}/lib/ui_reporting.jar" owner="${aiwUsr}"/><chgrp file="/aiw/${aiwUsr}/lib/ui_reporting.jar" group="aiwgrp1"/>

</target>

<target name="copyWebResources" description="Copy web resources (jars, jsp, graphics, etc) into WebSphere's

installation directory"><copy todir="${resource.root}" overwrite="yes">

Page 77: Ant

<fileset dir="UI_Web.war"/></copy>

<mkdir dir="${resource.root}/reports/tagImages"/><mkdir dir="${resource.root}/reports/tagScripts"/>

<!-- copy tag resources to the reporting context. This is a work around because the tag scripts use

relative paths that don't work correctly with struts modules paths. --> <copy todir="${resource.root}/reports/tagImages/" >

<fileset dir="${resource.root}/tagImages" /> </copy>

<copy todir="${resource.root}/reports/tagScripts/" ><fileset dir="${resource.root}/tagScripts" />

</copy></target>

<target name="copyHelpResources" description="Copy help resources (xml, html) into the help installation

directories"><echo>Making new Help directories</echo><mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt"/><mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/de"/>

<mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/en"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/es"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/fr"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/it"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/ja"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/ru"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/zh/TW"/>

<echo>Copying new Help resources</echo><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt">

<fileset dir="help/en" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/de">

<fileset dir="help/de/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/en">

<fileset dir="help/en/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/es">

<fileset dir="help/es/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/fr">

<fileset dir="help/fr/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/it">

<fileset dir="help/it/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/ja">

<fileset dir="help/ja/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/ru">

<fileset dir="help/ru/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/nl/zh/TW">

<fileset dir="help/zh/TW" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.rpt.nl1/"

file="help/fragment.xml" /></target>

<target name="wsReportsConfig"><exec executable="su" dir="${AIW}/extensions/reports/db" failonerror="false">

<arg line ="- ${aiwUsr} -c 'db2start ' " /></exec><echo message="db2started"/>

Page 78: Ant

<exec executable="su" dir="${AIW}/ws/bin/" ><arg line="- ${aiwUsr} -c 'LIBPATH=/usr/opt/db2_08_01/lib:

$LIBPATH ; startServer.sh aiwServer'"/></exec>

<exec executable="wsadmin.sh" dir="${AIW}/ws/bin/" failonerror="true"> <arg line ="-f ${AIW}/extensions/reports/wsReportsConfig.jacl" /></exec>

<exec executable="su" dir="${AIW}/bin" ><arg line="- ${aiwUsr} -c 'stopaiw'"/>

</exec>

<exec executable="su" dir="${AIW}/extensions/reports/db" failonerror="false"><arg line ="- ${aiwUsr} -c 'db2start ' " />

</exec><echo message="db2started"/>

</target>

<!--================ NLS Targets ================--><target name="runDBImportScript"

description="Import translated descriptions with SQL script"><echo>Running Database Script</echo>

<exec executable="su" dir="${AIW}/extensions/reports" failonerror="false"> <arg line ="- ${aiwUsr} -c 'cd ${AIW}/extensions/reports/db; ${AIW}/extensions/reports/db/importDescriptions.pl ' " />

</exec></target>

<!--================ Clean Targets ================--><target name="dev_cleanWebResources" depends="dev_setProperties"

description="Remove copied web resources and undo changes to modified web resources within RAD">

<echo message="Cleaning activated resources from ${resource.root}" />

<!-- Run 2 XSL transformations, the first to generate the second, and the second, which cleans the resources specified by

../Extension/resources/webresources.cfg of all changes made by this extension -->

<xslt in="${manifest}" out="clean.xsl" style="../Extension/resources/genclean.xsl"/><xslt basedir="${resource.root}" destdir="WebContent"

includesfile="../Extension/resources/webresources.cfg" style="clean.xsl"> <mapper type="identity"/></xslt>

<!-- Copy the cleaned files into the resource root, overwriting the old files --><copy todir="${resource.root}" overwrite="yes">

<fileset dir="WebContent"/></copy>

<!-- Cleanup temp files used in the above transformations --><delete file="clean.xsl"/><delete dir="WebContent"/>

<!-- Cleanup files previously copied to the resource root by this extension --><delete dir="${resource.root}/${shortname}"/><delete dir="${resource.root}/WEB-INF/${shortname}"/><delete file="${resource.root}/WEB-INF/lib/${shortname}.jar"/>

</target>

</project>

______________________________<?xml version="1.0" encoding="UTF-8"?>

Page 79: Ant

<!-- In production environments, this script depends on the following environment variables and parameters: --><!-- Must export ANT_OPTS="-Duser.install.root=$AIW/ws/profiles/aiw" --><!-- ${env.AIWHOME} set to Peak process user's home directory --><!-- ${env.AIW} set to root of Peak installation -->

<!-- Development Environment: To run this script in a development environment, --><!-- use the dev project target --><!-- This will set the dev property to enable the development targets and disable the production ones. --><!-- ant -factivate.xml dev -->

<!-- There are three targets: primary, secondary, and aixsecondary. The System Activator will run the appropriate target based on which kind of node we are installing on. The tasks for production environments: Run database script to create tables and initialize rows Copy server resources to the classpath area Deploy the web resources to the web server Copy the help resources to the help area Run activation utility Update the system classpath The tasks for development environments: Run database script to create tables and initialize rows Copy the web resources to ../UI_Web/WebContent Run activation utility -->

<project name="DOCExtensionActivation" default="primary" basedir="."> <description>Ant script for activation of DOC</description>

<import file="commonActivate.xml" />

<taskdef name="chown" classname="org.apache.tools.ant.taskdefs.optional.unix.Chown"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar" /> </classpath> </taskdef>

<taskdef name="chgrp" classname="org.apache.tools.ant.taskdefs.optional.unix.Chgrp"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar" /> </classpath> </taskdef>

<!--================ Define Project Targets ================--> <target name="primary" depends="precondition, increaseJVMSize, setProperties, activationTaskDef, runDBScript, copyServerResources,

Page 80: Ant

copyWebResources, copyHelpResources, activateServerAndWeb, activateHelp, localizeActivation" description="Activate on a Primary installation"> </target>

<target name="secondary" depends="copyServerResources" description="Activate on a Secondary installation"> </target>

<target name="aixsecondary" depends="copyServerResources" description="Activate on an AIX secondary"> <echo>No action taken</echo> </target>

<!-- This is the original depends line from dev target. Update the depends statement in the dev target as things start working: depends="dev_setProperties,dev_activationTaskDef,dev_RunDBScriptWin,copyWebResources,activateServerAndWeb" --> <target name="dev" depends="dev_setProperties,dev_activationTaskDef,copyWebResources,activateServerAndWeb" description="Activate within the RAD development environment"> <echo>Activating DOC within RAD environment</echo> </target>

<!--================ Set Properties ================--> <!-- Set global properties --> <property environment="env" /> <property name="shortname" value="doc" /> <property name="manifest" value="extension.xml" /> <property name="AIW" value="${env.AIW}" /> <property name="aiwUsr" value="aiw1" />

<!-- Establish precondition for activation --> <target name="precondition"> <exec executable="su"> <arg line="- ${aiwUsr} -c 'db2start | grep -v SQL1026N' " /> </exec> </target>

<!-- Set local properties --> <target name="setProperties" description="Set properties required for activating on a server"> <echo>Setting properties for activations </echo> <property name="resource.root" value="${AIW}/ws/profiles/aiw/installedApps/DefaultNode/aiw.ear.ear/UI_Web.war" /> <echo>resource.root = ${resource.root}</echo> </target>

<target name="dev_setProperties" description="Set properties required for activating within RAD"> <property name="resource.root" value="${basedir}/../UI_Web/WebContent" /> <echo>resource.root = ${resource.root}</echo> </target>

Page 81: Ant

<!--================ Define Ant Tasks, used by the targets ================--> <!-- Extension Activation Utility task --> <target name="activationTaskDef" description="Define the Activation Ant Task for activating on a server"> <echo>Establishing Activation Ant task</echo> <taskdef name="activateAIWExtension" classname="com.ibm.aiw.extension.activation.anttask.ActivateAIWExtension" classpath="${env.CLASSPATH}" /> </target>

<target name="dev_activationTaskDef" description="Define the Activation Ant task for activating within RAD"> <echo>Establishing Activation Ant task</echo> <property name="activationClassPath" value="./bin:../Interfaces:../Secondary:../Server:../Secondary/afpUtil.jar:../UI_DOC/classes:../DOC_Server:${env.CLASSPATH}:${env.DB2_DRIVER_PATH}" /> <taskdef name="activateAIWExtension" classname="com.ibm.aiw.extension.activation.anttask.ActivateAIWExtension" classpath="${activationClassPath}" /> </target>

<!--================ Database Targets ================--> <target name="runDBScript" description="Create database tables with SQL script"> <echo>Running Database Script</echo> <delete dir="/aiw/${aiwUsr}/db2/doc/tbsp/"/> <delete dir="/aiw/${aiwUsr}/db2/doc/ixsp/"/> <exec executable="su" failonerror="true"> <arg value="-"/> <arg value="${aiwUsr}"/> <arg value="-c"/> <arg value="db2 connect to aiwdb; if [ $? -gt 2 ]; then exit 1; fi; TSDIR=/aiw/${aiwUsr}/db2/doc/tbsp/tmp001; mkdir -m 770 -p $TSDIR; chgrp db2grp1 $TSDIR; db2 -v &#34;create user temporary tablespace doc_temp_ts in database partition group ibmdefaultgroup pagesize 4096 managed by system using ('/aiw/${aiwUsr}/db2/doc/tbsp/tmp001/TEMP_TS') extentsize 32 prefetchsize 96 bufferpool ibmdefaultbp&#34; ; if [ $? -gt 2 ]; then exit 1; fi; cd ${AIW}/extensions/doc/db; db2 -stwv -ec -f db2DefaultLogParms.txt; if [ $? -gt 2 ]; then exit 1; fi; set -e; perl setDb2LocklistSize.pl aiwdb 30000 100000; perl activateDatabase.pl /aiw/${aiwUsr} doc"/> </exec> </target>

<target name="dev_RunDBScript" description="Create database tables with SQL script"> <echo>Running Database Script on linux</echo> <exec executable="db2cmd" failonerror="false"> <arg value="/c" />

Page 82: Ant

<arg value="perl.exe" /> <arg value="../DOC_Database/src/dbUtilForDOC.pl" /> <arg value="y" /> <arg value="../DOC_Database/src/" /> </exec> </target>

<target name="dev_RunDBScriptWin" description="Create database tables with SQL script"> <echo>Running Database Script on Windows</echo> <exec executable="db2cmd" failonerror="true"> <arg value="/c" /> <arg value="perl.exe" /> <arg value="..\DOC_Database\src\dbUtilForDOC.pl" /> <arg value="y" /> <arg value="..\DOC_Database\src\" /> </exec> </target>

<!-- Localizing the activation includes all tasks that are sensitive to the environment variable AIWLANG. --> <target name="localizeActivation" description="Localize the activation to current locale."> <exec executable="su" failonerror="true"> <arg value="-"/> <arg value="${aiwUsr}"/> <arg value="-c"/> <arg value="cd ${AIW}/extensions/doc/db &amp;&amp; ./localizeDescriptions ${env.AIWLANG} $PWD" /> </exec> </target>

<!--================ Activation Targets ================-->

<target name="activateServerAndWeb" description="Activate database, server, and web components by calling the activateAIWExtension Task"> <!-- Deleting old files --> <delete file="/aiw/${aiwUsr}/config/workbench/docWorkbenchCustomDefinitions.xml" /> <!-- Run the AIW Extension Activation Utility --> <echo>Activating Extension</echo> <activateAIWExtension manifest="${manifest}" resourceRoot="${resource.root}" requestedActivators="com.ibm.aiw.extension.activation.activators.model.ModelActivator, com.ibm.aiw.extension.activation.activators.view.ViewActivator, com.ibm.aiw.extension.activation.activators.controller.ControllerActivator" /> <echo>SUCCESSFUL extension.xml</echo> </target>

<target name="activateHelp" depends="copyHelpResources" description="Activate help components plugin.xml, topic files, etc) by calling the activateAIWExtension Task"> <echo>Activating Help</echo> <activateAIWExtension manifest="doc-help.xml" resourceRoot="${AIW}/help/plugins/com.ibm.printers.aiw.nl1/nl" requestedActivators="com.ibm.aiw.extension.activation.activators.help.HelpActivator" /> <delete dir="${AIW}/help/configuration/org.eclipse.core.runtime" /> <delete dir="${AIW}/help/configuration/org.eclipse.osgi" /> <delete dir="${AIW}/help/configuration/org.eclipse.help.base" />

Page 83: Ant

<delete dir="${AIW}/help/configuration/org.eclipse.update" /> </target>

<!--================ Copy Targets ================--> <target name="copyServerResources" description="Copy server-related resources to the appropriate place"> <echo>Copying new Server files</echo>

<echo>Copying ui_docjar</echo> <mkdir dir="/aiw/${aiwUsr}/lib" /> <copy todir="/aiw/${aiwUsr}/lib" file="${AIW}/extensions/doc/UI_Web.war/WEB-INF/lib/ui_doc.jar" overwrite="yes" /> <chown file="/aiw/${aiwUsr}/lib/ui_doc.jar" owner="${aiwUsr}" /> <chgrp file="/aiw/${aiwUsr}/lib/ui_doc.jar" group="aiwgrp1" />

<echo>Copying doc_server.jar</echo> <copy todir="/aiw/${aiwUsr}/lib" file="${AIW}/extensions/doc/UI_Web.war/WEB-INF/lib/doc_server.jar" overwrite="yes" /> <chown file="/aiw/${aiwUsr}/lib/doc_server.jar" owner="${aiwUsr}" /> <chgrp file="/aiw/${aiwUsr}/lib/doc_server.jar" group="aiwgrp1" />

<echo>Copying AFPDPD.jar</echo> <copy todir="/aiw/${aiwUsr}/lib/plugins" file="${AIW}/extensions/doc/AFPDPD.jar" overwrite="yes" /> <chown file="/aiw/${aiwUsr}/lib/plugins/AFPDPD.jar" owner="${aiwUsr}" /> <chgrp file="/aiw/${aiwUsr}/lib/plugins/AFPDPD.jar" group="aiwgrp1" />

<echo>Create AFPDPD.jar link from /aiw/aiw1</echo> <exec executable="ln" dir="${AIW}/bin"> <arg line=" -sf /aiw/${aiwUsr}/lib/plugins/AFPDPD.jar /aiw/${aiwUsr}/lib/AFPDPD.jar " /> </exec>

<echo>Copying docWorkbenchDefinitions.xml</echo> <mkdir dir="/aiw/${aiwUsr}/config/workbench" /> <copy todir="/aiw/${aiwUsr}/config/workbench" file="${AIW}/extensions/doc/docWorkbenchDefinitions.xml" overwrite="yes" /> <chown file="/aiw/${aiwUsr}/config/workbench/docWorkbenchDefinitions.xml" owner="${aiwUsr}" /> <chgrp file="/aiw/${aiwUsr}/config/workbench/docWorkbenchDefinitions.xml" group="aiwgrp1" />

<echo>Copying docJobIndexerControlFile.xml</echo> <copy todir="/aiw/${aiwUsr}/config/workbench" file="${AIW}/extensions/doc/docJobIndexerControlFile.xml" overwrite="yes" /> <chown file="/aiw/${aiwUsr}/config/workbench/docJobIndexerControlFile.xml" owner="${aiwUsr}" /> <chgrp file="/aiw/${aiwUsr}/config/workbench/docJobIndexerControlFile.xml" group="aiwgrp1" />

<echo>Copying files from the bin directory</echo> <copy-tree sourcedirstem="${basedir}" sourcedirfolder="bin" targetdir="/aiw/${aiwUsr}/" user="${aiwUsr}" group="aiwgrp1" overwrite="true" />

Page 84: Ant

<echo>Copying files from the config directory</echo> <copy-tree sourcedirstem="${basedir}" sourcedirfolder="config" targetdir="/aiw/${aiwUsr}/" user="${aiwUsr}" group="aiwgrp1" overwrite="false" />

</target>

<target name="dev_copyWebResources" description="stand alone target to call the copyWebResources target in a dev environement" depends="dev_setProperties, copyWebResources"> </target>

<target name="copyWebResources" description="Copy web resources (jars, jsp, graphics, etc) into WebSphere's installation directory"> <copy todir="${resource.root}" overwrite="yes"> <fileset dir="UI_Web.war" /> </copy> <mkdir dir="${resource.root}/doc/tagImages" /> <mkdir dir="${resource.root}/doc/tagScripts" /> <!-- copy tag resources to the doc context. This is a work around because the tag scripts use relative paths that don't work correctly with struts modules paths. --> <copy todir="${resource.root}/doc/tagImages/"> <fileset dir="${resource.root}/tagImages" />

</copy> <copy todir="${resource.root}/doc/tagScripts/"> <fileset dir="${resource.root}/tagScripts" /> </copy>

</target>

<target name="copyHelpResources" depends=" setProperties, activationTaskDef" description="Copy Doc2 help resources (xml, html) into the help installation directories"> <echo>Copying new Help resources</echo> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.doc" /> <condition property="helpdir" value="${AIW}/extensions/doc2"> <available file="${AIW}/extensions/doc2/en/doc-help.zip" type="file"/> </condition> <condition property="helpdir" value="${AIW}/extensions/doc1"> <available file="${AIW}/extensions/doc1/en/doc-help.zip" type="file"/> </condition> <condition property="helpdir" value="${AIW}/extensions/doc"> <available file="${AIW}/extensions/doc/en/doc-help.zip" type="file"/> </condition>

<available file="${helpdir}/en/doc-help.zip" type="file" property="copyEn" value="en" /> <available file="${helpdir}/fr/doc-help.zip" type="file" property="copyFr" value="fr" /> <available file="${helpdir}/it/doc-help.zip" type="file" property="copyIt" value="it" />

Page 85: Ant

<available file="${helpdir}/de/doc-help.zip" type="file" property="copyDe" value="de" /> <available file="${helpdir}/ru/doc-help.zip" type="file" property="copyRu" value="ru" /> <available file="${helpdir}/es/doc-help.zip" type="file" property="copyEs" value="es" /> <available file="${helpdir}/ja/doc-help.zip" type="file" property="copyJa" value="ja" /> <available file="${helpdir}/zh/TW/doc-help.zip" type="file" property="copyZhtw" value="zhtw" />

<delete dir="${AIW}/help/plugins/com.infoprint.aiw.doc"/> <delete dir="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/"/> <delete dir="${AIW}/extensions/doc/UI_Help/eclipse/plugins/com.infoprint.aiw.doc.nl1/"/>

<antcall target="unzipEnHelpFile" /> <antcall target="unzipFrHelpFile" /> <antcall target="unzipItHelpFile" /> <antcall target="unzipDeHelpFile" /> <antcall target="unzipRuHelpFile" /> <antcall target="unzipEsHelpFile" /> <antcall target="unzipJaHelpFile" /> <antcall target="unzipZhtwHelpFile" /> </target>

<!-- Unzip English Help --> <target name="unzipEnHelpFile" if="copyEn"> <unzip src="${helpdir}/en/doc-help.zip" dest="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/nl/en" /> <unzip src="${helpdir}/en/doc-help.zip" dest="${AIW}/extensions/doc/UI_Help/eclipse/plugins/com.infoprint.aiw.doc.nl1/nl/en/" /> <copy todir="${AIW}/extensions/doc/" overwrite="yes" file="${helpdir}/en/doc-help.xml" /> <copy todir="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/" overwrite="yes" file="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/nl/en/fragment.xml" /> <chmod file="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/fragment.xml" perm="775"/>

<exec executable="/bin/ln"> <arg value="-s" /> <arg value="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/nl/en" /> <arg value="${AIW}/help/plugins/com.infoprint.aiw.doc" /> </exec> </target>

<!-- Unzip French Help --> <target name="unzipFrHelpFile" if="copyFr"> <unzip src="${helpdir}/fr/doc-help.zip" dest="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/nl/fr" /> <unzip src="${helpdir}/fr/doc-help.zip" dest="${AIW}/extensions/doc/UI_Help/eclipse/plugins/com.infoprint.aiw.doc.nl1/nl/fr/" /> </target>

<!-- Unzip Italian Help --> <target name="unzipItHelpFile" if="copyIt"> <unzip src="${helpdir}/it/doc-help.zip" dest="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/nl/it"/> <unzip src="${helpdir}/it/doc-help.zip" dest="${AIW}/extensions/doc/UI_Help/eclipse/plugins/com.infoprint.aiw.doc.nl1/nl/it/" /> </target>

<!-- Unzip German Help --> <target name="unzipDeHelpFile" if="copyDe"> <unzip src="${helpdir}/de/doc-help.zip" dest="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/nl/de"/>

Page 86: Ant

<unzip src="${helpdir}/de/doc-help.zip" dest="${AIW}/extensions/doc/UI_Help/eclipse/plugins/com.infoprint.aiw.doc.nl1/nl/de/" /> </target>

<!-- Unzip Russian Help --> <target name="unzipRuHelpFile" if="copyRu"> <unzip src="${helpdir}/ru/doc-help.zip" dest="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/nl/ru"/> <unzip src="${helpdir}/ru/doc-help.zip" dest="${AIW}/extensions/doc/UI_Help/eclipse/plugins/com.infoprint.aiw.doc.nl1/nl/ru/" /> </target>

<!-- Unzip Spanish Help --> <target name="unzipEsHelpFile" if="copyEs"> <unzip src="${helpdir}/es/doc-help.zip" dest="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/nl/es"/> <unzip src="${helpdir}/es/doc-help.zip" dest="${AIW}/extensions/doc/UI_Help/eclipse/plugins/com.infoprint.aiw.doc.nl1/nl/es/" /> </target>

<!-- Unzip Japanese Help --> <target name="unzipJaHelpFile" if="copyJa"> <unzip src="${helpdir}/ja/doc-help.zip" dest="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/nl/ja"/> <unzip src="${helpdir}/ja/doc-help.zip" dest="${AIW}/extensions/doc/UI_Help/eclipse/plugins/com.infoprint.aiw.doc.nl1/nl/ja/" /> </target>

<!-- Unzip Chinese Help --> <target name="unzipZhtwHelpFile" if="copyZhtw"> <unzip src="${helpdir}/zh/TW/doc-help.zip" dest="${AIW}/help/plugins/com.infoprint.aiw.doc.nl1/nl/zh/TW"/> <unzip src="${helpdir}/zh/TW/doc-help.zip" dest="${AIW}/extensions/doc/UI_Help/eclipse/plugins/com.infoprint.aiw.doc.nl1/nl/zh/TW" /> </target>

<!--================ Clean Targets ================--> <target name="dev_cleanWebResources" depends="dev_setProperties" description="Remove copied web resources and undo changes to modified web resources within RAD"> <echo message="Cleaning activated resources from ${resource.root}" />

<!-- Run 2 XSL transformations, the first to generate the second, and the second, which cleans the resources specified by ../Extension/resources/webresources.cfg of all changes made by this extension --> <xslt in="${manifest}" out="clean.xsl" style="../Extension/resources/genclean.xsl" /> <xslt basedir="${resource.root}" destdir="WebContent" includesfile="../Extension/resources/webresources.cfg" style="clean.xsl"> <mapper type="identity" /> </xslt>

<!-- Copy the cleaned files into the resource root, overwriting the old files --> <copy todir="${resource.root}" overwrite="yes"> <fileset dir="WebContent" />

Page 87: Ant

</copy>

<!-- Cleanup temp files used in the above transformations --> <delete file="clean.xsl" /> <delete dir="WebContent" />

<!-- Cleanup files previously copied to the resource root by this extension --> <delete dir="${resource.root}/${shortname}" /> <delete dir="${resource.root}/WEB-INF/${shortname}" /> <delete file="${resource.root}/WEB-INF/lib/${shortname}.jar" /> </target>

<target name="increaseJVMSize" description="Increase the JVM default memory size to -Xmx2000m and remove the JVM size setting in runAiwServer.sh"> <echo>Increasing JVM size for DocPool Installation</echo> <exec executable="/bin/sh"> <arg value="-c"/> <arg value=" set -e; if cd $AIWHOME &amp;&amp; ! grep -q '# *90253' .profile; then (echo '# 90253: Update JVM Size to 2G' &amp;&amp; echo 'export IBM_JAVA_OPTIONS=-Xmx2000m') &gt;&gt;.profile; fi; if cd /opt/IBM/aiw/V1.0/bin &amp;&amp; grep -q -- -Xmx512m runAiwServer.sh; then cp -p runAiwServer.sh runAiwServer.sh.work; sed -e 's/-Xmx512m/-Xmx2000m/' runAiwServer.sh &gt;runAiwServer.sh.work; mv -f runAiwServer.sh.work runAiwServer.sh; fi"/> </exec> </target></project>______________________<?xml version="1.0" encoding="UTF-8"?><!-- Activation for SLA package Licensed materials - Property of InfoPrint Solutions Company Copyright InfoPrint Solutions Company 2006, 2009--><!-- In production environments, this script depends on the following environment variables and parameters: --><!-- Must export ANT_OPTS="-Duser.install.root=$AIW/ws/profiles/aiw" --><!-- ${env.AIWHOME} set to Peak process user's home directory --><!-- ${env.AIW} set to root of Peak installation -->

<!-- Development Environment: To run this script in a development environment, --><!-- use the dev project target --><!-- This will set the dev property to enable the development targets and disable the production ones. --><!-- ant -factivate.xml dev -->

<!-- There are three targets: primary, secondary, and aixsecondary.The System Activator will run the appropriate target based on which kind of node we are installing on.

The tasks for production environments:

Page 88: Ant

Run database script to create tables and initialize rowsCopy server resources to the classpath areaDeploy the web resources to the web serverCopy the help resources to the help areaRun activation utility Update the system classpath

The tasks for development environments:Run database script to create tables and initialize rowsCopy the web resources to ../UI_Web/WebContentRun activation utility

-->

<project name="SLAExtensionActivation" default="primary" basedir=".">

<taskdef name="chown" classname="org.apache.tools.ant.taskdefs.optional.unix.Chown"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar" /> </classpath> </taskdef>

<taskdef name="chgrp" classname="org.apache.tools.ant.taskdefs.optional.unix.Chgrp"> <classpath> <pathelement location="/usr/share/ant/lib/ant-nodeps.jar" /> </classpath> </taskdef>

<description>Ant script for activation of SLA</description>

<!--================ Define Project Targets ================--> <target name="primary" depends="stopServers,setProperties,activationTaskDef,runDBScript,copyServerResources,copyWebResources,copyHelpResources,activateServerAndWeb,runDBImportScript,activateHelp" description="Activate on a Primary installation">

<echo>Activating SLA on Primary</echo></target>

<target name="secondary" depends="copyServerResources" description="Activate on a Secondary installation">

<echo>Activating on Secondary</echo></target>

<target name="aixsecondary" depends="copyServerResources" description="Activate on an AIX secondary">

<echo>No action taken</echo></target>

<!-- This is the original depends line from dev target. Update the depends statement in the dev target as things start working:

depends="dev_setProperties,dev_activationTaskDef,dev_RunDBScript,copyWebResources,activateServerAndWeb"-->

Page 89: Ant

<target name="dev" depends="dev_setProperties,dev_activationTaskDef,copyWebResources,activateServerAndWeb" description="Activate within the RAD development environment">

<echo>Activating SLA within RAD environment</echo></target>

<!--================ Set Properties ================--><!-- Set global properties --><property environment="env" /><property name="shortname" value="sla"/><property name="manifest" value="extension.xml" /><property name="AIW" value="${env.AIW}" /><property name="aiwUsr" value="aiw1" />

<!-- Stop servers --><target name="stopServers"

description="Prepare the IPPD Servers for installation by stopping all but the DB manager"><echo message="Stopping Servers..."/><echo message="${AIW}"/><exec executable="server.pl" dir="${AIW}/bin" >

<arg line="-u${aiwUsr} stop"/></exec><echo message="Starting db..."/><exec executable="su" dir="${AIW}/extensions/sla/db" failonerror="false">

<arg line ="- ${aiwUsr} -c 'db2start ' " /></exec>

<echo message="db2started"/></target>

<!-- Set local properties --> <target name="setProperties" description="Set properties required for activating on a server"> <echo>Setting properties</echo> <property name="resource.root" value="${AIW}/ws/profiles/aiw/installedApps/DefaultNode/aiw.ear.ear/UI_Web.war" /> </target>

<target name="dev_setProperties" description="Set properties required for activating within RAD"> <echo>Setting properties</echo> <property name="resource.root" value="../UI_Web/WebContent" /> </target>

<!--================ Define Ant Tasks, used by the targets ================--><!-- Extension Activation Utility task --><target name="activationTaskDef" description="Define the Activation Ant Task for activating on a server"> <echo>Establishing Activation Ant task</echo>

<taskdef name="activateAIWExtension" classname="com.ibm.aiw.extension.activation.anttask.ActivateAIWExtension" classpath="${env.CLASSPATH}"/>

</target>

<target name="dev_activationTaskDef" description="Define the Activation Ant task for activating within RAD">

Page 90: Ant

<echo>Establishing Activation Ant task</echo><property name="activationClassPath"

value="./bin:../Secondary/afpUtil.jar:../Interfaces:../Secondary:../Server:../UI_SLA:../SLA_Server:${env.CLASSPATH}:${env.DB2_DRIVER_PATH}" />

<taskdef name="activateAIWExtension" classname="com.ibm.aiw.extension.activation.anttask.ActivateAIWExtension"

classpath="${activationClassPath}"/></target>

<!--================ Database Targets ================--><target name="runDBScript"

description="Create database tables with SQL script"><echo>Running Database Script</echo>

<exec executable="su" dir="${AIW}/extensions/sla/db" failonerror="true"> <arg line ="- ${aiwUsr} -c '/opt/IBM/aiw/V1.0/extensions/sla/db/dbUtilForSLA.pl y /opt/IBM/aiw/V1.0/extensions/sla/db/ ' " />

</exec>

</target>

<target name="dev_RunDBScript" description="Create database tables with SQL script"> <echo>Running Database Script on linux</echo>

<exec executable="db2cmd" failonerror="false" ><arg value ="/c"/><arg value="perl.exe"/><arg value="../SLA_Database/com/ibm/aiw/sla/database/src/dbUtilForSLA.pl"/><arg value="y"/><arg value="../SLA_Database/com/ibm/aiw/sla/database/src/"/>

</exec></target>

<target name="dev_RunDBScriptWin" description="Create database tables with SQL script"> <echo>Running Database Script on Windows</echo>

<exec executable="db2cmd" failonerror="true" ><arg value ="/c"/><arg value="perl.exe"/><arg value="..\SLA_Database\com\ibm\aiw\sla\database\src\dbUtilForSLA.pl"/><arg value="y"/><arg value="..\SLA_Database\com\ibm\aiw\sla\database\src\"/>

</exec></target>

<!--================ NLS Targets ================--><target name="runDBImportScript"

description="Import descriptions with SQL script"><echo>Running Database Script</echo>

<exec executable="su" dir="${AIW}/extensions/sla/db" failonerror="false"> <arg line ="- ${aiwUsr} -c 'cd ${AIW}/extensions/sla/db; /opt/IBM/aiw/V1.0/extensions/sla/db/importDescriptions.pl ' " />

</exec></target>

Page 91: Ant

<target name="runDBExportScript" description="Export descriptions with SQL script">

<echo>Running Database Script</echo>

<exec executable="su" dir="${AIW}/extensions/sla/db" failonerror="false"> <arg line ="- ${aiwUsr} -c 'cd ${AIW}/extensions/sla/db; /opt/IBM/aiw/V1.0/extensions/sla/db/exportDescriptions.pl ' " />

</exec></target>

<!--================ Activation Targets ================--><target name="activateServerAndWeb"

description="Activate database, server, and web components by calling the activateAIWExtension Task"><!-- Run the AIW Extension Activation Utility --><echo>Activating Extension</echo><activateAIWExtension manifest="${manifest}"

resourceRoot="${resource.root}"

requestedActivators="com.ibm.aiw.extension.activation.activators.model.ModelActivator,com.ibm.aiw.extension.activation.activators.view.ViewActivator,com.ibm.aiw.extension.activation.activators.controller.ControllerActivator"/>

<echo>SUCCESSFUL</echo></target>

<target name="activateHelp" description="Activate help components (plugin.xml, topic files, etc) by calling the activateAIWExtension

Task"><echo>Activating Help</echo><activateAIWExtension manifest="${manifest}"

resourceRoot="${AIW}/help/plugins/com.ibm.printers.aiw.nl1/nl"

requestedActivators="com.ibm.aiw.extension.activation.activators.help.HelpActivator"/><delete dir="${AIW}/help/configuration/org.eclipse.core.runtime"/><delete dir="${AIW}/help/configuration/org.eclipse.osgi"/><delete dir="${AIW}/help/configuration/org.eclipse.help.base"/><delete dir="${AIW}/help/configuration/org.eclipse.update"/>

</target>

<!--================ Copy Targets ================--><target name="copyServerResources"

description="Copy server-related resources to the appropriate place"> <echo>Copying new Server files</echo> <echo>Copying ui_jar</echo>

<copy todir="/aiw/${aiwUsr}/lib" file="${AIW}/extensions/sla/UI_Web.war/WEB-INF/lib/ui_sla.jar" overwrite="yes" />

<chown file="/aiw/${aiwUsr}/lib/ui_sla.jar" owner="${aiwUsr}"/><chgrp file="/aiw/${aiwUsr}/lib/ui_sla.jar" group="aiwgrp1"/>

<echo>Copying sla_server.jar</echo><copy todir="/aiw/${aiwUsr}/lib"

file="${AIW}/extensions/sla/UI_Web.war/WEB-INF/lib/sla_server.jar" overwrite="yes" /><chown file="/aiw/${aiwUsr}/lib/sla_server.jar" owner="${aiwUsr}"/>

Page 92: Ant

<chgrp file="/aiw/${aiwUsr}/lib/sla_server.jar" group="aiwgrp1"/>

<echo>Copying new control file</echo><copy todir="/aiw/${aiwUsr}/control_files/audit"

file="${AIW}/extensions/sla/control_files/policy_properties.cfg" overwrite="yes" /><chown file="/aiw/${aiwUsr}/control_files/audit/policy_properties.cfg" owner="${aiwUsr}"/><chgrp file="/aiw/${aiwUsr}/control_files/audit/policy_properties.cfg" group="aiwgrp1"/>

</target>

<target name="dev_copyWebResources"description="stand alone target to call the copyWebResources target in a dev environement"

depends="dev_setProperties, copyWebResources" ></target>

<target name="copyWebResources" description="Copy web resources (jars, jsp, graphics, etc) into WebSphere's installation

directory"><copy todir="${resource.root}" overwrite="yes">

<fileset dir="UI_Web.war"/></copy>

<mkdir dir="${resource.root}/sla/tagImages"/><mkdir dir="${resource.root}/sla/tagScripts"/>

<!-- copy tag resources to the sla context. This is a work around because the tag scripts use relative paths that don't work correctly with struts modules paths. -->

<copy todir="${resource.root}/sla/tagImages/" > <fileset dir="${resource.root}/tagImages" /> </copy>

<copy todir="${resource.root}/sla/tagScripts/" ><fileset dir="${resource.root}/tagScripts" />

</copy></target>

<target name="copyHelpResources" description="Copy help resources (xml, html) into the help installation directories">

<echo>Making new Help directories</echo> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.sla"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/de"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/en"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/es"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/fr"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/it"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/ja"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/ru"/> <mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/zh/TW"/>

<echo>Copying new Help resources</echo><mkdir dir="${AIW}/help/plugins/com.infoprint.aiw.sla"/><copy todir="${AIW}/help/plugins/com.infoprint.aiw.sla" >

<fileset dir="help/en/" /></copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/de">

<fileset dir="help/de/" />

Page 93: Ant

</copy><copy todir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/en">

<fileset dir="help/en/" /></copy>

<copy todir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/es"><fileset dir="help/es/" /></copy>

<copy todir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/fr"><fileset dir="help/fr/" /></copy>

<copy todir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/it"><fileset dir="help/it/" /></copy>

<copy todir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/ja"><fileset dir="help/ja/" /></copy>

<copy todir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/ru"><fileset dir="help/ru/" /></copy>

<copy todir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/nl/zh/TW"><fileset dir="help/zh/TW" /></copy>

<copy todir="${AIW}/help/plugins/com.infoprint.aiw.sla.nl1/" file="help/fragment.xml" />

</target>

<!--================ Clean Targets ================--><target name="dev_cleanWebResources" depends="dev_setProperties"

description="Remove copied web resources and undo changes to modified web resources within RAD"><echo message="Cleaning activated resources from ${resource.root}" />

<!-- Run 2 XSL transformations, the first to generate the second, and the second, which cleans the resources specified by

../Extension/resources/webresources.cfg of all changes made by this extension --><xslt in="${manifest}" out="clean.xsl" style="../Extension/resources/genclean.xsl"/><xslt basedir="${resource.root}" destdir="WebContent"

includesfile="../Extension/resources/webresources.cfg" style="clean.xsl"> <mapper type="identity"/></xslt>

<!-- Copy the cleaned files into the resource root, overwriting the old files --><copy todir="${resource.root}" overwrite="yes">

<fileset dir="WebContent"/></copy>

<!-- Cleanup temp files used in the above transformations --><delete file="clean.xsl"/><delete dir="WebContent"/>

<!-- Cleanup files previously copied to the resource root by this extension --><delete dir="${resource.root}/${shortname}"/><delete dir="${resource.root}/WEB-INF/${shortname}"/><delete file="${resource.root}/WEB-INF/lib/${shortname}.jar"/>

</target>

Page 94: Ant

</project>