Previous Section
Table of Contents
Next Section


Chapter 2: Ant Data Types

Ant data types provide services, such as defining system assertions, creating directories, and renaming files. Ant provides two categories of data types, Core and Optional.

This chapter explains various core and optional data types of Ant.

Core Data Types

Core data types are the built-in data types that Ant provides. You can use core data types to perform most of the tasks required to build and deploy applications.

Table 2-1lists the various core data types:

Table 2-1: The Core Data Types

Core Data Type

Description

Assertion

Enables or disables assertions in packages and classes.

Description

Provides information about the project.

Dirset

Defines a group of directories.

FileList

Specifies a list of files relative to the specified directory.

FileSet

Defines a group of files.

FileMapper

Maps source files to destination files.

FilterReader and FilterChains

Defines the user-defined and built-in filter elements in the build file.

FilterSet

Replaces specific patterns with user-specified strings.

I/O Redirectors

Redirects input and output using the FileMapper data type to specify the source file and the destination file.

PatternSet

Filters files or directories based on user-specific patterns.

Path-Like Structures

Specifies PATH and CLASSPATH type references.

Permission

Grants or revokes permission on a specific set of code.

PropertySet

Groups the set of properties that a task requires.

Selectors

Selects files based on specified criteria, such as date and time of update, and case sensitivity.

XMLCatalog

Makes Web references to resources that point to a locally cached point of resources.

ZipFileSet

Useful for Zip/JAR tasks.

The Assertion Data Type

The assertion data type enables or disables the Java 1.4 assertion feature in a complete Java program or in a part of a Java program. An assertion is a statement that allows you to test assumptions specific to your program. The assertions are disabled, by default. Disabling assertions is useful only when they are enabled in the parent directory.

The assertion data type contains the enableSystemAssertion attribute. This attribute enables assertions in all system classes and sets assertion status to true. The following code shows how to enable assertions in a class named temp:

<assertions>  
<enable class="temp" />
</assertions>

The following code sets system assertions for .apache packages:

<assertions enableSystemAssertions="true" >
<enable package="org.apache" />
<disable package="org.apache.ant" />
</assertions>

The above code enables assertions for the org.apache package and disables assertions for the org.apache.ant package.

The Description Data Type

The <description> type.provides a project-wide description element to provide summarized information about the project. The <description > element occurs before the target descriptions and should be placed directly under the opening <project> tag. The Description data type does not contain any attributes. Only one description exists per project. If you use a second description element, it will overwrite the first description.

The following code shows how to write a description of the project in a Description data type:

<project default="deploy" basedir="."> 
<description>The description of the project goes here</description> 
</project> 

The above code describes the project.

The DirSet Data Type

The DirSet data type allows you to include or exclude specific directories. You can find the directories in a directory tree by starting in a base directory and matching the pattern from different PatternSet data types. The PatternSet data type filters files or directories based on user-specific patterns. You provide a pattern to match source files, known as an include pattern, and a pattern to exclude files, known as an exclude pattern.

The DirSet data type contains an implicit PatternSet data type. This means that PatternSet elements appear as attributes of the <DirSet> tag and support the nested <include>, <includesfile>, <exclude>, and <excludesfile> elements of <patternset> directly, as well as <patternset> attributes. You use the attributes of <patternset> data type to set the pattern. The mandatory attribute of the DirSet data type is dir, which defines the root of the directory tree. The optional attributes of the DirSet data type are:

  • includes: Defines the list of include directories.

  • includesfile: Defines the name of a file where each line of the file is taken as a include pattern while selecting files.

  • excludes: Defines the list of directories that must be excluded while making a selection.

  • excludesfile: Defines the name of a file where each line of the file is taken as an exclude pattern while selecting files.

  • casesensitive: Defines whether or not case sensitivity needs to be applied during selection.

  • followsymlinks: Defines symbolic links. A symbolic link is a text string that refers to a filename. When the links are called, they refer to the original file and allow the maintenance of a single copy of the file.

The following code shows how to use <dirset> to group directories:

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

The above code groups all directories found under the apps subdirectory of ${build.dir}.

Listing 2-1 shows how to use PatternSet within DirSet:

Listing 2-1: Using PatternSet within DirSet
Start example
<dirset dir="${build.dir}"> 
<patternset id="newone"> 
<include name="**/*.exe"/> 
<exclude name="**/*test*"/> 
</patternset> 
</dirset> 
End example

The above listing shows how the nested PatternSet defines the pattern of including the files whose names end with .exe extension and excluding the files that contain test in their name. After selecting the particular files, DirSet groups all the directories.

The FileList Data Type

The FileList data type is a list of files. The FileList data type does not support wildcard characters and provides a list of files that build the target files. FileList allows you to list a file that may or may not exist. You use this feature when you know the name of the file you are going to use. The mandatory attributes of FileList are:

  • dir: The base directory of the file list. This attribute is mandatory if you do not specify the files attribute.

  • files: A list of comma-separated filenames. This attribute is mandatory if you do not specify the dir attribute.

The following code shows how to use <fileset> to list files:

<filelist> 
id="docfiles" 
dir="${doc.src}"
files="newone.xml,rares.xml"/> 

The above code lists files named ${doc.src}/newone.xml and ${doc.src}/rares.xml.

The FileSet Data Type

The FileSet data type groups files based on a set of user-defined patterns and does not support a list of files. The attributes of the DirSet data type and the FileSet data type are the same. The FileSet data type contains only one more attribute, defaultexcludes, which takes yes or no as its value. The defaultexcludes attribute indicates whether or not the default excludes should be used. This exclude list may contain files, such as backup files, inside Concurrent Versions System (CVS) directories and temporary files. The default value of the defaultexcludes attribute is no. The FileSet data type can appear inside tasks that support FileSet data type features or tasks that are at the same level as target.

FileSet consists of an implicit PatternSet and supports the nested <include>, <includesfile>, <exclude>, and <excludesfile> elements of the PatternSet data type directly, as well as PatternSets attributes. The mandatory attribute of FileSet is dir, which defines the root of the directory tree. The optional attributes of FileSet are:

  • defaultexcludes: Defines a boolean type, which indicates whether or not to include default excludes.

  • includes: Defines the list of include files. When omitted, each file of the directory is included in the selection of files.

  • includesfile: Defines the name of the file where each line of this file is taken as an include pattern in the selection of files.

  • excludes: Defines a list of comma-separated files that must be excluded. When omitted, no file is excluded except defaultexcludes.

  • excludesfile: Defines the name of the file where each line of this file is taken as an exclude pattern in the selection of files.

  • casesensitive: Defines whether or not case sensitivity needs to be applied to the file system. The default value is no.

  • followsymlinks: Indicates the list of symbolic links. This is platform dependent and not available to all systems. This is used mostly for UNIX and Solaris systems.

The following code shows how to use <fileset> to group files:

<fileset dir="${server.src}" casesensitive="yes" >
<include name="**/*.jar"/>
<exclude name="**/*temp*"/>
</fileset>

The above code groups all jar files in the $(server.src) directory except the files that do not contain text named temp in their names.

Listing 2-2 shows code that uses FileSet with a nested PatternSet:

Listing 2-2: FileSet with a Nested PatternSet
Start example
<fileset dir="${build.dir}"> 
<patternset id="sources"> 
<include name="**/*.jar"/> 
<exclude name="**/*Temp*"/> 
</patternset> 
</fileset> 
End example

The above listing shows how PatternSet selects all jar files in the $(server.src) directory, except the files that do not contain text named temp in their names.

The FileMapper Data Type

The FileMapper data type uses a user-defined pattern to select source files using the from attribute and a user-defined pattern to define target files using the to attribute. The mandatory attributes of the FileMapper data type are:

  • type: Defines built-in implementations. This attribute is mandatory if you do not specify the classname attribute.

  • classname: Defines an implementation by class name. This attribute is mandatory if you do not specify the type attribute.

The optional attributes of FileMapper are:

  • classpath: Defines the class path when looking for a class name.

  • classpathref: Defines the reference for the class.

  • from: Matches the source pattern.

  • to: Matches the target pattern.

Note 

Ant will not directly convert the / or \ character used to the correct directory separator of your platform. You can use ${file.seperator} to specify the file separator.

Ant contains nine types of mappers, which are:

  • The identity mapper

  • The flatten mapper

  • The merge mapper

  • The glob mapper

  • The regexp mapper

  • The package mapper

  • The unpackage mapper

  • The composite mapper

  • The chained mapper

The identity Mapper

In the identity mapper, the target filename is identical to the source filename. The identity mapper ignores the types, from, and to attributes. The following code shows how to use the identity mapper:

<mapper type="identity"/>
<identitymapper />

The above code maps all the files with the same name with no change in the names of the files.

Table 2-2 lists the output of the identity mapper:

Table 2-2: Output of the Identity Mapper

Source Filename

Target Filename

ABC.java

ABC.java

Infom/bar/X.java

Infom/bar/X.java

Classes/dir/dir2/XYZ.properties

Classes/dir/dir2/XYZ.properties

The flatten Mapper

In the flatten mapper, the target filename is the same as the source filename with all the leading directory information ignored by the mapper. This mapper ignores both the to and from attributes. The following code shows how to use the flatten mapper to map files:

<mapper type="flatten"/>
<flattenmapper />

The above code maps files with the same name but ignores the directory information.

Table 2-3 lists the output of the flatten mapper:

Table 2-3: Output of the Flatten Mapper

Source Filename

Target Filename

ABC.java

ABC.java

Infom/bar/X.java

X.java

Classes/dir/dir2/XYZ.properties

XYZ.properties

The merge Mapper

In the merge mapper, the target file will always be the same as that defined by the to attribute. The merge mapper ignores the from attribute. The following code shows how to use the merge mapper:

<mapper type="merge" to="newone.tar"/>
<mergemapper to="newone.tar"/>

The above code maps all the files with the newone.tar filename.

Table 2-4 lists the output of the merge mapper:

Table 2-4: Output of the Merge Mapper

Source Filename

Target Filename

ABC.java

Newone.tar

Infom/bar/X.java

Newone.tar

Classes/dir/dir2/XYZ.properties

Newone.tar

The glob Mapper

In the glob mapper, both the to and the from attributes define patterns for target files. For every source file that matches the source pattern, this mapper generates a target file that follows the target pattern. The glob mapper allows the use of a wildcard character, * and ignores filenames that do not match the source pattern. For each source file that matches the source pattern, the glob mapper constructs a target filename from the target pattern by substituting * in the target pattern with the text that matches * in the source pattern. The following code shows how to use the glob mapper to map files:

<mapper type="glob" from="*.java" to="*.java.bak"/>
<globmapper from="*.java" to="*.java.bak"/>

The above code maps all the files with .java in their names to .java.bak. The code ignores the files, without the .java extension.

Table 2-5 lists the output of the glob mapper:

Table 2-5: Output of the Glob Mapper

Source Filename

Target Filename

ABC.java

ABC.java.bak

infom/bar/X.java

infom/bar/X.java.bak

Classes/dir/dir2/A.properties

ignored

The regexp Mapper

In the regexp mapper, both the to and the from attributes define patterns that may contain a maximum of one wildcard character *. If the source filename matches the source pattern, the regexp mapper constructs the target filename from the source pattern using \0 to \9 as back-references for the full match (\0) or the matches of subexpressions in the parentheses. The back-reference symbol, \, defines the presence of a directory structure, such as foo/bar/B.java. The regexp mapper ignores files that do not match the source pattern. The syntax of the regexp mapper depends on the underlying libraries defined in the java.util.regex package of JDK 1.4, jakarta-regexp and jakarta-ORO. The following code shows the regexp mapper with back references:

<mapper type="regexp" from="^(.*)\.java$$" to="\1.java.bak"/>
<regexpmapper from="^(.*)\.java$$" to="\1.java.bak"/>

The above code maps files using the to attribute and back-references.

Table 2-6 lists the output of the regexp mapper:

Table 2-6: Output of the regexp Mapper

Source Filename

Target Filename

A.java

A.java.bak

foo/bar/B.java

foo/bar/B.java.bak

Classes/dir/dir2/A.properties

ignored

The package Mapper

The package mapper has the same syntax as the glob mapper. The package mapper replaces the directory separators found in the matched source pattern with dots in the target pattern placeholder. The package mapper is particularly useful in combination with the output of <uptodate> and <junit>. The following code shows how to use the package mapper to map files:

<mapper type="package" from="*Test.java" to="TEST-*Test.xml"/>
<packagemapper from="*Test.java" to="TEST-*Test.xml"/>

The above code replaces a directory separator (/) with a dot (.). The mapper ignores the files that do not contain the text Test as the last four letters of their filename.

Table 2-7 lists the output of the package mapper to list files:

Table 2-7: Output of the package Mapper

Source Filename

Target Filename

org/apache/tools/ant/util/PackageMapperTest.java

TEST-org.apache.tools.ant.util.PackageMapperTest.xml

org/apache/tools/ant/util/Helper.java

ignored

The unpackage Mapper

The unpackage mapper is the reverse of the package mapper. It replaces the dots in a package name with directory separators. Ant 1.6.0 version introduced the unpackage mapper. The following code shows how to use the unpackage mapper:

<mapper type="unpackage" from="TEST-*Test.xml" to="${test.src.dir}/*Test.java">
<unpackagemapper from="TEST-*Test.xml" to="${test.src.dir}/*Test.java">

The above code replaces a separator (/) with a dot (.) in the source filename. The output of the Unpackage Mapper contains the source filename, TEST-org.acme.AcmeTest.xml and the target filename, ${test.src.dir}/org/acme/AcmeTest.java.

The composite Mapper

The composite mapper contains multiple nested mappers. Mapping occurs by sequentially passing the source filename to each nested mapper. The composite mapper ignores both the to and the from attributes. Ant 1.6.2 version introduced the composite mapper. The following code shows how to use the composite mapper to nest various mappers:

<compositemapper>  
<identitymapper />
<packagemapper from="*.java" to="*"/>
</compositemapper>

The above code nests the package mapper inside the identity mapper.

Table 2-8 lists the output of the composite mapper:

Table 2-8: Output of the Composite Mapper

Source Filename

Target Filename

foo/bar/A.java

foo/bar/A.java

foo.bar.A

The chained Mapper

The chained mapper contains multiple nested mappers. This mapper passes the source filename to the first mapper. The result of the first mapper is passed to the second mapper. This process continues until the result reaches the last mapper that generates the target filenames. The chained mapper ignores both the to and the from attributes.

Listing 2-3 shows how to nest mappers using the chained mapper:

Listing 2-3: Nesting a Mapper Using a Chained Mapper
Start example
<chainedmapper>
<flattenmapper />
<globmapper from="*" to="new/path/*"/>
<mapper>
<globmapper from="*" to="*1"/>
<globmapper from="*" to="*2"/>
</mapper>
</chainedmapper>
End example

The above listing shows how a glob mapper nests another glob mapper. The two globs mappers are further nested in a flatten mapper.

Table 2-9 lists the output of the chained mapper:

Table 2-9: Output of the Chained Mapper

Source Filename

Target Filename

foo/bar/A.java

new/path/A.java1

new/path/A.java2

boo/far/B.java

new/path/B.java1

new/path/B.java2

The FilterReaders and FilterChains Data Types

You can define user-defined and built-in filter elements in the build file using the FilterReader data type. The build file is an XML file that describes the various tasks Ant should complete. FilterReader filters the stream of data coming from files or directories.

FilterReader is a subclass of java.io.Reader. You can create your own FilterReader by extending the java.io.FilterReader class. The mandatory attribute of FilterReader is classname, which defines the class name of FilterReader. The optional attributes of FilterReader are:

  • param: Specifies the run time settings of an object inserted into eXtensible HTML (XHTML) documents.

  • classpath: Defines the classpath for loading the selector class.

FilterChain is a chain or pipeline of FilterReaders. You can use FilterReaders only when they are contained in a FilterChain, which encapsulates any number of FilterReaders in a user-specific order. FilterChain triggers multiple FilterReaders simultaneously.

The built-in FilterReaders in Ant are:

  • ClassConstants

  • ExpandProperties

  • ReplaceToken

  • StripJavaComments

  • StripLineBreaks

  • LineContains

  • LineContainsRefexp

  • PrefixLines

  • TabsToSpaces

The ClassConstants FilterReader

ClassConstants look for all the fields in a .class file that are constants and outputs those fields as key-value pairs.

ClassConstants requires the Jakarta Byte Code Engineering Library (BCEL) package in the classpath at the time of the build.

Listing 2-4 shows how to copy files using ClassConstants filters:

Listing 2-4: Using ClassConstants
Start example
<copy todir="bar"> 
<filterchain> 
<classconstants/> 
</filterchain> 
<fileset dir="foo"> 
<include name="**/*.class"/> 
</fileset> 
<mapper type="glob" from="*.class" to="*.txt"/> 
</copy> 
End example

The above listing shows how to copy the entire binary file into text files.

The ExpandProperties FilterReader

The ExpandProperties filter expands any Ant properties that the file contains. The properties are of the form ${...}. ExpandProperties parses any property or expression found in the input and combines their values with the output.

Note 

Expressions that are longer than 2048 characters are not guaranteed for expansion due to the limitation on buffering.

Listing 2-5 shows how to expand properties using the ExpandProperties filter:

Listing 2-5: Expanding Ant Properties
Start example
<copy todir="bar"> 
<filterchain> 
<expandproperties/> 
</filterchain> 
<fileset dir="foo"> 
<include name="**/*.java"/> 
</fileset> 
</copy> 
End example

The above listing shows how to expand the Ant properties of .java files using the ExpandProperties filter.

HeadFilter and TailFilter

The HeadFilter filter retrieves the first n lines from a file and the TailFilter filter retrieves the last n lines from the file. The HeadFilter and TailFilter filters work in the same way as the head and tail programs in UNIX. The filters are useful for copying only a sample from a file instead of the entire file. The filters provide two optional parameters:

  • lines: Defines the number of lines to be read. The default value is 10. A negative value retrieves all the lines in the file.

  • Skip: Defines the number of lines to be skipped from the beginning of the file. The default value is 0.

Listing 2-6 shows how to use the HeadFilter filter to filter a specific portion of a file:

Listing 2-6: Using HeadFilter to Filter Files
Start example
<copy todir="bar"> 
<filterchain> 
<headfilter lines="5"/> 
</filterchain> 
<fileset dir="foo"> 
<include name="**/*.java"/> 
</fileset> 
</copy> 
End example

The above listing shows how to copy only the first 5 lines of .java files.

Listing 2-7 shows how to use TailFilter to filter specific portions of files:

Listing 2-7: Using TailFilter to Filter Files
Start example
<copy todir="bar"> 
<filterchain> 
<tailfilter lines="5"/> 
</filterchain> 
<fileset dir="foo"> 
<include name="**/*.java"/> 
</fileset> 
</copy> 
End example

The above listing shows how to copy only the last 5 lines of .java files.

The ReplaceToken Filter

The ReplaceToken filter replaces all strings that lie between the begintoken and endtoken attributes. The tokens are user-specific and the default value is @. The mandatory attribute of ReplaceToken is token, which defines a user-specific string pattern. The optional attributes of ReplaceToken are:

  • begintoken: Defines the first character of the token.

  • endtoken: Defines the last character of the token.

Listing 2-8 shows how to use the ReplaceToken filter to replace a user-specific pattern:

Listing 2-8: Replacing a Token filter to User-Specific Pattern
Start example
<copy todir="bar"> 
<filterchain> 
<replacetokens> 
<token key="TODAY"            
value="${MY_DATE_FORMAT}"/> 
</replacetokens> 
</filterchain> 
<fileset dir="foo"> 
<include name="**/*.java"/> 
</fileset> 
</copy> 
End example

The above listing shows how to replace a token that contains the current date with a token that contains the customized date.

The StripJavaComments Filter

The StripJavaComments filter strips comments from a Java source file. This filter does not take a parameter. You can use this filter to remove commented code from source files.

Listing 2-9 shows how to delete comments from specified files:

Listing 2-9: Deleting Comments
Start example
<copy todir="bar"> 
<filterchain> 
<stripjavacomments/> 
</filterchain> 
<fileset dir="foo"> 
<include name="**/*.java"/> 
</fileset> 
</copy>
End example

The above listing shows how to remove all the comments from Java files.

The StripLineComments Filter

The StripLineComments filter removes lines from files that start with user-specified comment strings. You can specify multiple numbers of comment strings by providing nested comment strings. The comment string must be the first string on the line that you want to comment on. StripLineComments contains a mandatory attribute, comment. The comment attribute defines the string that is the search pattern to search the lines in the file.

Listing 2-10 shows how to delete all the lines starting with a user-specific pattern:

Listing 2-10: Deleting Lines with a User-Specific Pattern
Start example
<copy todir="bar"> 
<filterchain> 
<striplinecomments> 
<comment value="--"/> 
<comment value="#"/> 
</striplinecomments> 
</filterchain> 
<fileset dir="foo"> 
<include name="**/*.java"/> 
</fileset> 
</copy>
End example

The above listing shows how to strip off all the lines starting with # and —. The target files do not contain any lines starting with # and —.

The StripLineBreaks Filter

The StripLineBreaks filter removes a specific string from files and joins the balance text. StripLineBreaks contains an optional parameter, linebreaks, which specifies the end of line character. The default value is \r\n.

Listing 2-11 shows how to delete all the line breaks:

Listing 2-11: Deleting Line Breaks
Start example
<copy todir="bar"> 
<filterchain> 
<striplinebreaks/> 
</filterchain> 
<fileset dir="foo"> 
<include name="**/*.java"/> 
</fileset> 
</copy> 
End example

The above listing shows how to remove all the line breaks in the Java file. The target files are without any line breaks.

The LineContains Filter

The LineContains filter filters only the lines that contain a specified string pattern. You can specify multiple strings in the pattern. With multiple string patterns, the line must contain all the user-specified strings. LineContains provides a parameter that defines a substring for the match pattern in the file.

Listing 2-12 shows how to choose lines in a user-specific pattern:

Listing 2-12: Choose Lines with a User-Specific Pattern
Start example
<copy todir="bar"> 
<filterchain> 
<linecontains> 
<contains value="foo"/> 
<contains value="bar"/> 
</linecontains> 
</filterchain> 
<fileset dir="foo"> 
<include name="**/*.java"/> 
</fileset> 
</copy> 
End example

The above listing shows how to select only the lines that contain the foo and bar strings.

The LineContainsRegexp Filter

The LineContainsRegexp filter removes only the lines that match a user-specified regular expression. LineContainsRegexp provides the regexp parameter that defines a substring for the match pattern in the file.

Listing 2-13 shows how to select files with a pattern and a regular user-specific expression:

Listing 2-13: Selecting Files Using the LineContainsRegexp Filter
Start example
<copy todir="bar"> 
<filterchain> 
<linecontainsregexp> 
<regexp pattern="foo\s{3}bar"/> 
</linecontainsregexp> 
</filterchain> 
<fileset dir="foo"> 
<include name="**/*.java"/> 
</fileset> 
</copy> 
End example

The above listing shows how to copy only the lines that contain the foo string followed by three spaces and a string bar. The code shows a special attribute s{}<integer> to insert blank spaces in the text.

The PrefixLines Filter

The PrefixLines filter copies lines, prefixing each line with user-specified strings. PrefixLines prefixes a specified prefix to every line. This filter provides the mandatory parameter prefix, which defines the string that must be prefixed to every line in the file.

Listing 2-14 shows how to select files and then add a prefix to each specified line:

Listing 2-14: Adding a Prefix
Start example
<copy todir="bar">
<filterchain> 
<prefixlines prefix="Hello"/> 
</filterchain> 
<fileset dir="foo">
<include name="**/*.java"/> 
</fileset> 
</copy> 
End example

The above listing shows how to copy all lines to a target file and add a prefix, hello, to every line. In the target files, every line starts with a string named hello.

The TabsToSpaces Filter

The TabsToSpaces filter replaces all the tabs with spaces in the file. This filter provides an optional attribute, tablength. You can use tablength to specify the length of the tab. The default length of the tab is 8 spaces.

Listing 2-15 shows how to replace tabs with spaces:

Listing 2-15: Replacing Tabs with Spaces
Start example
<copy todir="bar"> 
<filterchain> 
<tabstospaces tablength="4"/> 
</filterchain> 
<fileset dir="foo"> 
<include name="**/*.java"/> 
</fileset>
End example

The above listing shows how to copy the file and replace each tab with four spaces.

The FilterSet Data Type

The FilterSet data type is similar to the ReplaceToken filter in the FilterReader data type. FilterSet is a set of multiple filters that replaces specific patterns with user-specified strings. The default value of the user-specific pattern is @. The mandatory attribute of FilterSet is token, which defines a user-specific string pattern. The optional parameters of FilterSet are:

  • begintoken: Defines the first character of the token.

  • endtoken: Defines the last character of the token.

You can change the begintoken and endtoken attributes by specifying replacements with a series of token tags defined in the begintoken and endtoken parameters. You can also specify a token by loading filters from the file of key-value pairs.

Listing 2-16 shows how to select files and replace a user-specific pattern from the files:

Listing 2-16: Replacing a User-Specific Pattern
Start example
<copy todir="${dist.dir}"> 
<fileset dir="${src.dir}" includes="**/*.java"/> 
<filterset> 
<filter token="TODAY" value="${DSTAMP}"/> 
</filterset> 
</copy> 
End example

The above listing shows how to replace instances of @TODAY@ with the current date.

Listing 2-17 shows how to copy files using files instead of tokens:

Listing 2-17: Copying Files without Token
Start example
<copy todir="${dist.dir}"> 
<fileset dir="${src.dir}" includes="**/*.java"/> 
<filterset> 
<filtersfile file="${filters.file.name}"/> 
</filterset> 
</copy> 
End example

The above listing shows how to copy files using filters.file.name instead of token. filters.file.name is a properties file of name-value pairs from which you load tokens.

The I/O Redirectors Data Type

You can define task input and output for tasks, such as exec, which you use to execute an external process. The executed process takes input and produces output. The output of a process is categorized as desired output or error output.

The I/O Redirectors data type provides the feature of redirecting input and output using the FileMapper data type to specify the source file and the destination file.

The optional attributes of I/O Redirector are:

  • output: Defines the name of the file to write the output of tasks. It does not distinguish between error output and desired output. Any type of result from the execution of the buildfile is redirected to the same file only if the error stream is not directed to a file or property.

  • error: Defines the name of the file to which the standard error of an executed command is redirected.

  • logError: Defines the attribute used when you wish to see error output in the Ant log and are redirecting the output to a file or console. Error output will not be included in the output file or console.

  • append: Determines whether to append or overwrite output and error files. The default value of this attribute is false.

  • createemptyfiles: Determines whether or not to create output and error files when there is no output. The default value is true.

  • outputproperty: Defines the name of a property in which the output of the command should be stored. Unless the error stream is redirected to a separate file or stream, this property will include the error output.

  • errorproperty: Defines the name of the property that stores the standard error of the command.

  • input: Defines a file from which the standard input of the command is derived. This attribute is a string that represents the input stream of the executed command.

  • inputencoding: Defines input encoding.

  • outputencoding: Defines output encoding.

  • errorencoding: Defines error encoding.

The parameters specified as nested elements are:

  • inputmapper: Defines a file mapper to redirect process input. Mapping is performed on a task-specified source file. A nested <inputmapper> is not compatible with either the input or the inputstring attribute.

  • outputmapper: Defines a file mapper to redirect process output. Mapping is performed on a task-specified sourcefile. A nested <outputmapper> is not compatible with the output attribute.

  • errormapper: Defines a file mapper to redirect error output. Mapping is performed on a task-specified sourcefile. A nested <errormapper> is not compatible with the error attribute.

The PatternSet Data Type

The PatternSet data type is a group of patterns that filters files or directories based on user-specific patterns. The wildcards to create patterns are:

  • ?: Matches a single character.

  • *: Matches zero or up to any number of characters.

  • **: Matches zero or more directories recursively.

You can use the above characters to specify files of your choice. PatternSet supports four, optional nested elements:

  • include: Defines the list of directories to be included.

  • includesfiles: Defines the name of a file where each line of the file is taken as a pattern to include files.

  • exclude: Defines the list of directories that must be excluded.

  • excludesfile: Defines the name of a file where each line of the file is taken as a pattern to exclude files.

You nest the above elements in <patternset> to filter files and directories of your choice. You can use the id attribute to refer to user-specific patterns for later use. In addition, the PatternSet data type can be defined as a standalone element at the same level as target. The <includes> and <excludes> attributes accept multiple elements separated by commas or spaces. The following code shows how to select files using PatternSet:

<patternset id="mypatternset">
<include name="**/*.java"/>
<exclude name="**/*Fine*"/>
</patternset>
 </dirset>

The above code lists all .class files except those that include the text fine in their name. You can refer to this PatternSet data type with the mypatternset ID.

The Path-Like Structure Data Type

The Path-Like Structure data type is a platform-dependant path or classpath. You can specify the PATH and CLASSPATH type references using both : and ; as separator characters of the operating system you are working on. To specify a path-like value, you can use a nested value.

Listing 2-18 shows how to use the Path-Like Structure data type:

Listing 2-18: Building a Path
Start example
<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>
End example

The above listing shows how to build a path that holds the ${classpath} value, followed by all the jar files in the lib directory, the classes directory and all directories named classes in the apps subdirectory of ${build.dir}. The $(classpath) value excludes the files with the text named Test in their name and the files specified in the referenced FileList data type.

To use the same Path-Like Structure data type for several tasks, you can define them with a <path> element at the same level as targets and refer to them using their id attribute.

Listing 2-19 shows how to use the id attribute in the Path-Like Structure data type:

Listing 2-19: Using the id Attribute
Start example
<path id="basics.path2">
<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>
End example

The above listing shows how to use the basics.path2 ID to define the pattern for file selection.

The Permissions Data Type

The Permissions data type is a set of security permissions that grants or revokes permission on a specific set of code executed in the Java Virtual Machine (JVM) where Ant is running. Permissions uses a nested set of permissions, <grant> and <revoke>.

When you run Ant without Permissions, you run it with a Base set, which is the set of default permissions granted to Ant.

The Base set is a set of permissions that implicitly contains the following permissions:

<grant class="java.net.SocketPermission" name="localhost:1024-" actions="listen">
<grant class="java.util.PropertyPermission" name="java.version" actions="read">
<grant class="java.util.PropertyPermission" name="java.vendor" actions="read">
<grant class="java.util.PropertyPermission" name="java.vendor.url" actions="read">
<grant class="java.util.PropertyPermission" name="java.class.version" actions="read">
<grant class="java.util.PropertyPermission" name="os.name" actions="read">
<grant class="java.util.PropertyPermission" name="os.version" actions="read">
<grant class="java.util.PropertyPermission" name="os.arch" actions="read">
<grant class="java.util.PropertyPermission" name="file.encoding" actions="read">
<grant class="java.util.PropertyPermission" name="file.separator" actions="read">
<grant class="java.util.PropertyPermission" name="path.separator" actions="read">
<grant class="java.util.PropertyPermission" name="line.separator" actions="read">
<grant class="java.util.PropertyPermission" name="java.specification.version" actions="read">
<grant class="java.util.PropertyPermission" name="java.specification.vendor" actions="read">
<grant class="java.util.PropertyPermission" name="java.specification.name" actions="read">
<grant class="java.util.PropertyPermission" name="java.vm.specification.version" actions="read">
<grant class="java.util.PropertyPermission" name="java.vm.specification.vendor" actions="read">
<grant class="java.util.PropertyPermission" name="java.vm.specification.name" actions="read">
<grant class="java.util.PropertyPermission" name="java.vm.version" actions="read">
<grant class="java.util.PropertyPermission" name="java.vm.vendor" actions="read">
<grant class="java.util.PropertyPermission" name="java.vm.name" actions="read">

The Permissions data type allows you to overlook security permissions by revoking them. This data type provides a security manager that throws an exception SecurityException. This exception occurs when the code asks for a permission that has not been granted or has been revoked by the Permissions data type.

The grant and revoke Element

The Permissions data type uses the grant element to grant a specific permission. The mandatory attribute of the grant element is class, which defines the name of the permission class. The optional attributes of the grant element are:

  • name: Defines the name of the permission, which depends on the permission class.

  • action: Defines the allowed action, which depends on the name and class attributes.

The Permissions data type uses the revoke element to revoke a particular permission. The revoke element can revoke any set of permissions from the base class. The mandatory attribute of the revoke element is class, which defines the name of the permission class. The optional attributes of the revoke element are:

  • name: Defines the name of the permission, which depends on the permission class.

  • action: Defines the allowed action, which depends on the name and class attribute.

The following code shows how to grant permissions using the grant element:

<permissions>
<grant class="java.security.AllPermission"/>
<revoke class="java.util.PropertyPermission"/>
</permissions>

The above code grants all permissions to the entire code, except to the code handling the properties of permissions.

The PropertySet Data Type

The PropertySet data type allows you to collect the properties of files. PropertySet uses file mappers to select multiple files to extract properties.

PropertySet provides three parameters: propertyref, propertyset, and mapper. The mandatory attributes of PropertySet are:

  • propertyref: Selects the properties that should be included in PropertySet. All the elements in this attribute are also mandatory. The elements of this attribute are:

    • name: Selects the property.

    • prefix: Selects properties based on a user-specified pattern.

    • regexp: Selects the property that matches a specified regular expression.

    • builtin: Selects a built-in set of properties.


The optional attributes of the PropertySet are:

  • propertyset: Allows you to use multiple PropertySets and prepares the set union of the property sets.

  • mapper: Changes the names of property keys.

Listing 2-20 shows how to collect properties using the PropertySet data type:

Listing 2-20: Using PropertySet to Collect Properties
Start example
<propertyset id="properties-test">
<propertyref prefix="test"/>
</propertyset>
<propertyset id="properties-lady">
<propertyref prefix="lady"/>
</propertyset>
<propertyset id="my-set">
<propertyset refid="properties-test"/>
<propertyset refid="properties-lady"/>
</propertyset>
End example

The above listing shows how to collect properties using the PropertySet data type whose filename starts with test or lady.

The Selectors Data Type

The Selector data type selects files based on specified criteria, such as date and time of update, and case sensitivity. Selector is an element of the FileSet data type. Selector selects files based on criteria other than their filenames. Some selectors can contain other selectors. These selectors are called Selector Containers.

Ant consists of two types of selectors:

  • Core selectors

  • Custom selectors

Core Selectors

Ant contains some built-in, standard selectors called core selectors. You can use core selectors within FileSet data types and store these core selectors in Selector Containers. Ant contains various core selectors, such as <contains>, <depend>, and <date>.

Contains Selector

The Contains selector selects only the files that contain a user-specific text string. This selector scans files for a user-defined string pattern and selects the files that contain the string. The mandatory attribute of the Contains selector is text, which specifies the string pattern that each file must contain. The optional attributes of the Contains selector are:

  • casesensitive: Defines case sensitivity when looking for a string in the file. The default value of this selector is true.

  • ignorewhitespace: Defines whether or not to ignore white spaces in the string. The default value of this selector is false.

The following code shows how to select files that contain a user-specific text pattern:

<fileset dir="${doc.path}" includes="**/*.html">
<contains text="test" casesensitive="no"/>
</fileset>

The above code selects only the files that contain the string test. The above code does not check case sensitivity and includes only .html files.

The Date Selector

The Date selector selects only the files that are modified after or before a user-specified date and time. The mandatory attributes of the Date selector are:

  • datetime: Specifies the date and the time to test the files. The format is MM/DD/YYYY HH:MM AM_or_PM. This attribute is mandatory if you do not specify the millis attribute.

  • millis: Defines the total number of milliseconds after 1970. This attribute is mandatory if you do not specify the datetime attribute.

The optional attribute of the Date selector is when, which defines whether the selected files are modified before or after the specified date and time. This attribute contains three values: before, after, and equals. The acceptable values of this attribute are:

  • before: Selects the files whose last modified date is before the specified date.

  • after: Selects the files whose last modified date is after the specified date.

  • equal: Selects the files whose last modified date is equal to the specified date.


The following code shows how to select a file using the datetime attribute:

<fileset dir="${jar.path}" includes="**/*.jar">
<date datetime="03/13/2003 08:00 PM" when="before"/>
</fileset>

The above code selects the files that were last modified before 20:00 hours, March 13, 2003.

The Depend Selector

The Depend selector selects files whose last modified date is later than another, equivalent file at another location. Depend also supports mapper elements. If a mapper element is not specified, Depend uses the identity mapper as the default mapper. This means that equivalent files at different locations are modified and the files are not equivalent. Depend is useful when you look for changes in files in different versions of software. The mandatory attribute of Depend is targetdir, which defines the base directory in which the selector looks for files. The optional attribute of Depend is granularity, which defines the number of milliseconds to wait before deciding that a file is out of date. You need this time because not every file system supports the tracking of the last modified time to the millisecond level.

The following code shows how to select files using Depend:

<fileset dir="${ant.1.5}/src/main" includes="**/*.java"> 
<depend targetdir="${ant.1.4.1}/src/main"/> 
</fileset> 

The above code lists the files changed between two versions of Ant.

The Depth Selector

The Depth selector selects files based on how many directory levels deep they are in relation to the base directory of the file set. The mandatory attributes of Depth are:

  • min: Defines the minimum number of directory levels below the base directory that the selector should look for files. This attribute is mandatory if you do not use the max attribute.

  • max: Defines the maximum number of directory levels below the base directory that the selector should look for files. This attribute is mandatory if you do not use the min attribute.

The following code shows how to select files in the base directory and two levels below the base directory:

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

The above code selects files that are present in the base directory and two levels below the base directory.

The Different Selector

The Different selector selects files that are different in some aspects. This selector performs a byte-for-byte comparison on equal-length files. The rules for deciding the differences are:

  • If there is no other file with the same name, the files are different.

  • Files are different if they are of differing lengths.

  • Files are different if the file timestamps are different and the ignoreFileTimes attribute is set to no.

Different is useful for program tasks that do not apply dependency checking measures, which are the steps taken to check file dependencies. The mandatory attribute of Different is targetdir, which defines the base directory for file comparison. The optional attributes of Different are:

  • ignoreFileTimes: Defines whether or not to use file timestamps in the comparison.

  • granularity: Defines the number of millisecond leeway to allocate before deciding that a file is out of date. You need the leeway because not every file system supports tracking the last modified time to millisecond level.

The following code shows how to compare files using Different:

<fileset dir="${ant.1.5}/src/main" includes="**/*.class">
<different targetdir="${ant.1.4.1}/src/main"
ignoreFileTimes="true"/>
</fileset>

The above code selects all the class files between the 1.4.1 and the 1.5 release of Ant and selects the files that are different, regardless of file times.

The Filename Selector

The Filename selector is similar to the <include> and <exclude> tags in the FileSet data type. You can combine Filename with all the other selectors to acquire the target files. Filename combines itself with other selectors using Selector Container.

Filename is case sensitive. The mandatory attribute of Filename is name, which defines the name of the file to be selected. This attribute uses the standard wildcard characters of Ant. The optional attributes of Filename are:

  • casesensitive: Defines whether or not to guard the case sensitivity of the filenames. The default value of this attribute is true.

  • negate: Reverses the effect of filename selection. The default value of this attribute is false.

The following code shows how to select files using the Filename selector:

<fileset dir="${doc.path}" includes="**/*">
<filename name="**/*.jar"/>
</fileset>

The above code selects all the .jar files.

The Present Selector

The Present selector selects all the files that are present either in the source or target directory or only in the target directory. Present selector takes the files from a directory and checks for the same files in the target directory. Present is case sensitive and uses mapper elements to match files. You can use any mapper for the selection. If you do not define a mapper, Present uses the identity mapper. The mandatory attribute of Present is targetdir, which defines the base directory to look for the files to compare against. The optional attributes of Present are:

  • present: Supports the use of mappers to look for the files to be compared. The present attribute can take two values, which are:

    • srconly: Selects files only if they are in the source directory tree and not in the target directory tree.

    • both: Selects files only if they are present both in the src and target directory trees.


The following code shows the selection of all JAR files in Ant.1.5 version:

<fileset dir="${ant.1.5}/src/main" includes="**/*.jar">
<present present="srconly" targetdir="${ant.1.4.1}/src/main"/>
</fileset>

The above code copies all the jar files that are not present in the ant.1.4.1}/src/main directory.

The Regular Expression Selector

The Regular Expression selector selects the target files that contain a user-specified pattern. You build the expression for Regular Expression using the expression attribute, which specifies the regular expression that is the matching pattern for the selector.

The selector contains the <containsregexp> tag, which limits the files to only the files that contain the user-specific expression. The following code shows how to select files based on a regular expression:

<fileset dir="${doc.path}" includes="*.txt">
<containsregexp expression="[5-8]\.[3-4]"/>
</fileset>

The above code selects only the files that have a regular expression, 5, 7, or 8, followed by a period, which is followed by a number from 3 to 4.

The Size Selector

The Size selector selects files based on their size. This selector selects the files on the less than, greater than, or equal to criterion based on a unit value. The mandatory attribute of Size is value, which defines the size of the file. The optional attributes of Size are:

  • unit: Defines the unit in which the value attribute is expressed. When using the standard single-letter SI designations, such as k, M, or G, multiples of 1,000 are used. If you want to use the unit with the exponent as 2, use the International Electrotechnical Commission (IEC) standards, which are Ki for 1024 and Mi for 1048576. The default is no units, which means that the value attribute expresses the exact number of bytes.

  • when: Defines whether or not the target files should be equal, greater than, or less than the indicated size.

Listing 2-21 shows how to select files based on size:

Listing 2-21: Selecting Files Based on Size
Start example
<fileset dir="${jar.path}">
<patternset>
<include name="**/*.jar"/>
</patternset>
<size value="4" units="Ki" when="more"/>
</fileset>
End example

The above listing shows how to select all .html files with sizes greater than 4,096 bytes.

The Type Selector

The Type selector selects files of specific type, such as a regular file, or a directory. Type has one mandatory attribute type. The type attribute accepts two values, dir for directories and file for files. You can also use these selectors in conjunction with other selectors. The following code shows how to select directories:

<fileset dir="${src}">
<type type="dir"/>
</fileset>

The above code selects all the directories in ${src}.

Listing 2-22 shows how to select files using the Type selector:

Listing 2-22: Using the Type Selector
Start example
<fileset dir="${src}">
<and>
<present targetdir="template"/>
<type type="file"/>
</and>
</fileset>
End example

The above listing selects files that also exist in a template directory but does not select empty directories.

The Modified Selector

The Modified selector computes a value for a file using an algorithm, compares the computed value to the value stored in a cache, and selects the file if the two values differ.

To compute the value:

  1. Compute the absolute path for the file.

  2. Obtain the cached value.

  3. Compute the value using the configured algorithm.

  4. Compare the two values using a comparator.

  5. Update the cache, if needed and requested.

  6. Make the selection based on the comparison.

Special interfaces compare and compute hashvalue and storage. The interfaces provide the following optional attributes:

  • algorithm: States the algorithm. This attribute takes two values, hashvalue and digest.

    • hashvalue: Reads the content of a file into java.lang.String.

    • digest: Uses java.security.MessageDigest to compute values. This algorithm supports two attributes, algorithm.algorithm and algorithm.provider. The algorithm.algorithm attribute defines the name of the Digest algorithm, such as MD5 or SHA. The default algorithm is MD5. The algorithm.provider attribute defines the name of the Digest provider.


  • cache: Defines the type of cache. The accepted value is properetyfile.

  • comparator: Defines the type of comparator.

  • update: Defines that the value of the cache should be updated, If the values in the file differ. The update attribute is of boolean type.

  • seldirs: Defines whether or not the directories need to be selected in the file set. The seldirs attribute is of boolean type.

Listing 2-23 shows how to copy files that contain changed text:

Listing 2-23: Coping Files Using the Modified Selector
Start example
<copy todir="lode">
<filelist dir="bind">
<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>
</filelist>
</copy>
End example

The above listing shows how to copy all the files with changed code from the bind directory to the lode directory. The code uses an updated PropertyfileCache with cache.properties and the MD5 digest algorithm.

Custom Selectors

Custom selectors are also known as Selector Containers. Custom selectors can contain other selectors to create a particular user-specified selector. Custom selectors combine other selectors using them as elements. The selector elements within containers are:

  • and

  • or

  • not

  • majority

  • none

  • select

The and Selector

The and selector contains a number of contained selectors that individually produce files. This selector selects only the files that are present in every file set of the contained selector. This selector applies several conditions defined by individual selectors. The and selector produces only the files that are selected by all selectors.

Listing 2-24 shows how to use the and selector:

Listing 2-24: Using the And Selector
Start example
<copy todir="${tmp.dir}"> 
<fileset dir="${src.dir}" includes="**/*.java"> 
<and> 
<filename name="**/*line*.java"/> 
<date datetime="09/23/2004 12:00 PM"                        
when="before"/> 
</and> 
</fileset> 
</copy> 
End example

The above listing shows how to use two contained selectors, filename and date. The filename selector selects the files that contain the text line in their filenames. The date selector selects only the files that are modified before September 23, 2004. The custom selector contains only the common selectors in the file sets.

The or Selector

The or selector contains a number of contained selectors that individually produce a file set. This selector selects all files from all file sets. The or selector selects every file that satisfies the conditions specified in any one selector.

Listing 2-25 shows how to use the or selector:

Listing 2-25: Using the Or Selector
Start example
<copy todir="${tmp.dir}"> 
<fileset dir="${src.dir}" includes="**/*.java"> 
<or> 
<filename name="**/*line*.java"/> 
<date datetime="09/23/2004 12:00 PM"                     
when="before"/> 
<size value="1" units="Ki" when="more"/> 
</or> 
</fileset> 
</copy> 
End example

The above listing shows how to select all the files that contain the text line in their filenames and are modified before September 23, 2004.

The not Selector

The not selector reverses the result of the file set of its contained selector. This selector negates the output of the contained selector to obtain the target files. This selector can contain only one selector and the contained selector can be another container selector.

Listing 2-26 shows how to use the not selector:

Listing 2-26: Using the not Selector
Start example
<copy todir="${tmp.dir}"> 
<fileset dir="${src.dir}" includes="**/*.java"> 
<not>
<and> 
<filename name="**/*line*.java"/> 
<date datetime="09/23/2004 12:00 PM"                        
when="before"/> 
<size value="1" units="Ki" when="more"/> 
</and> 
</not>
</fileset> 
</copy> 
End example

The above listing shows how to use two contained selectors, filename and date. The filename selector does not select the files with the text line in their filenames. The date selector does not select the files that are modified after September 23, 2004. The custom selector contains only the common selectors in the file sets.

The majority Selector

The majority selector is a combination of the and and or selectors. The majority selector selects a file if a majority of contained selectors select a file. The majority selector contains the allowtie attribute. This attribute allows the majority selector for a tie. This means that a file is selected if a majority of the selectors select it.

Listing 2-27 shows how to select files using the majority selector:

Listing 2-27: Using the majority Selector
Start example
<copy todir="${tmp.dir}"> 
<fileset dir="${src.dir}" includes="**/*.java"> 
<majority> 
<filename name="**/*line*.java"/> 
<date datetime="09/23/2004 12:00 PM " when="before"/>  
<size value="1" units="Ki" when="more"/> 
</majority> 
</fileset> 
</copy> 
End example

The above listing shows how to select the files that meet two of the three criteria for selection.

The none Selector

The none selector selects only the files that are not available in the file sets of the contained selectors. This means that only those files are selected that are not selected by any of the selectors.

Listing 2-28 shows how to use the none selector:

Listing 2-28: Using the none Selector
Start example
<copy todir="${tmp.dir}"> 
<fileset dir="${src.dir}" includes="**/*.java"> 
<none> 
<filename name="**/*Test*.java"/> 
<date datetime="09/23/2004 12:00 PM"                        
when="before"/> 
</none> 
</fileset> 
</copy> 
End example

The above listing shows how to select files where the filename selector selects all the files that contain the text line in their filenames and the date selector selects only the files that were modified before September 23, 2004.

The selector Selector

The selector selector is a reference to a selector. This selector contains an id attribute that assigns an identification, which you can refer to later. This is the only selector that can be specified outside a target. This selector contains only one selector that can also be a container.

Listing 2-29 shows how to select a file using a reference:

Listing 2-29: Using a Reference for Selection
Start example
<target name="init"> 
<selector id="mySelector"> 
<and> 
<filename name="**/*line*.java"/> 
<date datetime="07/21/2002 12:00 PM" when="before"/> 
</and> 
</selector> 
</target> 
<target name="copy" depends="init"> 
<copy todir="${tmp.dir}"> 
End example

<fileset dir="${src.dir}" includes="**/*.java">

<selector refid="copySelector"/> 
</fileset> 
</copy> 
</target>

The above listing shows how to use a selector ID, mySelector. You can refer to this selector using the mySelector ID.

The XMLCatalog Data Type

The XMLCatalog data type is a catalog of the public resources, such as Document Type Definitions (DTDs), of an XML file. The DTD defines the document’s structure with a list of legal elements. The XMLCatalog data type can appear inside tasks that support a catalog of public resources or at the same level as target. The XML Validate task uses XMLCatalog for entity resolution. The eXtensible Stylesheet Language Transformation (XSLT) uses XMLCatalog for both entity and Universal Resource Identifier (URI) resolution. XMLCatalog provides standards for XML documents. You can use XMLCatalog to make Web references to resources that point to a locally cached point of resources. XMLCatalog contains an element named catalogpath. The nested catalogpath element is a path-like structure that lists the catalog files to be searched. All files in this path are assumed to be Organization for the Advancement of Structured Information Standards (OASIS) "Open Catalog" files in either plain text or XML format. The filenames that are no longer available will be ignored. If the resolver library from xml-commons is not available in the classpath, Ant will ignore all the catalog paths and will log a warning. The XMLCatalog data type contains two optional attributes:

  • id: Defines the name for XMLCcatalog that defines an identification for the XML catalog’s content from another XMLCatalog.

  • refid: Defines the ID of another XMLCatalog whose content you want to use in the current XMLCatalog.

Listing 2-30 shows how to use XMLCatalog:

Listing 2-30: Using XMLCatalog
Start example
<target name="init"> 
<xmlcatalog id="ejbDTDs"> 
<dtd 
End example

publicId="-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"

location="c:/DTDs/ejb-jar-2.0.dtd"/> 
<dtd 

publicId="-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN"

location="ejb-jar-1.1.dtd"/> 
</xmlcatalog> 
</target> 
<target name="validate" depends="init"> 
<xmlvalidate file="${etc.dir}/ejb-jar.xml"> 
<xmlcatalog refid="ejbDTDs"/> 
</xmlvalidate> 
</target>

The above listing shows how to first create and then use an XMLCatalog.

The ZipFileSet Data Type

The ZipFileSet data type is a special form of FileSet data type with some extra attributes that are useful for Zip/JAR tasks. ZipFileSet adds additional features to FileSet and supports all attributes of FileSet.

ZipFileSet behaves in two ways:

  • Using the src attribute, ZipFileSet is populated with the zip entries found in the src file.

  • Using the dir attribute, ZipFileSet is populated with the file system files found under dir.

ZipFileSet contains five optional attributes:

  • prefix: Inserts a prefix for all files in the file set.

  • fullpath: Places the file described in fileset in the exact location in the archive.

  • src: Specifies a zip file whose contents are to be extracted and included in the archive.

  • filemode: Specifies the user, group, and other modes in standard UNIX as a 3-digit octet string. The default value of filemode attribute is 644. This attribute applies only to files.

  • dirmod: Specifies the user, group, and other modes in standard Unix as a 3-digit octet string. The default value of dirmod attribute is 755. This attribute applies only to directories.

Prefix and full path are mutually exclusive for a file set. Include and exclude patterns may also be used to specify the subsets of a zip file for inclusion in the archive.

Listing 2-31 shows how to use ZipFileSet:

Listing 2-31: Using ZipFileSet
Start example
<zip destfile="${dist}/manual.zip">
<zipfileset dir="mydocs/manual" prefix="docsmine/user-manual"/>
<zipfileset dir="." includes="ChangeLog27.txt" fullpath="docs/ChangeLog.txt"/>
<zipfileset src="examples.zip" includes="**/*.html" prefix="docs/examples"/>
</zip>
End example

The above listing shows how to zip all files in the mydocs/manual directory into the docsmine/user-manual directory in the archive. It adds the ChangeLog27.txt file to the current directory as docs/ChangeLog.txt and includes all the HTML files in examples.zip under docs/examples.



Previous Section
Table of Contents
Next Section