Ant Script to Write Into a Java File

The following sections list out the most commonly used tasks in Ant build scripts. Required attributes are marked in bold.

Core Java Related Tasks

This section gives a complete reference of all tasks and their attributes that are most commonly used by Java Developers.

Compiling Java Code

Compilation is achieved with the <javac> task.

Attribute Description
srcdir Location of java files to compile
bootclasspath/ boothclasspathref Location of bootstrap class files or reference to a predefined path
classpath/ classpathref Classpath to use for compilation or reference to a predefined path
compiler Compiler implementation to use. Default is current VM
debug Whether source should be compiled with debug information (-g parameter). Defaults to off
debuglevel Can be lines, var or source. Used in the -g parameter for the compiler
depend Enables dependency tracking on jikes and classic compilers
deprecation Whether source should compile with deprecation information
destdir Destination for compiled .class files
encoding Encoding of source files
errorProperty Property to set to true if compilation fails
excludes Comma separated list of files that must be excluded from compilation. Wildcard patterns can be used
excludesFile File that contains the exclusion list
executable Path to javac executable to use when fork set to yes
extdirs Location of installed extensions
fork Whether to execute javac using the JDK compiler externally. Default no
failonerror Whether compilation error fails the build. Default true
includes Comma separated list of files that must be included in compilation. Wildcard patterns can be used
includeAntRuntime Whether to include ANT runtime libraries in the classpath. Default yes
includeDestClasses Whether classes compiled to the dest directory are included in the classpath. Default true. When false, causes recompilation of dependent classes
includesFile File containing the exclusion list
includeJavaRuntime Whether to include default libraries from VM.Default no
listfiles Whether source files to be compiled will be listed. Default no
memoryInitialSize / memoryMaximumSize Initial and maximum memory sizes for VM if run externally
nowarn Whether -nowarn should be used with the compiler. Defaults to off
optimize Whether to compile with optimization, ignored since JDK1.3
source Value of the -source command line switch
sourcepath/ sourcepathref Defaults to value of srcdir or reference to a predefined path
target Generate class files for a particular VM version
tempdir Temporary file location if fork set to yes
updatedProperty Property to set for successful compilation
verbose Use verbose output on the compiler

Table 6: javac tasks properties

Additional command line arguments can be passed through to the compiler using the <compilerarg> nested element.

Hot Tip

Compiler Choice To use different compilers set the build.compiler property to classic (1.1, 1.2) modern (1.3-1.6) or choose a separate compiler such as jikes, jvc, kjc, gcj or sj.

Class file dependencies can be managed using the <depend> task.

Attribute Description
srcdir Location of Java files to compile. Will be examined to determine which files are out of date
cache Directory where dependency information is stored and retrieved. No cache if not used
classpath Classpath from which dependencies also need to be checked
closure If true, all classes depending on an out-of-date class are deleted
destdir Location of class file to be analyzed
dump If true dependency info is written to the debug level log
warnOnRmiStubs Disables warnings about files that look like rmic generated stubs but no .java source

Table 7: Depend task properties

Distributing Compiled Code

Jar files can be created using the <jar> task.

Attribute Description
destfile JAR file to create
basedir The directory to build from
compress Compress data in jar. Defaults true
createUnicodeExtraFields Whether to create unicode extra fields to store file names a second time inside the entry's metadata
defaultexcludes Whether default excludes should be used. Default true
duplicate Behavior when a duplicate file is found - add (default), preserve, fail
keepcompression For entries coming from other archives, keep its compression, overriding compress
encoding Character encoding for filenames. Default UTF8
excludes List of patterns of files to exclude
excludesfile The name of a file that defines an exclude pattern
fallbacktoUTF8 If the specified encoding cannot be used, whether to fallback to UTF8
filesonly Store only file entries. Default false
filesetmanifest Behavior for when a manifest is found in a zipfilesset. Can merge, mergewithoutmain or skip (default)
flattenAttributes Merge attributes occurring more than once in a section into one single attribute
includes List of patterns of files to include
includesfile The name of a file that defines an include pattern
index Whether to create an index list to speed up classloading. Default false
indexMetaInf Whether to include META-INF in the index. Default false
level Compression level for files from 0 (none) to 9 (maximum)
manifest Location of manifest for jar
manifestencoding Encoding to use for manifest. Default is platform encoding
mergeClassPathAttributes Merge classpath attributes of different manifests when merging
preserve0permissions If a file has permissions value of 0, it will preserve this instead of applying default values
roundup Whether to round up file modification time to the next even number of seconds
strict How to handle breaks of packaging version specification Fail, warn or ignore (default)
update Whether to overwrite files that already exist. Default false
useLanguageEncodingFlag Whether to set language encoding if encoding set to UTF8 only
whenmanifestonly Behavior when no files match - fail, skip or create (default)

Table 8: Jar task properties

Hot Tip

War and Ear Archive Tasks Both <war> and <ear> tasks have similar attributes to the <jar> task, adding in attributes for web.xml or application.xml respectively.

Additionally, you can sign jar archives using the <signjar> task.

Attribute Description
alias The alias to sign under
jar The jar file to sign
storepass The password for keystore integrity
executable Specific jarsigner executable to use in place of default in JDK
force Force signing if already signed or not out of date
internals Whether to include the .SF file inside signature block. Default false
keypass The password for the private key
keystore Keystore location
lazy Whether a signature file being present means the jar is signed
maxmemory Maximum memory the VM will use when signing
preservelastmodified Signed files keep the same modification time as original jar files
sectionsonly Whether to compute the hash of entire manifest
sigfile The name of the .SF or .DSA file
signedjar The name of the signed jar file
storetype The keystore type
tsacert Alias in keystore for timestamp authority
tsaurl URL for timestamp authority
verbose Whether to use verbose output. Default false

Table 9: Signjar task properties

Manifests can be included using the <manifest> task.

Attribute Description
file Manifest file to create or update
encoding Encoding to read existing manifest
flattenAttributes Merge attributes occurring more than once in a section into one single attribute
mergeClassPathAttributes Merge classpath attributes of different manifests when merging
mode Either update or replace (default)

Table 10: Manifest task properties

Generating Documentation

JavaDoc generation is done through the <javadoc> task.

Attribute Description
sourcepath
sourcepathref
sourcefiles
Location of the source files for the task. At least one of these attributes required for this specification
destdir Destination directory required unless a doclet is specified
access Access mode (public, private, protected, package)
additionalparam Additional parameters to pass through
author Include @author parts
bootclasspath /
bootclasspathref
Location of class files loaded by bootstrap class loader
bottom Bottom text for each page
breakiterator Use new breakiterator algorithm
charset Charset for cross platform viewing
classpath/classpathref Location of classpath
defaultexcludes Whether default excludes should be used
docencoding Encoding of output file
docfilessubdirs Deep copy of doc-file subdirectories
doclet/docletpathref Classfile that starts to doclet used
doctitle Title for the package index page
encoding Source file encoding
excludepackagenames Packages to exclude from javadoc
executable Specify a javadoc executable instead of VM default
extdirs Location of installed extensions
failonerror Stops build process if command fails
footer Footer text for each page
group Group specified packages together in overview page
header Header text for each page
helpfile Specifies help file to include
includenosourcepackages When true includes packages with no source
link Create links to javadoc output at given url
linksource Generate links to source files
locale Locale to be used
maxmemory Maximum amount of memory to allocate in VM
nodeprecated Do not include @deprecated information
nodeprecatedlist Do not generate deprecated list
notree Do not generate class hierarchy
noindex Do not generate index
nohelp Do not generate help link
nonavbar Do not generate naviation bar
noqualifier Enables -noqualifier argument for a list of packages (or all)
overview Read overview documentation from HTML file
packagenames List of package files to use
packageList File containing packages to use
public Show only public classes and members
protected Show only protected/public classes and members
package Show only package/protected/public classes and members
private Show all classes and members
serialwarn Warn about @serial tag
source Source level used for compilation
splitindex Split index into one file per letter
stylesheetfile Specifies CSS stylesheet
use Create class and package usage pages
verbose Output all messages of javadoc process
version Include @version parts
windowtitle Browser window title for documentation

Table 11: JavaDoc task properties

Executing Java Classes

Java classes can be executed from Ant using the <java> task.

Attribute Description
classname jar The jar file or classname to execute. If using jar, fork must be set to true
append Whether output/error files should be appended or overwritten
args Arguments for class. Better to use nested <arg> elements
classpath / classpathref Classpath to use for execution
clonevm Clones system properties and bootclasspath of forked VM to be the same as the Ant VM
dir Directory to invoke VM in
error File to write error (System.err) output to
errorproperty Property to store error output from command
failonerror Stops Ant build process if failure occurs
fork Executes the class in another VM
input File where standard input is taken from
inputstring String where standard input is taken from
jvm Command used to invoke JVM. Default is java
javmargs Arguments for forked JVM. Better to use nested <jvmarg>
logError Shows error output in Ant log
maxmemory Maximum memory to allocate to the forked VM
newenvironment When fork=true, do not propogate current environment variables
output File to write output to
outputproperty Property to store output of the command
resultproperty Property where return code of command is stored
spawn Need fork set to true. Will spawn a process independent of calling Ant process
timeout Timeout for the command to execute within before being stopped

Table 12: Java task properties

Running Unit Tests

JUnit tests are executed from Ant through the <junit> task

Attribute Description
clonevm Clones system properties and bootclasspath of forked VM to be the same as the Ant VM
dir Directory from which to invoke the VM
errorproperty Property to set when errors occur
failureproperty Property to set when failure occurs
filtertrace Filter out JUnit or Ant stack frames from stack traces in errors or failures
fork Run JUnit in a separate VM
forkmode How many VMs to create when forking tests. (preTest, perBatch or once)
haltonerror Stop build process if an error happens
haltonfailure Stops build process if a test fails
includeAntruntime Stops build process if a test fails
jvm Command used to invoke VM, default java
logfailedtests Log a FAILED message for each failed test to Ant's logging system
maxmemory Maximum memory to allocate to forked VM
newenvironment When fork=true, do not propogate current environment variables
outputformatters Send output generated by tests to test formatters
printsummary Print statistics for each test case. (on, off, withOutAndErr)
reloading Whether a new classloader should be instAntiated for each test
showoutput Send output to Ant log
tempdir Location for temporary files
timeout Cancel tests if not complete in specified time

Table 13: JUnit task properties

Tests are defined in nested elements within the <junit> task. Batch tests are defined using the <<batchtest> tag:

Attribute Description
name Name of test class
errorproperty Property to set when errors occur
failureproperty Property to set when failure occurs
filtertrace Filter out JUnit or Ant stack frames from stack traces in errorsor failures
fork Run tests in a separate VM, overriding the value set in the <junit> task
haltonerror Stop build process if an error happens
haltonfailure Stops build process if a test fails
if Property condition to run test against, if set
todir Directory to write reports to
unless Property condition to run test against, if not set

Table 14: JUnit batch test definition

Hot Tip

Single Tests If you just need to run a single test, the <test> tag can be used to specify the test. This contains similar attributes to the <batchtest> tag.

Test results can be written to different formats, using the outputformatters attribute in the <junit> task. The following table shows the options for formatter definition:

Attribute Description
type A predefined formatter type of either xml, plain, brief or failure
classname If no type specified, use a customer formatter implementing org.apache.tools.Ant.taskdefs.optional.junit .JUnitResultFormatter
if Use formatter if property is set
unless Use formatter if property is not set
usefile If output should be sent to a file. Default true

Table 15: JUnit formatter definition

Once tests are completed, reports can be generated for the tests using the <junitreport> task.

Attribute Description
todir The directory that will contain the results
tofile The name of the XML file that will aggregate all previously generated results

Table 16: JUnitReport task properties

The <junitreport> task contains a fileset that collects all the reports from previous Junit tests.

To output to a report file, use the internal <report> tag.

Attribute Description
format Format of report (frames or noframes)
styledir Directory containing stylesheets. Files must be junit-frames.xsl or junit-noframes.xsl
todir The directory that files are written to. By default this is the current directory

Table 17: Report tag for <junitreport>

Infrastructure Tasks

There are a number of other core tasks related to file operations. The following is an overview of these tasks:

Task Description
attrib /chmod Changes permission of a file (attrib for Windows, chmod for Unix)
checksum Generates a checksum for files
concat Concatenates multiple files into one single file, or to the console
copy Copies a file, or collection of files, to another location
delete Deletes a file, directory or collection of files
exec Executes a system command
ftp Provides basic FTP functionality
get Gets a file from a URL
import /include Imports or includes another build file into the current Ant script
mail Sends mail over SMTP
mkdir Creates a new directory
move Moves a file, or collection of files, to another location
record Listens to the build process and outputs to a file
replace Replaces occurances of a string in file or collection of files
replaceregexp Replaces occurances of a string in file or collection of files using regular expressions
sql Executes SQL statements to a database using JDBC
sync Synchronizes a target directory with a list of files
zip / unzip tar / untar Creates a zip file / unzips an existing zip. Also provides functionality for tar files

Table 18: Overview of basic infrastructure tasks

SCM Related Tasks

ANT provides a number of tasks for connecting with different source control management systems. The core support deals with CVS.

Task Description
cvs Handles commands to be run against CVS, defaulting with checkout
cvschangelog Generates a report of change logs recorded in CVS
cvspass Adds entries to a .cvspass file
cvstagdiff Generates a report of the changes between two tags/dates from CVS
cvsversion Retrieves CVS client and server version
patch Applies a diff file to originals

Table 19: CVS task properties

There are also tasks available for interfacing with ClearCase, Visual Source Safe, Pvcs, Perforce and Continuus. Additional tasks can be found online for DCVS systems such as Git and Mercurial.

Property Tasks

Ant provides some tasks that deal with managing properties throughout your build process.

Task Description
available Sets property if file, directory or class in classpath is available at runtime
basename Sets property to last element of specified path
buildnumber Reads build number from a specified file
condition Set property if a condition is true
dirname Set property to the directory path of a specified file
echoproperties Display all properties to file or console
loadfile Loads a file into a property
loadproperties Load a property file contents as Ant properties
makeurl Converts filenames into URLs
pathconvert Converts a file list or path structure to a separated string for the target platform
property Set a property
propertyfile Creation and modification of property files
uptodate Set property if specified target file is newer than source files
whichresource Find class or resource
xmlproperty Loads properties from property file written in XML

Table 20: Ant Property Tasks

Hot Tip

Writing Your Own Tasks If Ant doesn't provide you with the functionality that you need, you can write your own Ant tasks in Java by extending org.apache.tools.ant.Task.

Ant Script to Write Into a Java File

Source: https://dzone.com/refcardz/getting-started-apache-ant

0 Response to "Ant Script to Write Into a Java File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel