Home
Ant: The Definitive Guide, 2nd Edition By Steve Holzner
Contents
1. Tokenizes the filtered text into strings One optional attribute delimoutput tokenfilter i overrides the tokendelimiter returned by the tokenizer Each of these filters correspond to a Java class for example the head filter corresponds to org apache tools ant filters HeadFilter Here are a few examples Suppose you want to read the first three lines of the file given by sourcefile into the property sourcefile header You could use filterreader and the Ant filter reader class org apache tools ant filters HeadFilter lt loadfile srcfile S sourcefile property sourcefile header gt lt filterchain gt lt filterreader classname org apache tools ant filters HeadFilter gt lt param name lines value 3 gt lt filterreader gt lt filterchain gt lt loadfile gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir Ant gives you a shortcut with filter readers like this one where you can use a task namedheadfilter to do the same thing lt loadfile srcfile S sourcefile property sourcefile header gt lt filterchain gt lt headfilter lines 3 gt lt filterchain gt lt loadfile gt The linecontains filter reader includes only those lines that contain all the strings you specify with contains elements Here s an example where I m filtering only lines containing apples and oranges lt linecontains gt lt contains value apples gt lt contains value oranges gt lt
2. downloaded from lib eommolketab ir handling for custom tasks for project elements for property elements for target elements author attribute javadoc task authserver command CVS available element condition task available task 2nd 3rd 4th axisdeploy element ejbdoclet task axisundeploy element ejbdoclet task downloaded from lib eommolketab ir downloaded from lib eommoltketab ir Index A B C D E F G H I Y K L M N O P Q R S M U V W X Z back slash backups attribute patch task basedir attribute cab task ear task jar task project element 2nd 3rd tar task 2nd war task xslt style task zip task BaseExtendSelector class basejarname attribute ejbjar task basename task 2nd bash shell Unix 2nd batch execution batch testing 2nd batchtest element 2nd batchtest task bcc element mail task bcclist attribute mail task begintoken attribute FilterSet type binary attribute ftp task binary release Ant 2nd blgenclient task EJB 2nd boolean data type bootclasspath attribute javac task 2nd javadoc task path type bootclasspath element java task and path type and bootclasspathref attribute javac task javadoc task borland element ejbdoclet task nesting and bottom attribute javadoc task branching See forking breakiterator attribute javadoc task brief formatter 2nd downloaded from lib eommolketa
3. these values downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 3 3 Calling Other Ant Tasks You ve seen that you can branch using true false properties Ant provides other powerful mechanism for branchingthe antcall task which you can use to call one Ant task from another and theant task which calls Ant tasks in other build files 3 3 1 Calling Ant Tasks in the Same Build File A better way to think of antcall Is that you re starting a new instance of Ant and executing targets in it When you call an Ant target with antcali its dependent targets are executed in order something that can be confusing if you think you re calling a single target Generally it s best to do things the standard way and let Ant sort out the dependencies as it s Supposed to However Ant can make life easier aS when you Nave a build file that creates a distribution for many different servers and when varying sets of tasks need to be executed for each Even in cases like that however you can still se things up easily enough withif and unless and true false properties When you use antcall you can think of that call as creating a new project all the properties of the current project are available in that new project by default The attributes of theantcall task appear in Table 3 4 Table 3 4 The antcall attributes Attribute Description Required Default If true means the task should pass all current properti
4. 12 2 9 Running Scripts While discussing how to execute external programs Ant includes an optional task namedscript that can run scripts such as those written in JavaScript You needbsf jar from http jakarta apache org bsf n the IBM version in the Ant lib directory to run this task You ll need one or more of these jar files depending on the scripting language you want to use downloaded from lib ommolketab ir downloaded from lib ommoltketab ir jacl jar and tcljava jar Resources to run TCL scripts Get them from http www scriptics com software java jruby jar Resources to run Ruby scripts Get this from http jruby sourceforge net js jar JAR file for running JavaScript code Get it from http www mozilla org rhino judo jar Resources to run J udoscript code Get this from http www judoscript com index html jython jar JAR file to run Python scripts Get it from http jython sourceforge net netrexx jar Resources to run Rexx scripts Get this from http www2 hursley ibm com netrexx The BeanShell J AR files You need these to run BeanShell scripts Get them from http www beanshell org Ant 1 6 and later require Beanshell Version 1 3 or later The attributes for the script taSk appear in Table 12 4 Table 12 4 The script tasks s attributes Attribute Description Requirs language Specifies the script s language Must be a supported Apache BSF language Yes Speci
5. BUILD SUCESSFUL Total time 2 seconds Here s the Windows version C ant chOl gt ant f properties xml Buildfile properties xml init mkdir Created dirt Ce ant cho bin compile javac Compiling 1 source file to C ant ch0l1 bin compress jar Building jar C ant ch01 bin Project jar main echo echo Building the jar file echo BUILD SUCCESSFUL Total time 4 seconds downloaded from lib ommolketab ir downloaded from lib ommotketab ir 1 4 5 2 Built in properties Ant gives you access to the same system properties you d have access to in Java code as if they were Ant properties For example if you want to determine the name of the operating system you can refer to os name in your build file For a list of system properties see the Java documentation of the System getProperties method Ant has some additional Ant specific properties ant file Contains the absolute path of the build file ant java version Contains the JVM version Ant is using can hold only1 1 1 2 1 3 1 4 and as of Ant 1 6 1 5 ant project name Holds the name of the project that is executing set with thename attribute of project anteversion Contains the version of Ant running basedir Holds the absolute path of the project s base directory set with thebasedir attribute of project downloaded from lib ommolketab ir downloaded from lib ommotketab ir 1 5 Running Ant Running
6. Static void assertNull java lang String message Tests if an object is null java lang Object object ane ee objec a Tests if two objects refer to the same object Static void assertSame java lang Object expected java lang Object actual Tests if two objects refer to the same object Static void assertSame java lang String message java lang Object expected java lang Object actual static void atsar Irne boolean condition Tests if a condition is true static void assertTrue java lang String message boolean E Tests if a condition is true condition static void failil j Makes a test fail Makes a test fail with the specified message static void fail java lang String message Table 5 2 lists the methods specific to the J Unit TestCase method downloaded from lib ommolketab ir downloaded from lib ommolketab ir Table 5 2 The junit framework TestCase methods Method Does this ine dount Testcases Counts how many test cases are executed rotected TestResult j Creates a default TestResult object createResult java lang String getName Gets the name of a TestCase and returns it TestResult run Runs a test storing results in aTestResult object void un Testhesult result Runs a test case and stores the results inTestResult void runBare Executes a bare test id setN java lang Stri m iene ee eae eee edd Specifies the name of a test case protected void
7. ava jar S bin connect Jar fork true failonerror true maxmemory 512m gt lt arg value q gt Clees pall lt pathelement location S bin connect jar gt lt pathelement path S java class path gt lt Slasspath gt lt java gt This example passes on a system property and an argument to the JVM lt java classname Project main fork true gt lt sysproperty key DEBUG value true gt lt arg value z gt lt jvmarg value enableassertions gt lt classoa un lt pathelement location S bin gt lt classpath gt lt java gt As you can see there are a great many options when running J ava code downloaded from lib ommolketab ir downloaded from lib ommolketab ir 7 2 Executing External Programs The exec task executes a system command or external program The attributes for this task appear in Table 7 2 Table 7 2 The exec task s attributes Attribute Description Required Default opera Specifies whether you want to append to NO eee output and error files Deprecated Use executable and nested arg Exactly one of elements Specifies the command you want to command or run executable Specifies the directory where you want to run the command Specifies the file where standard error output ce EOr Should be stored command Specifies the name of a property where you errororopert oe d want to store errors Exactly one of c
8. lt i tp To delete files set action to del lt ftp action del server 000 000 000 000 remotedir cgi bin userid S name password password gt lt fileset gt lt include name html gt lt fileset gt SIED To list files set action to list here s how to store the listing of files in the remote cgi bin directory in a file named file list lt ftp action ist server 000 000 000 000 remotedir cgi bin userid S name password password lioting iC e digt gt lt fileset gt lt include name gt lt fileset gt STID Here s how to create a directory cgi bin by setting action to mkdir lt ftp action mkdir server 000 000 000 000 downloaded from lib ommolketab ir downloaded from lib ommolketab ir remotedir cgi bin userid Iname password password gt You can remove directories set action to rmdir You can see the attributes of this task inTable 4 12 Table 4 12 The ftp task s attributes Attribute Description Required Default Specifies the ftp action you want to action perform Possible values put get del No send list chmod mkdir and rmdir Specifies the transfer mode Possible values binary mode yes or text mode No no Specifies the file permissions for new or chmod existing files Unix only binary Specifies you want to transfer only new or changed files Set to yes no Specifies
9. lt target name commit depends login gt lt cevs dest S cvs dir GreetingApp command commit m New Version gt lt target gt lt project Here s what this build file gives you when you run it and the CVS server commits the new code Sant Bulldfile build xml downloaded from lib ommolketab ir downloaded from lib ommotketab ir Login commit eys Using cvs paserile home cvspass cvs cvs commit Examining cvs cvs commit Examining org cvs cvs commit Examining org antbook leys eve commit Examining oroyancbock cn0G evs Checking in org antbook ch06 GreetingClass java cvs home steven repository GreetingApp org antbook ch06 GreetingClass java v lt GreetingClass java cvs new revision 1 5 previous revision 1 4 cvs done main echo echo Committing echo BUILD SUCCESSFUL Total time 1 second 6 3 4 Comparing Files You can compare local files to those in the CVS repository with the CVSdiff command For example say that the module you ve been working with GreetingApp contains GreetingClass java which holds these contents presumably committed earlier by you or another developer package org antbook ch06 public class GreetingClass DUDLIG tatio void main string ards system out printin No problems here Then suppose you change the displayed message from No problems here to No problems at all in the local version of the file
10. package org antbook ch06 public class GreetingClass public static void main String args downloaded from lib ommolketab ir downloaded from lib ommoltketab ir System out printin No problems at all The CVS diff command finds the difference between your local copy and the server s version You can see a build file using this command in Example 6 4 in this case the differences are written to a file named patch txt Example 6 4 Finding differences in a CVS module chO6 diff build xml lt 7xml version 1 0 gt lt project default main basedir gt propercy fmome evs cir valiue project gt lt target name main gt lt cvspass cvsroot pserver steven STEVE home steven repository password opensesame gt lt cvs command diff dest S cvs dir GreetingApp output patch txt gt lt target gt lt project gt Here s what the build process looks like at work Sant Buildfile build xml main evs Using cvs passfile home cvspass evs cva Server Diriring cvs cvs server Diffing org evs cvs server Diffing org antbook evs cvs server Diffing org antbook ch06 BUILD SUCCESSFUL Total time 1 second In patch txt the diff command caught the difference between the local copy of the file and the version in the CVS repository Index org antbook ch06 GreetingClass java RCS file home steven repository GreetingApp org antbook ch06 GreetingClass java v retrievi
11. public class Nested public Nested String language downloaded from lib ommolketab ir downloaded from lib ommotketab ir public void setLanguage String language this language language public String getLanguage return language Here s what the build file looks like when running The support code handled the nested elements and recovered the value of the language attributes Sant Buildfile build xml compile javac Compiling 1 source file to home steven ant ch1l2 nestedelement output jar jar Building jar home steven ant ch1l2 nestedelement Project jar main project The language is English project The language is German BUILD SUCCESSFUL Total time 3 seconds 12 2 7 Using Filesets You can make your custom tasks support filesets with the right code Example 12 11shows a custom tas project acting as a fileset with an include nested element In this case the custom project element wi display all the java files in and below the base directory Example 12 11 Supporting filesets in a build file ch12 fileset src Project java lt xml vwersi10n 1 0 7 gt lt project basedir default main gt lt property name srce value src gt lt property name output value output gt lt target name main depends jar gt lt taskdef name project classname Project classpath Project jar gt downloaded from lib ommolketab ir downloaded fro
12. Attribute Description Required Default Specifies the base name you want used for basejarname No the generated jar files Specifies the classpath you wnt used when classpath resolving classes that are to be added to No the jar Specifies the CMP version Possible values cmpversion Ez 1 0 Or 2 0 E ATEO eer Specifies which classes and interfaces are P y added to the jar Specifies the directory under which the descrip rordixz task shoulc scan for EJB deployment descriptors Yes unless you use Specifies the directory into which you want vendor specific destdi ii generated J AR files to be placed deployment elements Specifies you want to store all generated JARs in the root of the destdir rather flatdestd os seca than the location specified by the ng deployment descriptor Set to true false Specifies a string that you want appended Bp __ to the deployment descriptor in order to e genericjarsuffix No generic jar create the filename of a generic EJB JAR file Specifies the naming convention you want naming No to use to name generated EJB jars downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required Default Specifies the base directory containing the lsrcedir class files that make up the generated Yes bean You can nest classpath elements to set the classpath in theejb
13. downloaded from lib eommolketab ir modules and moving scanning working with groups of DirectoryScanner class dirmode attribute tarfileset element ziptileset element dirname task 2nd dirset element apply task chmod task DirSet type 2nd 3rd displayname attribute user element docencoding attribute javadoc task doclet attribute javadoc task doclet task XDoclet docletpath attribute javadoc task docletpathref attribute javadoc task doctitle attribute javadoc task document element documentation See also reports See also reports of code fixing Carriage returns in JUnit dollar sign 2nd DSTAMP property tstamp task 2nd dtd element ejbjar task xmlicatalog element and xmlivalidate task and DTDs antstructure task and creating for Ant tasks 2nd validating with XMLCatalog and dump attribute depend task duplicate attribute ear task jar task war task zip task duration attribute success fail elements downloaded from lib eommolketab ir downloaded from libeommolketab ir Index A B C D E F G H 1 fy K L M N O P Q R S M U V W RX Z e option ear task 2nd 3rd easerver element ejbdoclet task echo task creating text files description example 2nd JavaScript and output and 2nd echoproperties task Eclipse IDE Ant versions and 2nd Ant view and overview running Ant build files writing Ant build files eclipse org consortium
14. downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default Specifes the patterns matching files to exclude excludes No aS a comma or Space separated list Specifes the name of a file where each line is a excludesfile maa ee matching files to exclude feilesonly Specifies you want to store only file entries Secon false Specifes the patterns matching files to include includes as a comma or Space separated list Specifes the name of a file where each line is a pattern matching files to include Preserves the compression as it has been in keepcompression archives you re compressing instead of using false the compress attribute Available since Ant 1 6 Specifies the manifest file to use in the manifest No compressed file Specifies whether you want to update or a l fal a overwrite the target file if it exists me _ Exactly one of includesfile Deprecated Use destfile Specifies the WAR warfile destfile Or file you want to create warfile gape Specifies the deployment descriptor you want icra to to use Will be deployed to WEB INF web xml ue S The war task can contain elements like fileset and zipfileset to specify what files to include in the war file This task can contain these elements to specify where you want various files to go e Files contained in the webinf element end up in WEB INF e Files contained in the classes e
15. downloaded from lib ommotketab ir 1 4 Anatomy of a Build File Ant projects all revolve around one or more build files By default Ant looks for a build file named build xml Because Ant files are XML documents they start with an XML declaration as all valid XML documents must lt 7 Version L OU 7 For the complete XML 1 0 syntax look at http www w3 org TR REC xml XML 1 1 is out now as well but Ant build files are based on XML 1 0 and the difference between these versions is small anyway centering mostly on the manner in which certain Unicode characters are supported 1 4 1 Projects Every Ant build file contains exactly oneproject You set up an Ant project in a build file with the project element which is the document elementi e the element that contains all other elements lt xml version 1 0 gt lt projyect gt lt project gt As Ant build files are just XML you ll need to know which attributes are allowed on the top level project element You ll also want to know about the elements that can be nested withinproject Those are dealt with throughout the rest of this chapter and inChapter 2 The three allowed attributes for the project element are shown in Table 1 1 Table 1 1 The project element s supported attributes downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required name Defines the project name No default
16. echo echo Building the jar file downloaded from lib ommolketab ir downloaded from lib ommotketab ir echo BUILD SUCLCESSFYL Total time 2 seconds The debug options prints out even more informationoften pages of itwhich isn t reproduced here Included in a debugging build is information about classes as they re loaded classes that Ant looked for but couldn t find the locations where Ant is picking up library files and almost everything else you could think of Another useful command line option for displaying information is the projecthelp option which 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 Subtargets and then the Default target is listed Here s the example build file with the addition of adescription attribute for each target element lt xml version 1 0 gt lt project default main gt lt target name main depends compile compress description Main target gt lt echo gt Building the jar file lt echo gt lt target gt lt target name compile description Compilation target gt lt javac srcdir gt lt target gt lt target name compress description Compression target gt lt jar jarfile Project jar basedir includes class gt lt target gt lt project Here s what you d see when running Ant with the projecthelp option Sant
17. in ludeEmetyDirs Specifies if you want to delete empty No directories when using file sets false Deprecated Use a nested fileset element Specifies the patterns All files are includes No matching files to include as a comma included Or Space separated list Deprecated Use a nested fileset element Specifies the name of a file es No where each line is a pattern matching files to include quiet Suppresses most diagnostic messages No Specifies that you want to show the name of each deleted file true false No false The delete task can contain nested fileset elements includesfile verbose Here s something you might not have expected empty directories arenot deleted by default To remove empty directories use the includeEmptyDirs attribute downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 4 2 2 Creating New Directories Want to create the directory structure for local or network deployment Usemkdir This one s so important that you ve seen it in use since Chapter 1 And it s easy to use with only one attribute as you can see in Table 4 10 Table 4 10 The mkdir task s attributes Attribute Description Required dir Specifies the directory you want to create Yes Want to create a directory J ust do It mete dir dis 7S Just realized that you ve asked mkdir to create a directory whose parent directories don t exist That s not a problem sincemkdir
18. javadoc Javadoc execution javadoc javadoc Building tree for all the packages and classes javadoc Building index for all the packages and classes javadoc D anthill work Anthill Example source java example Widget java 12 warning author tag has no arguments javadoc Building index for all classes javadoc Generating D anthill publishDir CVS_Anthill Example api stylesheet css javadoc 1 warning clean delete Deleting directory D anthill work Anthill Example build temp BUILD SULCCESSEUL Total time 15 seconds You schedule builds from the console page http localhost 8080 anthill if you re using Tomcat Click New Schedule in the Schedule box configure the new schedule as shown in Figure 4 5 and click Update update the scheduler Figure 4 5 Setting up a schedule downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Schedule Microsoft Internet Explorer File Edt view Favortes Tools Help Sauk gt O A Qseach Garon mee GG 3 at a Address 2 http hocallost 6050 erd bil Creates heduleSer viet Eao links g Custo schedule Schedule Mame Projects Minutes between builds build interval rel The time this schedule initially starts hh mm Curent serar time 12 27 Pit start time 12 37 All in all Anthill is a great automated build tooleasy to set up easy to use 4 4 4 Cruise Control and Gump Cruise Control and G
19. 11 2 4 Setting Environment Variables You can set the environment variables you want passed to Ant but you have to ensure Ant will run it its own JRE the default In the project s Ant launch configuration click the JRE tab and click the Separate JRE radio button To set environment variables click the Environment tab shown inFigure 11 9 and click the New button to create a new environment variable downloaded from lib ommolketab ir downloaded from lib eommolketab ir Figure 11 9 Setting environment variables I AntEstanvole bariki sml Modify attributes and launch Create a configuration that will run an Ant buidle i append SU i EET pL A G e EATE TETE M ED AGE mative environmen Win Speed Enon When you click the New button the New Environment Variable dialog appears Enter the name and value of the environment variable in the appropriate fields and click OK 11 2 5 Configuring the Ant Editor You can reformat an Ant build file using the Format command Ctrl Shift F from the Ant editor s context menu or by selecting Edit Format To configure how that formatting works open the Ant preferences page with Window Preferences Ant Editor Formatter as shown in Figure 11 10 Any changes you make will be reflected in the Preview box Figure 11 10 Configuring Ant formatting downloaded from lib ommolketab ir downloaded from lib eommotketab ir Preferenc
20. Comp tjevec sredic org antbook gt Larget gt CLarget pahe comprese descr iption Comp jer jarfiles Project jar basedir If you close build xml you can open it again in the Eclipse Ant editor double click it in the Package Explorer This is different than previous versions of Eclipse which had no default Ant editor You had to take extra steps to open Ant build files for editing Support for Ant is evident in Eclipse scode assist also called content assist which was added for Ant build files in Eclipse 3 0 When you enter partial text for Ant elements or attributes you can press Ctrl Space to open code assist which will list possible completions of what you ve been typing as shown in Figure 11 4 Figure 11 4 Using code assist downloaded from lib ommolketab ir downloaded from lib ommolketab ir Daw Iuililand Eclipse Plaihorm Ol File Edt Mavioste Search Project Run Window Help a o as elk hd see Panne st Resource Je lt project default saint gt x iter get pom e main depends compile f EA t Hia an HT Maiami ajm AR w r Z i ry aink bnk H irass java E B JRE System Liteary target buidar target private tanget f Tba ES target public terg t Shar 2 te TAE Get Er tAE gE lt pro ect If you enter a and use code assist Eclipse s Ant editor will list all the Ant property names it knows about Ec
21. The attributes of the compilerarg element appear in Table 3 2 Table 3 2 The compilerarg attributes Attribute Description Required Specifies the required version of the compiler you want to use if compiler the compiler is not of this version the argument won t be passed No to it For possible values see theSection 3 1 3 Exactly one of file Specifies the name of a file as a command line argument value line file Or path downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required Exactly one of line value line file OF path es jos Here s an example that stores the output of the compilation in a directory namedoutput1 4 if the compiler version is 1 3 1 4 1 5 all of which correspond to the modern option see the section Section 3 1 3 for details on specifying the compiler version Specifies a list of command line arguments delimited by spaces Specifies a path like string as a command line argument You can use or aS path separators if you wish Ant will convert them to local path separators Exactly one of value line file Or path Exactly one of value line file Or path Specifies a command line argument lt javac sredir src destdir buila gt lt compilerarg compiler modern value d output1 4 gt lt javac gt Here s an example where the compiler switches to
22. To insert the contents of the shared xml build file into the current build file you can use an XML entity reference sshared like this lt xml version 1 0 gt lt DOCTYPE project lt ENTITY shared SYSTEM file shared xml gt gt lt project default main basedir gt amp shared lt target name init gt lt target gt lt project gt Since Ant 1 6 however there is a new import task that can be used to include build files The referenced files have to be complete Ant build files which are inserted whole minus the XML declaration and lt project gt and lt project gt tags Here s how the above example would work using the import task downloaded from lib ommolketab ir downloaded from lib ommoltketab ir lt x VWereion 1 0 7 gt lt project default main basedir gt lt import file shared xml gt lt target name init gt lt target gt lt project gt The attributes of the import task appear in Table 3 8 Table 3 8 The import task s attributes Attribute Description Required Default file Specifies the name of the build file you want to import Yes Specifies whether you want to stop the build if the build file to import does not exist optional No false Unlike entity includes you can deference a property withs and to set the name of the file to import with the import task In addition if a target with the Same name exists it takes p
23. class gt lt target gt lt project gt If you use this task to delete temporary files created by editors or other software and it doesn t work try setting the defaultexcludes attribute to no You can see the attributes of this task in Table 4 9 The includes includesfile exclude and excludesfile attributes are deprecated and are being replaced by fileset This makes me suspect that other tasks will follow this same pattern Table 4 9 The delete task s attributes downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default ee ee ae Specifies if you want to use default No Default excludes excludes Set to yes no are used Specifies the name of a directory to At least one of file or dir unless a fileset element is specified delete All its files and subdirectories will be deleted os Deprecated Use a fileset element Specifies the patterns matching files to exclude aS a comma or space separated list No files except No default excludes are excluded excludes TRue Deprecated Use a fileset element Specifies the name of a file where each excludesfile No line is a pattern matching files to exclude No E EEEN Specifies if you want an error to stop the build Only used if if quiet iS false At least one of file or file Specifies the file you want to delete dir unless a fileset element is specified
24. data charAt 0 data data substring l1 if data length 0 downloaded from lib ommolketab ir downloaded from lib ommotketab ir data null else data readLine if data null leadChar 1 else data data return read return leadChar You can see how to use this new filter in the build file in Example 12 19 This build file copies all java files in the project comments out each line and stores the result in a directory namedcommented Example 12 19 Build file for the new filter ch12 filter build xml 72m wereio0n 1 0 7 gt lt project basedir default main gt lt property name sre value src gt lt property name output value output gt lt property name commented value commented gt lt target name main depends jar gt lt copy todir commented gt lt fileset dir S srce includes java gt lt filterchain gt lt filterreader classname ProjectFilter classpath Project jar gt lt filterchain gt lt copy gt lt target gt lt target name compile gt lt mkdir dir S ourput gt Anes dar s71 commented T gt lt javac srcdir S srce destdir S output gt lt target gt lt target name jJar depends compile gt lt jar destfile Project jar basedir S output gt lt target gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir pr
25. dist includes readme txt fullpath docs readme txt gt lt zipfileset src examples zip includes html prefix docs examples gt lt 7 21 gt Ant provides an unzip task if you want to decompress ZIP files 4 1 4 Fixing Carriage Returns If you ve ever deployed documentation files from Unix to Windows or Windows to Unix you ve probably run into problems with line endings Lines in Unix text files typically end with a newline n while those in DOS and Windows typically end with a carriage return line feed pair r n To modify text files before deploying them to other operating systems uSefixcrif Like other directory based Ant tasks this task forms an implicit FileSet and supports all attributes offileset dir becomes srcdir aS well as the nested include exclude and patternset elements Say for example that you wanted to convert the end of line characters in Unix shell scripts sh to be uploaded from Windows to a Unix server to a linefeed and remove any DOS style end of file EOF characters z You could do that like this lt Tfixcrils srodir Ipro eol L1r eof remove downloaded from lib ommolketab ir downloaded from lib ommoltketab ir includes sh i gt Here s how you might go the other way replacing all end of line EOL characters with a cr If pair in DOS batch bat files in preparation to downloading them to Windows five lt srodir araj eol crlft eof add incl
26. downloaded from lib eommolketab ir 0 ae To add additional assembly descriptor info here add a file to your XDoclet merge directory called assembly descriptor xml that contains the lt assembly descriptor gt lt assembly descriptor gt markup gt lt security role gt lt role name gt App lt role name gt lt security role gt lt security role gt lt role name gt Administrator lt role name gt lt security role gt lt method permission gt lt role name gt App lt role name gt lt role name gt Administrator lt role name gt lt method gt lt ejb name gt App lt ejb name gt lt method name gt lt method name gt lt method gt lt method permission gt lt i Lransecclons gt lt container transaction gt lt method gt lt ejb name gt App lt ejb name gt lt method name gt lt method name gt lt method gt lt trans attribute gt Required lt trans attribute gt lt container transaction gt lt container transaction gt lt method gt lt ejb name gt App lt ejb name gt lt method intf gt LocalHome lt method intf gt lt method name gt remove lt method name gt lt method params gt lt method params gt lt method gt lt trans attribute gt Mandatory lt trans attribute gt lt container transaction gt lt container transaction gt lt method gt lt ejb name gt App lt ejb name gt lt method intf gt Home lt method intf gt lt method name gt remove lt method name gt lt m
27. downloaded from lib ommoltketab ir Ant The Definitive Guide 2nd Edition By Steve Holzner Publisher O Reilly Pub Date April 2005 ISBN 0 596 00609 8 Pages 334 Table of Contents Index Errata Overview As the most widely used tool for cross platform development Ant has undergone a number of important changes in its functionality and use since its launch Ant The Definitive Guide 2nd Edition has been reworked to reflect these changes for Java developers everywhere Topics covered include everything from downloading and installing to using Ant to build Web applications to using Ant to test code downloaded from lib ommolketab ir downloaded from lib eommolketab ir Ant The Definitive Guide 2nd Edition By Steve Holzner Publisher O Reilly Pub Date April 2005 ISBN 0 596 00609 8 Pages 334 Table of Contents Index Errata Copyright Preface What s Inside Conventions Used in This Book What You ll Need Using Code Examples We d Like to Hear from You Chapter 1 Getting Started Section 1 1 Ant s Origins Section 1 2 Getting Ant Section 1 3 Ant at Work Section 1 4 Anatomy ofa Build File Section 1 5 Running Ant Chapter 2 Using Properties and Types Section 2 1 Using Properties to Control Tasks Section 2 2 Using Property Files Section 2 3 Handling Data Using Types Chapter 3 Building Java Code Section 3 1 Compiling Code Section 3 2 Getting Inpu
28. gt This example copies an entire directory to a new location lt copy todir backup gt lt fileset dir S src gt a7 Sopy This copies a set of files to a new directory lt copy todir backup gt lt fileset dir src gt lt include name Jjava gt lt fileset gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir sJ copy Want to copy files and change their names Use amapper element like this lt copy todir backup gt lt fileset dir src gt lt mapper type glob from to old gt lt copy gt Here s how to copy a set of files to a directory replacing Topoe with Done in all copied files lt copy todir backup gt lt fileset dir src gt lt filter set gt lt filter token TOD0 salue DONE 7 gt lt filter set gt lt 1 6opy gt In Unix file permissions are not retained when files are copied files end up with the default umask permissions instead If you need a permission preserving copy function use the system copy utilitiessee theexec task in Chapter 7 you d use lt exec executable cp gt here Or use the chmod task coming up in this chapter after the copy Example 4 3 uses copy to copy a documentation file to make sure it s included in the final JAR for a project and then deploys the J AR file to a directory nameduser Example 4 3 Using the copy task ch04 copy build xml lt 7xml1 vereicn 1 0 Fe
29. lt echo gt lt target gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt target name init gt lt mkdir dir Siourpul gt lt target gt lt target name compile gt lt exec dir executable bin cpp exe failonerror true gt lt erq 1ine 6 farc Cpo o output 72 lt exec gt lt target gt lt project gt You can use this task to run any general program Here s an example that will launch the Internet Explorer in Windows assuming a default installation of that browser and open theexec task s documentation page lt xml version 1 0 7 gt lt project default main gt lt property name browser location C Program Files Internet Explorer iexplore exe gt lt property name file location S ant home docs manual coretasks exec html gt lt target name main gt lt exec executable S browser spawn true gt lt arg value S file gt lt exec gt lt target gt lt project This example starts emacs on X Window s display 1 lt xml version 1 0 gt lt project default main gt lt target name main gt lt exec executable usr bin emacs gt lt env key DISPLAY value 1 0 gt lt exec gt lt target gt lt project gt 7 2 2 Targeting Operating Systems The exec task depends on a specific operating system If you want your build file to work on multiple platforms use the os attribute to specify which exec
30. lt Laroe Tieme Compress gt lt jar destfile S output Project jar basedir output includes class gt lt target gt lt target name deploy gt lt move todir S1dist gt lt fileset dir S output gt lt exclude name java gt lt exclude name class gt lt fileset gt lt move gt lt target gt lt project For more examples look at the section Deploying By Copying downloaded from lib ommolketab ir downloaded from lib ommotketab ir 4 3 3 Deploying Remotely Using FTP The ftp task is handy for remote deployment This task can send receive list delete files and create directories This is one of Ant s optional tasks so you ll need two JAR files which you place in the Ant lib directory jakarta oro jar available from http jakarta apache org oro and commons net jar available from http jakarta apache org commons net index html If you want to use this task with MS FTP servers you need a version of commons net jar and jakarta oro jar released after 02 01 2004 or a release of commons net jar after 1 1 0 and jakarta oro jar after 2 0 8 Here s an example that deploys the results of a build to the directory cgi bin on a remote server Since it s a bad idea to hardcode the username and password in build files I ll set those as properties on the command line you can use the input task here using the properties name and password sant Dname Steve Dpass
31. lt lastname gt Gable lt lastname gt lt firstname gt Clark lt firstname gt lt name gt lt hiredate gt October 25 2005 lt hiredate gt lt projects gt lt projyect gt lt product gt Keyboard lt product gt lt i gt RI lt price gt 129 00 lt price gt lt projyect gt lt project gt lt product gt Mouse lt product gt lt 10 gt 660 lt 10 gt lt price gt s25 00 lt price gt oro 7ecr lt projecto lt employee gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt document gt And here are the results Sant Buildfile build xml main xmlvalidate 1 file s have been successfully validated BUILD SUCCESSFUL Total time Q seconds downloaded from lib ommolketab ir downloaded from lib ommotketab ir 9 2 Loading Properties from XML Files The xmlproperty task loads property values from a well formed XML file The way you structure the XML document determines the names of the properties it creates Say you have this XML document properties xml that defines a property named namel and two nested properties firstName and lastName creating the properties namel firstName and namel lastName lt namel language english gt lt firstName language german gt Stefan lt firstName gt lt lastName gt Edwards lt lastName gt lt namel gt You can load these properties into a build with thexmlproperty task as shown in Example 9 3 This build file disp
32. 1 fy K L M N O P Q R S CO U V W RX Z q option quiet attribute cvs task cvstagdiff task delete task patch task quiet option 2nd downloaded from lib ommolketab ir downloaded from libeommolketab ir Index A B C D E F G H H J K L M N O P Q R S O U V W RX 2 rannotate command CVS rdiff command CVS 2nd 3rd read element telnet task readbuffersize attribute checksum task reallyquiet attribute cvs task rebuild attribute weblogic element reconfigure method Task class record task reference element 2nd 3rd refid attribute FilterSet type property element reference element xmicatalog element regexp element regexp mapper 2nd 3rd regular expressions from attribute and mappers and 2nd substituting text relative attribute apply task release command CVS reload task 2nd reloading attribute junit task reloadstylesheet attribute xslt style task remotedir attribute ftp task 2nd remotefacade element ejbdoclet task remoteinterface element ejbdoclet task remove command CVS rename task renameextensions task replace attribute replaceregexp task replace task 2nd replaceProperties method Project class 2nd replaceregexp task 2nd replacetokens element FilterChain type replyto attribute mail task replyto element mail task report element reports brief formatter change logs cvstagdiff task and
33. Ant sets you can create a set of properties and refer to them all at once by ID This element can contain propertyref mapper and other propertyset elements Example 3 2 iS an antcall example In this case the example calls a new target displayMessage to display some text The example passes the text to display as a parameter namedmsg Example 3 2 Using antcall ch03 antcall build xml lt xml vercion LUT gt lt project default main gt lt property name message value Building the jar file gt lt property name sre location source gt lt property name output location bin gt lt target name main depends init compile compress gt lt antcall target displayMessage gt lt param name msg value message gt lt antcall gt lt target gt lt target name displayMessage gt lt echo message msg s msg gt lt target gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt target name init gt lt mkdir dir S7ouLpuLy 7 gt lt target gt lt target name compile gt lt javac srcdir S sre destdir S output gt lt target gt Larger name compress gt lt jar destfile S output Project jar basedir output includes class gt lt target gt lt pra ect Here s what you see when you run Ant using this build file themsg parameter was passed to the called target Ce ant chnoo anteal 1 Sant Bulldfile bui
34. BUILD SUCCESSFUL Total time 3 seconds downloaded from lib ommolketab ir downloaded from lib ommoltketab ir downloaded from lib ommolketab ir downloaded from lib ommotketab ir 12 5 Creating Custom Filters You can implement custom Ant filters To do that you can extend Ant classes like org apache tools ant filters BaseParamFilterReader If you want your filter to be chainable impleme the org apache tools ant filters ChainableReader Interface Example 12 18 shows how to write a filter In this example the code reads each line of a Java file using the read method and adds a Java single line comment at the beginning of each line When the code reaches the end of the file it returns a value of 1 to quit Example 12 18 A new filter ch12 filter src ProjectFilter java import java io Reader import jaVa 10 1TORXxCepLion import org apache tools ant filters ChainableReader import org apache tools ant filters BaseParamFilterReader public final class ProjectFilter extends BaseParamFilterReader implements ChainableReade otring data full public ProjectFilter super public ProjectFilter final Reader reader super reader public final Reader chain final Reader reader Pro e0Lrilvler filter few Pro jecitr ver reader filter setInitialized true return filter public final int read throws IOException int leadChar 1 if data null leadChar
35. Constant width Indicates commands options switches variables types classes namespaces methods modules properties parameters values objects events event handlers or XML tags Constant width italic Shows text that should be replaced with user supplied values Constant width bold This icon signifies a tip suggestion or general note This icon signifies a caution or warning downloaded from lib ommolketab ir downloaded from lib ommoltketab ir What You ll Need All the software you ll need in this book can be downloaded from the Internet for free You ll need Antthis book was written using Ant 1 6 1land I ll discuss where to get Ant in Chapter 1 Other softwar packages are used at various points in the book such as the AntHill build server or the Eclipse IDE Chapter 11 is on using Ant in Eclipse and I ll show where to download all the requisite software as it s needed It s all free downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Using Code Examples This book is here to help you get your job done In general you may use the code in this book in your programs and documentation You do not need to contact O Reilly for permission unless you re reproducing a significant portion of the code For example writing a program that uses several chunks of code from this book does not require permission Selling or distributing a CD ROM of examples from O Reilly books does requ
36. Example 12 5 shows the code to handle a String attribute named language and displays the value assig to this attribute in the build file ThesetLanguage method will be passed the attribute s value Example 12 5 Accessing attributes ch12 attributetask src Project java import org apache tools ant Task import org apache tools ant BuildException public class Project extends Task private String language public void execute throws BuildException Ssystem out printin The language is language public void setLanguage String language this language language The build file that builds the custom task in Example 12 5 and then uses it appears in Example 12 6 In t example Ant builds the code for the new task project and uses that task setting the language attribut to English The code for this task reads the value of thelanguage attribute and displays it during the bt Example 12 6 Build file for accessing attributes ch12 attributetask build xml lt 7eml wersion 1 0 gt lt project basedir default main gt lt property name src value src gt lt property name output value output gt lt target name main depends jar gt lt taskdef name project classname Project classpath Project jar gt lt project language English gt lt target gt lt target name compile gt nhs cira s oucput gt lt javac srcdir S srce destdir S output gt lt tar
37. Here s an example using ant where I m setting the value of a property named parameter and loading properties from a file lt ant antfile subproject subbuild xml gt lt property name parameter value 4096 gt lt property file config subproject build properties gt lt fant gt You can see the attributes of this task inTable 3 6 Table 3 6 The ant task s attributes Attribute Description Required Default eee Specifies the build file where No paid xil the target to call is The current project S basedir unless dir inheritall has been set to false in sasaaa which case there is no default value If true makes the task pass all inheritRefs current references to the new No false Ant project No No Directory where the build file is No If true makes the task pass all current properties to the new Ant project No true PS Specifies the filename where i the task should write output Specifies the target in the Ant ae taret project that you want to call The new project s default target If you don t specify a value for the ant file attribute the file build xml in the directory given by the dir attribute is used If no target attribute is supplied the default target of the new project will be used Passing properties to the new project works as it does with theantcall task except that here you use nested property elements instead of param elements to pass properties You can use
38. JVM accessing system properties Eclipse and forking 2nd mixed environments and passing environment variables to jvm attribute java task junit task jvmarg element arguments and generic element and jonas element and nesting and jvmargs attribute java task downloaded from lib ommolketab ir downloaded from lib ommoltketab ir weblogic element jvmdebuglevel attribute weblogic element ijWebUnit downloaded from lib ommolketab ir downloaded from lib ommotketab ir Index A B C D E F G H 1 J K L M N O P Q R S M U V W X Z k option keep going option keepcompression attribute ear task jar task war task zip task keepgenerated attribute weblogic element keepgeneric attribute weblogic element keepRoot attribute xmlproperty task key attribute env element system properties and keyfile attribute scp task sshexec task knownhosts attribute scp task sshexec task knownhosts file downloaded from lib ommolketab ir downloaded from libeommolketab ir Index A B C D E F G H H Y K L M N O P Q R S O U V W BX 2 option 2nd language attribute script task lenient attribute xmlvalidate task lib directory Ant 2nd lib element war task lib option 2nd libcabinet tool line attribute argument element compilearg element line feed carriage return linecontains elem
39. Required Default Specifies the the name of a property you want to Nave set if No there is an error Specifies the name of a property in B a aka case the task fails me Ee ne Removes J unit and Ant stack No a frames from error stack traces Specifies you want to run tests ina fork new JVM EPEE Specifies you want to stop the build if there are errors Specifies you want to stop the naltonfailure build if the test fails Specifies this test should run only UER a specified property is set Specifies the name of the test class rame you want to use eSrrorproperty TEST name Where name is the No name of the test specified in the name attribute Sets the filename where the test results should go outfile downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Attribute Description Required Default ee Specifies the directory you want The current directory the reports written to Specifies this test should run only It a specified property is not set unless 5 1 2 3 Running tests in batches Another nested element batchtest lets you set up a number of tests at once Thebatchtest element collects the included files from any number of nested filesets and generates a test class name for each file that ends in java or class You ll use this element later in this chapter The attributes for batchtest appear in Table 5 6 Table 5 6 The batchtest element s attribute
40. Specifies the args No arguments for the class that you want to run classname Specifies the Java class you want to run One OPE ie jar Or classname EEN Specifies the classpath you want to use when the class No 2a oar Specifies the classpath you want to use as a No reference when the class Is run dix Specifies the directory where you want to run J ava L Specifies the file where standard error output should CELECOE be stored E EE E Specifies the name of a property where you want to store errors EE OECO Specifies the build should be stopped if the task Mo PE encounters errors forks o Specifies you want to run the class in a forked JVM you want to run the class in a forked J VM Sects You wart anhe esa ote e false Specifies the file where the task should take input to Lp run the class with Specifies a string holding the input stream for the class to run F Specifies the location of the jar file to run The jar file aren must have a Main Class entry in the manifest eh Cre ee pa Specifies the command used to start J ava x E java EE Deprecated Use nested jvmarg elements Specifies a a leres to pass to the forked Java Virtual Machine flogkrror Specifies you want to send error output to Ant s log you want to send error output to Ant s log araumen pass te e Prea jana Wa Meene EENEI Specifies the maximum amount of memory you want No i to give a forked J VM Specifies old environment variables should not be
41. Table 4 13 The telnet task s attributes Attribute Values Required e e Default ETE PETA Specifies that you want to send a carriage return after connecting to the server Specifies the login password you want to use on the Yes if userid IS password Telnet server e port Specifies the port on the Telnet server to use Specifies the address of the remote Telnet server you Server want to use Specifies a default timeout for Telnet actions in No timeout seconds timeout Specifies the username to use to log into the Telnet Yes if password IS userid ve server Specified 4 3 5 Deploying Remotely Using SSH The more secure SSH protocol is replacing Telnet in general use and Ant 1 6 added thesshexec task to execute SSH commands on a remote system This is an optional task so you ll needjsch jar which you can get at http www jcraft com jsch index html in the Ant lib directory Here s an example that runs a command touch on a remote machine using sshexec lt sshexec host 000 000 000 000 username S name password S password command touch index html gt You can find the attributes of this task inTable 4 14 See the scp task for copying files for deployment to web servers using SSH in Chapter 8 downloaded from lib ommolketab ir downloaded from lib ommolketab ir Table 4 14 The sshexec task s attributes Attribute Description Required Default Specifies if you want t
42. The build file was written for a later version of Ant Fix upgrade to at least the latest release version of Ant The task is not an Ant core or optional task and needs to be declared using lt taskdef gt Remember that for JAR files to be visible to Ant tasks implemented in ANT_HOME 1l1ib the files must be in the same directory or on the classpath Please neither file bug reports on this problem nor email the Ant mailing lists until all of these causes have been explored as this is not an Ant bug Total time 0 seconds Sometimes errors won t stop a build and you may want to change that behavior so the build will terminate when there s been any kind of problem Most tasks have afailonerror attribute which is set to false by default Setting this attribute s value to true makes the build fail if the task encounters an error allowing you to stop a build if a specific task generates errors downloaded from lib ommolketab ir downloaded from lib ommotketab ir Keep in mind that this won t affect your build in the case where you ve previously executed the build and your output files are up to date By default Ant tasks check to see if the output files they re Supposed to create are current i e the output file is more recent than the files used to create it if they are Ant tasks won t recreate them because Ant considers the target executed For example here s what you d see when you run the example build file a second timeA
43. The target to invoke if no target is explicitly specified Yes basedix The base directory from which all relative paths are resolved No Note that the default attribute is required This attribute points to the Ant target that you want run by default in other words this controls what happens when you typeant at the command prompt without any other special instructions In the following case the default target iSmain lt xml version 1 0 gt lt project default main gt lt project gt 1 4 2 Targets An Ant target is a group of tasks that you want Ant to perform These tasks are grouped together into one easily remembered unit which is the target For example you might have a target deploy which opens an FTP connection to a remote server uploads various files and closes the connection Though multiple tasks may be involved opening the connection performing an upload closing the connection and perhaps checking for error messages it s easiest to think of this as one unit of work Considering this as a single target makes it reusable and easily accessed from various portions of your build file Another example might be a target named init that initializes a build by deleting output directories and recreating them so they ll be empty as well as copying over license files that should be a part of every build You might use a target named compile to compile dozens of source files across various directories and store the
44. Yes ETE Specifies what to do if a duplicate file is found No ads Valid values are add preserve and fail downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required Default Specifies the character encoding to use for eens filenames in the EAR file we Specifies the patterns matching files to exclude excludes No aS a comma or Space separated list Specifies the name of a file where each line is a excludesfile Saas lesan matching files to exclude filesonly Specifies you want to store only file entries Seca fe false Specifies the patterns matching files to include includes as a comma or space separated list Specifies the name of a file where each line is a pattern matching files to include includesfile Preserves the compression as it has been in keepcompression archives you re compressing instead of using the No compress attribute Available since Ant 1 6 Specifies the manifest file to use in the manifest No compressed file Specifies whether you want to update or d oe Ge ral se overwrite the target file if it exists me 259 The extended zipfileset element from the zip task which supports the attributes prefix fullpath and src is available in the ear task The nested metainf element specifies a fileset all files included in this fileset will end up in themeTa 1NF directory of the ear file This task lets you specify where to getapplic
45. checking out compiling patches to source control See CVS source release Ant sourcetiles attribute javadoc task SourceOffsite SourceGear sourceoffsite task sourcepath attribute javac task 2nd 3rd javadoc task path type sourcepath element sourcepathref attribute javac task javadoc task spaces 2nd 3rd downloaded from lib ommolketab ir downloaded from lib eommolketab ir spawn attribute apply task exec task java task splash screens 2nd 3rd splash task 2nd 3rd splitindex attribute javadoc task sql task SQLUnit src attribute get task gzip bzip2 tasks message element script task unjar task zipfileset element 2nd src element srcdir attribute depend task ejbjar task fixcrif task javac task 2nd 3rd ispc task path type srcfile attribute example loadfile task purpose update task srcfile element SSH protocol 2nd 3rd sshexec task 2nd 3rd ssl attribute mail task start attribute cvschangelog task startdate attribute cvstagdiff task StarTeam 2nd starteam task starttag attribute cvstagdift task status command CVS STCheckin task STCheckout task STLabel task STList task stripjavacomments element FilterChain type 2nd striplinebreaks element FilterChain type striplinecomments element FilterChain type 2nd strutsconfigxml element webdoclet task strutsform element ejbdoclet task strutsvalidationxml element webdoclet task style attribute xslt style
46. edit command CVS editors command CVS EJB Enterprise JavaBean Ant tasks for deploying to containers developing working with containers ejbc task EJB 2nd ejbcclass attribute weblogic element ejoClassNameSuffix attribute ejbdoclet task ejbdoclet task XDoclet 2nd ejbjar task EJB 2nd 3rd ejbSpec attribute ejbdoclet task elements nesting 2nd 3rd emacs option email remote deployment enablemultiolemappings attribute copy task encoding attribute copy task ear task fixcrif task jar task javac task javadoc task loadfile task mail task downloaded from lib ommolketab ir downloaded from lib eommolketab ir manifest task replaceregexp task war task zip task end attribute cvschangelog task end of line EOL characters enddate attribute cvstagdiff task endtag attribute cvstagdift task endtoken attribute FilterSet type Enterprise JavaBean See EJB entityomp element ejbdoclet task entityemp element ejbdoclet task entityfacade element ejbdoclet task entityok element ejbdoclet task env element 2nd 3rd 4th environment attribute property element 2nd 3rd environment variables customizing env element and 2nd forked JVM and JDK and Setting setting properties using 2nd 3rd eof attribute fixcrif task EOL end of line characters eol attribute fixcrlf task equals element condition task error attribute apply task cvs task exec task java task errorprope
47. if you want to check the src directory for java files as in the previous example and any subdirectory of src you could set includes to java Doing so would match the java files in the src directory and in any subdirectories of src Here s how that might look lt uptodate property Do Not Build targetfile classes jar gt lt srcfiles dir src includes java gt lt uptodate gt Here s an example checking against a single source file using thesrcfile attribute lt uptodate property Do Not Build targetfile classes jar gt lt srcfile includes usr local bin classes java gt lt uptodate gt You can see attributes for the uptodate task in Table 2 5 Table 2 5 The uptodate task s attributes Attribute Attribute Description 7 Required Default Peers The name of the property to set with the S results of this task OR EEA The value you want to set the property to NO bene if the target is current The file you want to check against the Yes unless a nested srcfiles srcfile target file s element is present The file you want to check for current Yes unless a nested mapper targetfile Status element is present downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 2 2 Using Property Files In larger build files you might be working with dozens of properties and storing them in property files common Setting tens or hundreds of properties all wi
48. lib ommotketab ir If you don t want to have to check dependencies you can wipe all the directories that contain compiled code and rebuild from scratch When there are a large number of files to compile that s a less attractive option and using the depend task can save significant time But experience shows that if your dependencies are complex it can save time to do a wipe and start fresh Table 10 4 The depend attributes Attribute Description Required Default Specifies the directory where you want the task to store cache No dependency data Specifies the classpath which should also be checked when classpath No checking dependencies o Specifies the task should traverse all class dependencies No ee deleting all classes that depend on out of date material TF 7 a Specifies the root directory containing the class files that you No The value of want to check sredir Specifies the dependency information should be sent to the dump No debug log sredir Specifies the directory where the source is Yes Like many other Ant tasks this task forms an implicit FileSet and so supports all attributes offileset though dir becomes srcdir as well as the nested include exclude and patternset elements The depend task s classpath attribute is a path like structure and can also be set using a nestedclasspath element If you specify a classpath depend will include classes and JARs on the classpath for dependency ch
49. linecontains gt The linecontainsregexp filter reader includes only those lines that match the regular expression you ve specified For example here s how to match only lines that contain lowercase letters lt linecontainsregexp gt lt regexp pattern a z S gt lt linecontainsregexp gt The stripjavacomments filter reader strips away comments from the data using Java syntax guidelines Here s an example lt loadfile srcfile S srce file property jJava text gt lt filterchain gt lt stripjavacomments gt lt filterchain gt lt loadfile gt The striplinecomments filter reader removes all those lines that begin with strings that represent comments as specified by the user For example here s how to remove all lines that begin with REM rem and lt striplinecomments gt lt comment value gt lt comment value REM gt lt comment value rem gt lt comment value gt lt striplinecomments gt The tabstospaces filter reader replaces tabs with spaces here s an example downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt loadfile srcfile S srce file property src file detabbed gt lt filterchain gt lt tabstospaces gt lt filterchain gt lt loadfile gt The classconstants filter readers recovers constants defined in Java class files For example say that you have a constant named MAXFILES public interface Files public static final
50. lt javac gt lt target gt lt target name main depends compile gt lt echo gt Using EJBDoclet lt echo gt lt target gt lt project gt Running this build file creates EJB interface code and a deployment descriptor ejb jar xml Here is the relevant part of the generated ejb jar xml lt xml version 1 0 encoding UTF 8 gt lt DOCTYPE ejb jar PUBLIC Sun Microsystems Inc DID Enterprise JavaBeans 2 0 EN httpi Jara s n com dtd esJb Jar 2 Osdtd gt lt ejb jar gt lt description gt lt CDATA ejbbean gt lt description gt lt display name gt Generated by XDoclet lt display name gt lt enterprise beans gt lt Session Beans gt lt session gt lt description gt lt CDATA App example bean gt lt description gt lt ejb name gt App lt ejb name gt lt home gt app web AppHome lt home gt lt remote gt app web App lt remote gt lt local home gt app web AppLocalHome lt local home gt lt local gt app web AppLocal lt local gt lt ejb class gt app web AppSession lt ejb class gt lt session type gt Stateless lt session type gt lt transaction type gt Container lt transaction type gt lt security role ref gt lt role name gt admin lt role name gt lt role link gt Administrator lt role lLink gt lt security role ref gt lt secei on lt Assembly Descriptor gt lt assembly descriptor gt downloaded from lib ommolketab ir
51. lt target gt lt project downloaded from lib ommolketab ir downloaded from lib ommotketab ir This attempts to override the property with a new definition Once you define a property in a build file behaves much like a constantie you can t redefine it inside the build file So when you run Ant using this build file you ll see the first version of the property Lait mkdir Created dir home steve ch02 properties bin compile javac Compiling 1 source file to home steve ch02 properties bin compress jar Building jar home steve ch02 properties bin Project jar main echo echo Building the jar file echo BUILD SUCCESSFUL Total time 3 seconds When Ant sees a property defined whether in a build or a property file it considers that property defined You can t change it Except in one way Of course Who wants a language without exceptions If you want to override a property in a build file you can set properties on the command line That 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 set in the build file the value specified on the command line will override the value specified in the build file Here s how to do that sant Dmessage Compiling and compressing Bouitdri de HP ild xml Linit mkdir Created dir home steve ch02 properties bin compile javac Compiling
52. lt mkdir dir S jars gt lt target gt lt target name compile gt lt javac srcdir S sre destdir S output gt lt target gt lt target name test depends testl test2 test3 test4 test5 gt lt echo gt S testsOK lt echo gt lt target gt lt TENTO GO HERE gt lt target name compress gt lt jar destfile S jars Project jar basedir S output gt lt include name class gt lt jar gt lt target gt lt target name deploy gt lt delete dir S dist gt sm air dir idisti gt lt copy todir o dist gt lt fileset dir S jars gt lt include name 7ar gt lt fileset gt lt j Cooy gt lt target gt pre eae downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 5 1 Using JUnit J Unit is an open source testing framework housed online athttp www junit org where you ll find downloads and documentation Using J Unit you can construct a set of standard tests for everyone working on an application and if they change the application s code all they ll need is to run the buil file to verify that the application still passes the standard set of tests J Unit is primarily made up of a set of assertion methods that can test various conditions Here they are assertEquals a b Tests if a is equal to b a and b are primitive values or must have an equals method for comparison purposes assertFalse a Tests i
53. printlni No worries You can create Javadoc for the project using the javadoc task in a new target l Il name doc which will put the generated Javadoc in a doc directory as you see in Example 3 3 Note the XML lt cDATA gt sections which the build file uses to pass data to the javadoc tool Example 3 3 Creating javadoc ch0O3 javadoc build xml lt xml version 1 0 gt lt project default main gt lt property name message value Building the jar file gt lt property name sre location source gt lt property name docs location docs gt lt property name output location bin gt lt target name main depends init compile doc compress gt lt echo gt S message lt echo gt lt target gt lt target name init gt downloaded from lib ommolketab ir downloaded from lib eommolketab ir lt mkdir dir output 7S lt m alr dir coca J gt lt target gt lt target name compile gt lt javac srcdir S src destdir S output gt lt target gt lt target name doc gt lt javadoc sourcefiles S src Project java destdir docs author true version true use true windowtitle Project API gt lt doctitle gt lt CDATA lt h1 gt Project API lt h1 gt gt lt doctitle gt lt bottom gt lt CDATA xi gt Cop right 67169 2005 lt 1 gt l gt x lt bottomn gt lt 7 Javadoc lt target gt lt target name compress gt
54. At least one fileset Or filelist IS required false EEL YE a false true HT ET tt You can use One mapper element to specify the target files relative to thedest attribute for dependency checking as l Il do below Command line arguments can be passed witharg elements as with the exec task and you can use nested env elements How does Ant pass the names of files to the external program By default the file names of the source files are added to the end of the command line If you want to insert the names of files in a different place use a nested srcfile element between nested arg elements Nested target file elements are similar to srcfile elements except they mark the position of the target filename on the command line You can only use atargetfile element if you define a nested mapper and thedest attribute downloaded from lib ommolketab ir downloaded from lib ommotketab ir downloaded from lib ommolketab ir downloaded from lib ommotketab ir 7 4 Multithreading Tasks The parallel task can contain other Ant tasks and execute each nested task in its own thread While the tasks within the parallel task are being run the main thread will be blocked waiting for all the child threads to complete This task is useful to speed up build file processing and to launch external tasks that may depend on each other you may want to launch a server and run tests on build output for example The attrib
55. Builds Every Ant developer has builds that fail for one reason or another Ant does its best to pinpoint the problem For example say you misspelled the name of the javac task lt xml version 1 0 gt lt project default main gt lt target name main depends compile compress gt lt echo gt Building the jar file lt echo gt lt target gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt target name compile gt lt jjavac srcedir gt lt target gt Ant will diagnose this problem when it runs and give you some feedback cant build xml 10 Could not create task or type of type jJjavac Ant could not find the task or a class this task relies upon This 1S common and has a number of causes the usual solutions are to read the manual pages then download and install needed JAR files or fix the build file You have misspelt Jjjavac Fix check your spelling The task needs an external JAR file to execute and this is not found at the right place in the classpath Fix check the documentation for dependencies Fix declare the task The task is an Ant optional task and optional jar is absent Fix look for optional jar in ANT_HOME 1ib download if needed The task was not built into optional jar as dependent libraries were not found at build time Fix look in the JAR to verify then rebuild with the needed libraries or download a release version from apache org
56. CDATA IMPLIED gt lt ELEMENT target tasks stypes gt lt ATTLIST target id ID IMPLIED name CDATA REQUIRED if CDATA IMPLIED unless CDATA IMPLIED depends CDATA IMPLIED description CDATA IMPLIED gt lt ELEMENT patternset include patternset exclude excludesfile includesfile gt lt ATTLIST patternset id ID IMPLIED includes CDATA IMPLIED refid IDREF IMPLIED downloaded from lib ommolketab ir downloaded from lib ommolketab ir description CDATA IMPLIED excludesfile CDATA IMPLIED includesfile CDATA IMPLIED excludes CDATA IMPLIED gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir 9 4 Transforming XML Using XSLT The xslt task also called the style task the two names are interchangeable in Ant can process a set of documents via XSLT This is handy for building nicely formatted views of XML based documentation in other formats like HTML or for generating code How do you use this task to perform XSLT transformations Example 9 5 shows a build file that puts it to work transforming style xml into style html using style xsl Example 9 5 Using the xslIt style task ch09 xsIt build xml lt xml version 1 0 encoding UTF 8 gt lt project default main gt lt target name main gt lt xslt basedir destdir extension html includes style xml style style xsl gt lt target gt lt project gt Here s style xm
57. J compiler ildasm Disassembles from NET intermediate language back to source code ilasm Assembles code into NET intermediate language wsdl ToDotNet Given a WSDL file this task will generate C or VB code ineereTypelis COM library importer downloaded from lib ommolketab ir downloaded from fib ommolketab ir Specific tasks for the Clearcase version control system are listed inTable 1 6 Table 1 6 Clearcase Ant tasks Task name Description CeCheckin a Checks in files CCCheckout Checks out files CCUnCheckout Un checks out files CCUpdate Executes cleartool CCMklbType Executes cleartool mklbtyle CCMklabel Executes cleartool mklabel CCRmt ype Executes cleartool rmtype Cu Lock Executes cleartool CeUniek Executes cleartool unlock CCMkbl1 Executes cleartool CCMkattr Executes cleartool mkattr CCMkdir Executes cleartool CCMkelem Executes cleartool mkelem Many EJB specific tasks are shown in Table 1 7 Table 1 7 EJ B related Ant tasks downloaded from lib ommolketab ir downloaded from lib ommolketab ir Task name name eseription blgenclient Generates a client JAR for Borland application servers daoreator Creates EJB deployment descriptors given a group of WebLogic deployment descriptors ejbc Invokes WebLogic s ejbc tool i lanet ejb ee Se Invokes iPlanet s ejbc tool b PA Invokes the ejbjar tool used for many a
58. String MAXFILES 4 To load the MAXFILES constant and make it accessible by name you can use the Loadproperties task and the classconstants filter reader lt loadproperties srcfile Files class gt lt filterchain gt lt classconstants gt lt filterchain gt lt loadproperties gt As you can gather from the name you can use multiple filter readers in a filter chain and we ll add the prefixlines filter reader to prefix constants we recover with the text Files lt loadproperties srcfile Files class gt lt filterchain gt classconstancs gt lt prefixlines prefix Files gt lt filterchain gt lt loadproperties gt Now you ve recovered the constant Files MAXFILES from a compiled class file and can display it with echo lt echo gt o Files MAxXFILES lt echo gt 2 3 9 Transforming One Set of Files to Another with Mappers Mappers are another Ant type and they re used to map one set of files to another For example one of the mappers available in Ant is the regexp mapper that lets you grab a set of files and rename them You can use mappers in copy move apply uptodate and a number of additional tasks downloaded from lib ommolketab ir downloaded from lib ommotketab ir Here s an example where I m copying a file set from a directory nameddevelopment to a directory named backup renaming java files to backup files This works because whatever matches to the expression inside the p
59. Windows at command schedules commands to run in Windows at specific times For example say y a batch file dobuild bat which runs your nightly build set ANT_HOME C ant apache ant 1 6 1 set JAVA_HOME C jdk1 4 set PATH PATHS SANT_HOME bin ed Ce work call SANT_HOMES bin ant bat f nightlybuild xml You can schedule that build for every night with the Windowsat command downloaded from lib ommolketab ir downloaded from lib ommotketab ir C ant gt at 00 01 every M T W Th F C work dobuild bat Added a new job with job ID 1 To list scheduled at jobs enter at C ant gt at Status ID Day Time Command Line 1 Each M T W Th F 12 01 AM C work dobuild bat Want to get the results of your nightly build emailed to you Use the Ant mail logger covered earlier in this chapter The crontab and at commands are basic ways to get your builds to run automatically but they re still be There are more advanced and powerful tools available 4 4 3 Anthill In my opinion Anthill is the easist of the automatic build tools to use as well as the easiest to install It software build management server that can handle most of your build needs from individual up to the corporate The web site is http www urbancode com default jsp and this is how Anthill describes itsel Anthill ensures a controlled build process and promotes the sharing of knowledge within an organiz Anthill performs a checkout from the source repository o
60. a new file or a new directory or it moves sets of files to a new directory The attributes and nested elements are the same as forcopy see Table 4 11 and related sections By default the destination file is overwritten if it already exists When overwrite IS turned off files are only moved if the source file is newer than the destination file or when the destination file does not exist Here s an example that moves a single file the net result is that the file is renamed lt move tile file ext Lorile 1le backip gt Here s how to move a directory to a new directory lt move todir Ssource gt lt fileset dire backup gt lt move gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir Example 4 4 uses move to deploy the files it creates Example 4 4 Moving a file ch04 move build xml lt xml version 1 0 gt lt project default main gt lt property name message value Deploying the jar file gt lt property name src location source gt lt property name output location bin gt lt property name dist location user gt lt target name main depends init compile compress deploy gt lt echo gt message lt 7ecne lt target gt lt target name init gt lt mkdir dir output gt lt mkdir dir dist je lt target gt lt target name compile gt lt javac srcdir S sre destdir S output gt lt target gt
61. and jar task and javac task and jonas element and ispc task and mail task and mapper element and 2nd 3rd message elements param elements PatternSet type 2nd property elements propertyset elements 2nd read elements downloaded from lib eommolketab ir downloaded from lib eommolketab ir reference elements 2nd replaceregexp task and selectors tarfileset elements taskdef task and text data user element webdoclet task and weblogic element and write elements xmicatalog elements and xmlivalidate task and xslt style task and zipgroupfileset elements NET 2nd netrexxc task New Java Class dialog box Eclipse New Project dialog box Eclipse newCMP attribute weblogic element newenvironment attribute apply task exec task java task junit task newer attribute ftp task newline n nodeprecated attribute javadoc task nodeprecatedlist attribute javadoc task noEJBC attribute weblogic element noexec attribute cvs task nohelp attribute javadoc task noindex attribute javadoc task noinput option nonavbar attribute javadoc task NonStop Kernel Tandem noqualifier attribute javadoc task not element condition task notree attribute javadoc task nowarn attribute javac task downloaded from lib eommotketab ir downloaded from libeommolketab ir Index A B C D E F G H 0 9 K L M N O P Q R S CO U V W X Z oc4j element
62. and gt lt available classname org steven SAXparser gt lt available classname o0rg steven DOMparser gt lt and gt lt condition gt lt fail message Could not find all classes unless classes available gt lt target gt You can see the available attributes of fail in Table 2 3 Table 2 3 The fail task s attributes Attribute Description Required Default message A message indicating why the build exited No m Fails if the property of the given name is true in the current No project downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required Default unless Fails if a property of the given name is false in the current project No 2 1 4 Property Setting Tasks A few tasks allow you to indirectly set properties that is you specify a task likeavailable and assign the result of that task s processing to a property These function are like thecondition task though the syntax is different 2 1 4 1 Availability of resources The available task sets a property to true if a resource Is available at runtime The resource can be file a directory a class in the classpath or a JVM system resource If the resource is available the oroperty value is set to true otherwise the property is not set For example the following build fragment will set the propertyMath present to true If org steve Math is in Ant s classpath lt available classna
63. build file is one of true y or on and false otherwise char Or java lang Character Your method will be passed the first character of the attribute value Primitive types int short and so forth Ant will convert the value of the attribute into this type and pass it to your setter method java io File Ant will pass you a File object if the attribute value corresponds to a valid filename org apache tools ant types Path Ant will tokenize the value specified in the build file using and as path separators java lang Class Ant will want to interpret the attribute value as a Java class name and load the named class from system class loader Any other type that has a constructor with a singleString argument Ant will use this constructor to create a new instance using the name in the attribute A subclass of org apache tools ant types EnumeratedAttribute Ant will invoke this class s setValue method if your task supports enumerated attributes i e attributes with values that must be part of a predefined set of legal values What happens if more than one setter method is present for a given attribute A method taking a String argument will not be called if more specific methods are available If Ant could choose from other setters only one of them will be calledbut which one is called is indeterminate depending on your J VM downloaded from lib ommolketab ir downloaded from lib ommoltketab ir
64. builds are made up of components that have been fairly well tested but their operation together may still have some issues Nightly builds These are the most experimental of all publicly available Eclipse builds They re created nightly by the Eclipse team and there s really no guarantee that things will work well As with other software you generally want to use the latest release version of Eclipse I ll use Eclipse 3 0 the most recent release build in this chapter Select the download for your operating system and click the appropriate link to download it I nstallin Eclipse is easy all you ve got to do is to unzip or untar it depending on your operating system Since you download the version of Eclipse targeted to your operating system you ll find the executable file ready to run aS soon as you uncompress Eclipse You start Eclipse by running the Eclipse executable When you first run Eclipse you should see the Welcome page To get an overview of Eclipse or to rur a tutorial click the appropriate links To close this Welcome page click the X in the page s tab downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 11 1 2 Creating an Eclipse Project If you ve installed Eclipse and have got it running you have access to the Ant Eclipse interface and no extra work is needed Development work in Eclipse is based onprojects and I ll create a new project to show how to use Ant inside Eclipse To create a new
65. character set to use A Specifies the classpath for user class files oera Specifies where to find user class files by reference Specifies whether you want default Pout defaultexcludes excludes excludes to be used Set to yes or no ae Heed destdir Sets the output directory pe docencoding Sets the output file encoding to use Specifies the class file used to start a doclet doclet that will generate the documentation deeieeoas Specifies the path to the doclet given No by the doclet option Societe ec Specifies the path to the doclet given No by the doclet option by reference downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default Sa ete Sets the title for the package index No No Specifies the encoding of the source encoding file Specifies the packages to exclude in the excludepackagenames documentation Give as a comma No separated list een Specifies you want to override the No location of installed extensions Specifies you want to stop the build far bonerres process if the task exits with a non zero No return code footer Specifies the footer text for each page No Specifies you want to group particular group packages in the generated overview No page A Specifies the header text you want to No use for each page help ile Specifies the HTML help file you want k No use if any T Specifies you w
66. compile Weblogic text based deployment descriptors into an EJB deployment ddcreator descriptor ejbe Lets you run Weblogic s ejbc tool Weblogic 4 5 1 Borland Application Server 4 5 and 5 x OO iPlanet Application Server 6 0 J Boss JOnAS ejbjar ae skeletons for iPlanet Application ejbc Server 6 0 2 4 x and 2 5 Weblogic 5 1 to 7 0 and IBM WebSphere 4 0 wlrun Lets you start a Weblogic server Weblogic 4 5 1 to 7 0 wistop Lets you stop a Weblogic server Weblogic 4 5 1 to 7 0 Weblogic 4 5 1 Supports creation of EJB jar files EJB 1 1 amp 2 0 Supports compilation of EJB stubs and iPlanet Application Server 6 0 downloaded from lib ommolketab ir downloaded from lib ommotketab ir 9 6 1 JARing Files The largest and most general of the EJB tasks is theejbjar task This task works by scanning directories for each deployment descriptor found ejb jar will parse it to determine the necessary class files which implement the bean These files are assembled along with the deployment descriptors into a well formed EJB jar file Any support files which should be included in the created Jar file can be added with the support nested element For each class included in the jar file ejbjar will scan for any super classes or super interfaces which will be added to the generated jar file The attributes of this task appear in Table 9 15 Table 9 15 The Ant ejbjar task s attribute
67. creates parent directories as needed downloaded from lib ommolketab ir downloaded from lib ommotketab ir 4 3 Deploying Applications As you d expect Ant excels at deploying applications and there are a number of tasks to choose from You ve saw the javac task s destdir attribute for deployment back in Chapter 1 In this section you ll see copy move ftp telnet and sshexec The copy and move tasks are useful for local and network deployments and tasks likeftp are great for remote deployments Additionally Chapter 8 will cover deployment to web servers with tasks like get which you can use to send administrative commands to servers like Tomcat I ll cover Tomcat s built in custom Ant tasks and serverdeploy Want to get a file s name without the path attached Pass the filename to the basename task Want to get just the path Use dirname The pathconvert task converts a nested path or reference to a Path FileSet DirSet or FileList into a path automatically adjusted for the target platform and stores the result in a given property 4 3 1 Deploying by Copying This task copies a file or a fileset to a new file or a new directory This is Ant s most basic deployment task for local and network deployment Here are a few examples starting with copying just one file lt copy file file txt tofile backup txt gt This example copies a file to a new location lt copy file file txt todir backup
68. doesn t timeout finish in time Time is measured in milliseconds No Ignored if fork is disabled The junit task supports a nested classpath element that represents a path like structure and which you can use to set the classpath used while the tests are running A number of other elements may be nested inside thejunit element If you re using fork you can pass additional parameters to the new JVM with nested jvmarg elements lt junit fork yes gt lt jvmarg value Djava compiler NONE gt lt 7 Vio downloaded from lib ommolketab ir downloaded from lib ommotketab ir You can specify environment variables to pass to a forked JVM with nestedenv elements I ll look at this element including its attributes inChapter 7 Nested sysproperty elements can specify system properties required by the class you re testing These properties will be made available to the JVM during the execution of the test You can use the same attributes as the env task here for example you can use the key and value attributes to Specifies properties and property values as in this example unto lt sysproperty key basedir value S basedir gt lt 7 Junit 5 1 2 1 Formatting test results Test results can be printed in various formats and you use the formatter nested element to specify which format to use by default the output of the tests will be sent to a file unless you set the usefile attribute to false There are t
69. downloaded from lib eommolketab ir downloaded from lib eommoltketab ir junitreport task and plain formatter XML formatter repositories resin ejb xml element ejbdoclet task resin web xml element webdoclet task resolveExecutable attribute apply task exec task resolveFile method Project class resource attribute available task property element taskdef task resultproperty attribute apply task exec task 2nd java task 2nd 3rd return codes 2nd 3rd reverse attribute patch task rexec task rlog command CVS rmic task rootDirectory attribute xmlproperty task rom task rtag command CVS run method JUnit runBare method JUnit downloaded from lib eommolketab ir downloaded from libeommolketab ir Index A B C D E F G H H J K L M N O P Q R S O U V W RX 2 S Option SAX Parser SAX2 parser scanincludeddirectories attribute xslt style task Schema Unit Test SUT schema validating with 2nd scp command Unix scp task 2nd 3rd Scripdef task script task 2nd section element manifest task selector element fileset element selectors 2nd 3rd 4th Selectors type semanticAttributes attribute xmlproperty task semicolon separator attribute ftp task sequential task 2nd 3rd serialwarn attribute javadoc task server attribute fto task 2nd generic element jonas element telnet task weblogic element server command CVS s
70. echo Building the jar file echo BUILD SUCCES OFUL Total time 2 seconds Each build file requires a default target but you can specify the target s you want Ant to run via the command line For example add a target named clean to the build file using Example 1 2 as a starting point lt project default main gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt target name main depends compile compress gt lt ecno gt Building the jar file lt echo gt lt target gt lt target name compile gt lt javac srcdir gt lt target gt lt target Name Ccompress gt lt jar jarfile Project jar basedir includes class gt lt target gt lt target name clean gt lt delete file class gt lt delete file jar gt lt target gt lt project gt You can then specify the clean target from the command line Sant clean If you want to run multiple targets you can list them in the order they should be run Sant clean compile compress If you don t want to allow a target to be run from the command line you can Start the target name with a hyphen e g clean This will make Ant think the target is a command line option and since clean isn t a valid command line option Ant will refuse to run that target directly By default the build file that Ant looks for isbuild xml but you can name the file as you want The downloadable examp
71. ejbdoclet task offset attribute format task old attribute javadoc task onerror attribute taskdef task open source Ant and CVS and Eclipse and JUnit and XDoclet and openejb element ejbdoclet task operating systems Ant support build process and determining name exec task and 2nd optimize attribute javac task optional attribute import task options attribute cab task or element condition task orb attribute jonas element originalfile attribute patch task orion element ejbdoclet task os attribute apply task exec task 2nd 3rd os element condition task out attribute xslt style task outfile attribute test task Outline view Eclipse outproperty element output build process and controlling logging 2nd output attribute ant task antstructure task apply task cvs task exec task java task sshexec task downloaded from lib ommolketab ir downloaded from lib ommolketab ir outputdir attribute weblogic element outputencoding attribute copy task outputproperty attribute apply task exec task java task sshexec task overview attribute javadoc task overwrite attribute copy task 2nd move task downloaded from lib ommolketab ir downloaded from libeommolketab ir Index A B C D E F G H H Y K L M N O P Q R S CO U V W X Z p option P4Add task P4Change task P4Counter task P4Delete task P4Edittask P4Fs
72. elements and if the number of files is more than 1 or if only the dir attribute is specified in the fileset then only todir is allowed Specifies the directory the files should be copied to If you use the file attribute tofile Or todir can be used If you use nested fileset elements and if the number of files is more than 1 or if only the dir attribute is specified in the fileset then only todir downloaded from lib ommotketab ir Attribute Description Required Default is allowed Specifies you want to verbose see filenames displayed as the files are being copied No false By default files are only copied if the source file is newer than the destination file or when the destination file does not exist However you can explicitly overwrite files with the overwrite attribute You can use fileset elements inside copy elements to create a fileset to copy If you want to use a fileset the todir attribute must be set You can use nested mapper elements and filter set elements and the copy task supports nested FilterChains If you use filters in your copy operation limit the operation to text files Binary files will be corrupted by that kind of copy operation This is true whether the filters are implicitly defined by the filter task or explicitly provided to the copy operation as filter sets 4 3 2 Moving Files The move task moves a file copies and then deletes the original to
73. example lt fileset dir S source includes gt lt filename name cpp gt lt fileset gt The containsregexp selector limits the files in a fileset to only those whose contents contain a match to the regular expression specified by the expression attribute lt fileset dir source includes jJava gt lt containsregexp expression S printin gt lt fileset gt The type tag selects files of a certain type directory or regular Here s an example downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt fileset dir T pro gt lt type type dir gt lt fileset gt FileSets are no longer about filenames Now you ve got access to more data including what s inside files Selectors can be defined outside of any target by using theselector tag and using them as references 2 3 File Filters Filters let you filter the data in files modifying that data if you want to FilterSets are groups of filters and you can use filters to replace tokens in files with new content For example say that your files contain a token like DATEe you can use filters and a filter set to copy those files with thecopy task while replacing that token with the current date You can find the attributes of thefilter set type in Table 2 14 to use FilterSets you can use the filter task which is coming up next with examples When a filter set iS used in an operation the files are pr
74. excludesfile and patternset elements Here s an example Oirset car 51bu110 dir gt lt include name apps classes gt lt exclude name apps Test gt lt dirset gt You can find the attributes of this type inTable 2 10 Table 2 10 The dirset type s attributes Attribute Description Required Default casesensitive Specifies whether you want to use case sensitivity No true dir Contains the root of the directory tree you want to use Yes A list of the patterns matching directories you want exluded No excludes i Comma or space separated list Specifies a name of a file each line of the file is interpreted NO excludesfile as an exclude pattern downloaded from lib ommolketab ir downloaded from lib ommotketab ir ere Attribute Secu a ee mee Description ees Required Pete Default followsymlinks Set to true if you want Set to true if you want symbolic links to be followed links to be followed No true A list of the patterns matching directories you want included includes Comma or space separated list Specifies a name of a file each line of the file is interpreted as an include pattern includesfile 2 3 4 Creating Lists of Files FileLists are types corresponding to explicitly named lists of files While FileSets act as filters returning only those files that exist in the filesystem and match specified patterns FileLists are usefu for specifying files individu
75. file is older or does not exist It doesn t check the files those java files might depend on such as parent or imported classes Thedepend task however lets you perform this kind of dependency checking When this task finds out of date classes it removes the class files of any other classes that depend on them To determine dependencies this task analyzes the classes in all files passed to it using the class references encoded into class files by the compiler It does not parse or read source code You typically use the depend task before compiling Here s an example that uses depend before calling javac lt xml version 1 0 gt lt project default main gt lt property name message value Building gt lt property name sro location source gt lt property name output location bin gt lt target name main depends init compile compress gt lt echo gt message lt echo gt lt target gt lt target name init gt lt mkdir dir S output gt lt target gt lt target name compile gt lt depend srcdir src destdir output closure yes gt lt javac srcdir srce destdir output gt lt target gt lt target name compress gt lt jar destfile S output Project jar basedir output includes class gt lt target gt lt pro ect The attributes of this task appear in Table 10 4 downloaded from lib ommolketab ir downloaded from
76. from lib ommolketab ir downloaded from lib ommotketab ir You can see the attributes of this task in Table 2 6 Table 2 6 The loadfile task s attributes Attribute Description E Required Default srcFile Indicates the source file property Indicates the property you want to store the text in Indicates the encoding you want to use when reading text from the encoding Fic failonerror Set to true if you want to halt the build if this task failed Ea 2 2 2 Overriding Properties Take a look at Example 2 3 defining a property named message twice Building the jar file and then redefining it Compiling and compressing Example 2 3 Overriding a property ch02 overriding build xml lt xml version 1 0 gt lt project default main gt lt property name message value Building the jar file gt lt property name src location source gt lt property name output location bin gt lt property name message value Compiling and compressing gt lt target name main depends init compile compress gt lt echo gt message lt echo gt lt target gt lt target name init gt lt mkdir dir o0output gt lt target gt lt target name compile gt lt javac srcdir S src destdir S output gt lt target gt lt target name compress gt lt jar destfile S output Project jar basedir S output includes class gt
77. from which to load definitions No if any Specifies the format of the file or resource pointed to by the format file Or resource attributes No properties Possible values are properties Or xml No Joaderner Specifies the loader that you want to use to load the class Name Yes unless the Specifies the name of the file Or resource datatype or task you re type attributes creating have been specified Specifies what to do if there is an error while defining a type Possible values are fail Causes a build exception No fail report Outputs a warning ignore Does nothing Since Ant 1 6 Specifies the name of the resource resource from which you want No to load definitions Vie EOL downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required Default Specifies the URI at which this uri type task definition should be No found Since Ant 1 6 The taskdef taSk S classpath attribute Is a path like structure and can be set with a nestedclasspath element The build file in Example 12 2 builds the simple Ant task and JARs it ingreeting jar The taskdef task in the same build file retrieves the task from that J ARfile and executes the task which should print out the No worries message Example 12 2 Build file for a simple Ant task ch12 greetingtask build xml lt xml version 1 0 gt lt project default main gt
78. gt lt property name app lib dir value lib gt lt property name app meta inf dir value meta inf gt lt property name app xdoclet force value false gt Pati gt downloaded from lib eommolketab ir lt tstamp gt lt taskdef name ejbdoclet classname xdoclet modules ejb E bDocletTask classpathref app class path gt lt mkdir dir S app classes dir gt lt mkdir dir S app generated srce dir gt lt mkdir dir S app meta inf dir gt lt target gt lt target name ejbdoclet depends init gt lt ejbdoclet destdir S app generated src dir mergedir parent fake to debug excludedtags version author todo ejbspec 2 0 force app xdoclet force verbose false gt lt fileset dir src java gt lt include name java gt lt fileset gt lt remoteinterface gt lt Localinvertace gt lt homeinterface gt lt localhomeinterface gt lt entitycmp gt lt entitybmp gt lt seesi0n gt lt deploymentdescriptor destdir S app meta inf dir description ejbbean gt lt ejbdoclet gt lt target gt lt target name compile depends ejbdoclet gt lt Javie destdir S app classes dir classpathrei app Class path debug on deprecation on optimize off gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt srce path S app java dir gt lt src path S app generated sre dir gt
79. in Table 9 16 Table 9 16 The weblogic element s attribute Attribute Description Required Default Specifies any additional arguments you want to pass args No to the weblogic ejbc tool Specifies the classpath that should be used when the classpath l No task runs the weblogic ejbc tool Specifies a different compiler to be used for compiling compiler No the generated J ava files ae eae Specifies the directory where the generated J AR files Yes should be stored Specifies the classname of the ejbc compiler When ejbcclass used with Version 7 this attribute should be set to No weblogic ejbc to avoid a deprecation warning Specifies the suffix used for the generic J AR file This genericjarsuffix JAR file is generated as an intermediate step in No generic jar building the weblogic deployment J AR eee Specifies any additional arguments you want passed No i to the JVM running the weblogic ejbc tool Specifies the debug level for messages Set to 16 to avoid warnings about EJB Home and Remotes in the No classpath EEEE T Specifies if Weblogic will preserve the Java files it No OE generates ee Specifies if you want the generic file used for input to No mee ejbc to be preserved Specifies ejbjar should parse the Weblogic newCMP deployment descriptor to find the CMP descriptors No false Set to true false Ea Specifies you don t want Weblogic s ejbc to be run on No the EJB jar file M Specifies this directory as the
80. in the past you want change log No information rer specifies the file in which you want the change log report Yes written dir Specifies the directory from which to run the CVS log No TT command Specifies the latest date for which you want to include change y logs Specifies that you want the task to fail if it encounters an failonerror Ra O false package Specifies the module you want to check out the module you want to check out Specifies the password file you want the task to read passfile cvspass passwords from Specifies the port the task should use to communicate with om the CVS server me poriadna mE Specifies the earliest date for which you want to include m een bylag CvVSroot cag Letts you access Lets you access change logs by tag 0 logs by tag Specifies a property file holding name value pairs ae usersfile user IDs and names allowing the task to report names No inctead of IDs downloaded from lib ommolketab ir downloaded from lib ommotketab ir The nested user element allows you to specify a mapping between a user ID as it appears to the CVS server and a name to include in the formatted report The attributes of theuser element appear in Table 6 7 Table 6 7 The user element s attributes Attribute Description Required Default displayname Specifies the name you want used in the CVS change log report Yes Specifies the user ID of the person as far as the CVS server is userid
81. installation into thelib directory of your Ant installation to use these tasks The Tomcat deployment tasks are deploy reload and undeploy to use them add these taskdef elements discussed in Chapter 11 to your build file lt taskdef name deploy classname org apache catalina ant DeployTask gt lt taskdef name reload classname org apache catalina ant ReloadTask gt lt taskdef name undeploy classname org apache catalina ant UndeployTask gt To use these tasks you ll need manager privileges with Tomcat editconf tomcat users xml to add manager privileges for a username admin here and password like this lt xml version 1 0 encoding utf 8 gt lt COMcal Uscere lt role rolename manager gt lt role rolename rolel gt lt role rolename tomcat gt lt user username admin password password roles manager gt lt user username rolel password tomcat roles rolel gt lt user username tomcat password tomcat roles tomcat gt lt user username both password tomcat roles tomcat rolel gt lt tomcat users gt You can use the deploy task to deploy a web application to Tomcat from Ant like this lt target name install gt lt deploy url S manager url username manager username password S manager password path S app path localWar file build gt lt target gt Here manager url is the URL of the Tomcat manager servlet The default name for thi
82. jar destfile S output Project jar basedir S output includes class gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir guru ale ee lt project gt Here are the entire contents of another sample file build properties which uses a name value format for each property message Building the jar file Using the build file from Example 2 2 here s the output from running Ant note the value of themessage property was picked up correctly from build properties Sant Bulldfile build xml init mkdir Created dir home steve ch02 properties bin compile javac Compiling 1 source file to home steve ch02 properties bin compress jar Building jar home steve ch0O2 properties bin Project jar main echo echo Building the jar file echo BUILD SUCCESSFUL Total time 3 seconds Properties in external files are stored as text strings suitable for properties of the kind you d set with the property task s value attribute Ant has an optional task propertyfile that lets you edit property files This can be useful when you need to make unattended modifications to configuration files when deploying to servers 2 2 1 Loading Text You can use the loadfile task to load a text file into a single property Here s an example that loads the property message with the text in the file message txt lt loadfile property message srcFile message txt gt downloaded
83. lt jar destfile S output Project jar basedir S output includes class gt lt target gt lt project You can see the javadoc task at work when the build file runs Sant B ildfile build xml PLC mkdir Created dir home steven ch03 javadoc bin mkdir Created dir home steven ch03 javadoc docs compile javac Compiling 1 source file to home steven ch03 javadoc bin QOC javadoc Generating Javadoc javadoc Javadoc execution javadoc Loading source file home steven ch03 javadoc source Project java javadoc Constructing Javadoc information javadoc Standard Doclet version 1 4 0 javadoc Building tree for all the packages and classes javadoc Building index for all the packages and classes javadoc Building index for all classes javadoc Generating home steven ch03 javadoc docs stylesheet css downloaded from lib ommolketab ir downloaded from lib ommolketab ir compress jar Building jar home steven ch03 javadoc bin Project jar main echo echo Building the jar file echo BUILD SUCCESSFUL Total time 10 seconds And you can see the index html Javadoc result in Figure 3 1 Note the message This application prints out No worries Figure 3 1 New J avadoc for the project Project Propect APT Macrosolt Interet Fapkiner rec gt A g Ash proves Breda G SS So Address a Package RET lice Tree Depr
84. lt project default main gt lt property name message value Deploying the jar file gt lt property name srce location source gt lt property name output location bin gt lt property name dist location user gt lt target name main depends init compile compress deploy gt lt echo gt message ge elves lt target gt lt target name init gt lt mkdir dir S output gt lt mkdir dLri dist J gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt targat lt target name compile gt lt javac srcdir o src destdir 0u utput gt lt target gt lt target name compress gt lt copy todir S output file S src readme txt gt lt jar destfile S output Project jar basedir output gt lt include name class gt lt include name txt gt lt jar gt lt target gt lt target name deploy gt lt copy todir Sidist gt lt fileset dir S output gt lt exclude name java gt lt exclude name class gt lt exclude name txt gt lt fileset gt lt ecooy lt target gt lt project gt You can see the attributes of this task inTable 4 11 Table 4 11 The copy task s attributes Attribute Description Required Default Specifies that you want to use multiple mapper elements Available since Ant 1 6 No false enablemultiplemappings Specifies the enco
85. lt property name src location src gt lt property name output location output gt lt target name main depends jar gt lt taskdef name greeting classname Greeting classpath greeting jar gt lt greeting gt lt target gt lt target name jar depends compile gt lt jar destfile greeting jar basedir S output gt lt target gt lt target name compile gt lt mkdir dir S output gt lt javac srcdir S srce destdir S output gt lt target gt lt project gt Here s what you see when the build file runs Theexecute method of the task s code was indeed called displaying the expected message Sant Buildfile build xml compile mkdir Created dir home steven ant chl12 greetingtask output javac Compiling 2 source files to home steven ant chi2 greetingtask output downloaded from lib ommolketab ir downloaded from lib ommolketab ir jar jar Building jar home steven ant ch1l2 greetingtask greeting jar main greeting No worries BULLD SUCCESSFUL Total time 3 seconds downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Team LiB 12 2 Extending the Task Class Usually you extend an Ant task class like org apache tools ant Task when you write custom tasks Ant comes with a selection of task classes meant to be extended AbstractCvstTask Abstract CVS task class JDBCTask Handles J DBC configuration needed
86. name hello type xs string gt lt xs sequence gt lt xs complexType gt lt xs element gt lt xs schema gt Finally here s what you see when you execute this build file showing that the document was successfully validated Sant Bulldfile build xml main xmlvalidate 1 file s have been successfully validated BULLD SUCCESSFUL Total time 1 second Here s what you d see if there was an error for example if document had been mispelled documnt in the schema Sant Buildfile build xml main xmlvalidate document xml 4 60 cvc elt 1 Cannot find the declaration of document downloaded from lib ommolketab ir downloaded from lib ommotketab ir BUILD FAILED document xml 1s not a valid XML document Total time 1 second 9 1 2 Validating with DTDs Validating documents using DTDs is as easy aS you can see in Example 9 2 which validates a document document xml with a DTD Example 9 2 Valiating with a DTD ch09 DTD build xml lt xml version 1 0 encoding UTF 8 7 gt lt project default main gt lt target name main gt lt xmilvalidate lenient no warn yes file document xml classname org apache xerces parsers SAXParser gt lt xmlvalidate gt lt target gt lt project gt Here s the document with a DTD document xml to validate lt xml version 1 0 standalone yes gt lt DOCTYPE document lt ELEMENT document employee gt lt ELEMEN
87. newenvironment i false passed as new environment variables to a forked J VM Specifies the name of a file in which to store the output output Specifies the name of a property in which you want A a the output of the task to be placed inpucstring downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required Default Specifies the name of the property that you want to resultproperty hold the return code Use this only iffailonerror IS No false and if fork IS true aa Specifies you want to spawn a new process in which to No run the class To use this attribute set fork tO true Specifies you want the task to quit if it doesn t finish in timeout the given time Set the time in milliseconds You No Should only use this if fork IS true The java task Supports a number of nested elements many of which are the same as the javac task You can use arg elements to pass arguments to Java and jvmarg elements to specify arguments to a forked JVM Nested sysproperty elements specify system properties required by the class you re running As of Ant 1 6 you can US syspropertyset elements which specify a set of properties to be used as system properties The java task Supports nested classpath elements which you can use to specify a classpath to use when Java runs and supports aS bootclasspath elements since Ant 1 6 to set the location of bootstrap class files You can
88. ommotketab ir Attribute Description Required Default ieaie Specifies you want to run the command one No T time only on multiple files Specifies if filenames should be absolute or relative relative when passed to the command to No false execute Specifies the name of the executable should be resolved using the project s base directory then using the execution directory if that doesn t work Since Ant 1 6 false resolveExecutable Specifies the name of the property that you resultproperty want to hold the return code Use this one only No If failonerror IS false and If fork IS true Specifies you don t want to run the command if skipemptyfilesets no source files found or are newer than their No corresponding target files false Specifies you want to spawn a new process in spawn which to run the command To use this attribute set fork to true Specifies you want the task to quit if it doesn t timeout finish in the given time Set the time in milliseconds Specifies whether you re working with files or directories Set to dir file or both e Specifies whether you want the task to display N its progress Since Ant 1 6 Specifies you want to run the executable using 1 h l nn caudate the J VM s execution facilities You can use any number of nested fileset elements to specify the files you want to use with this task Since Ant 1 6 you can use any number of nestedfilelist and or dirset elements as well
89. on its body and prominent horns on its head It is also Known as the horny toad Despite the horned lizards fierce appearance they are not aggressive Their primary diet consists of ants although they sometimes eat beetles grasshoppers and other insects which they catch with their long tongues The horned lizards first line of defense from predators is their camouflage but they are also known to hiss and inflate their bodies to appear more intimidating As a last resort the have the ability to squirt blood from the corners of their eyes in an attempt to confuse attackers In Texas and Oklahoma horned lizards are considered a threatened species It is illegal to possess a horned lizard without a scientific permit Matt Hutchinson was the production editor for Ant The Definitive Guide Second Edition GEX Inc provided production services Mary Brady Sanders Kleinfeld and Darren Kelly provided quality control Hanna Dyer designed the cover of this book based on a series design by Edie Freedman The cover image is a 19th century engraving from the Dover Pictorial Archive Karen Montgomery produced the cover layout with Adobe InDesign CS using Adobe s ITC Garamond font David Futato designed the interior layout This book was converted by Keith Fahlgren to FrameMaker 5 5 6 with a format conversion tool created by Erik Ray Jason McIntosh Neil Walls and Mike Sierra that uses Perl and XML technologies The text font is Linotype Birka t
90. or semicolon downloaded from lib ommolketab ir downloaded from lib ommotketab ir separated lists of locations such as classes jar classes2 jar You can separate directories with a or a on any platform If you want to build your own paths and reference them later you can use thepath element with enclosed pathelement elements For example to create a new path and give it the ID build classpath you can use this path element and then refer to the new path with therefid attribute that path like structure elements support lt path id build classpath gt lt pathelement path classes gt lt pathelement path classes2 gt lt path gt lt target name compile gt lt javac destdir S build classpath classes jar debug on gt sre path 5rc gt lt classpath refid build classpath gt lt javac gt lt target gt If a task supports path like structures you can specify paths using the attributes of the task nested elements with names that correspond to those attributes or with a reference to a path you ve explicitly created withpath 2 3 2 Working with Groups of Files FileSet S are types that represent groups of files and they re common in Ant because handling a group of files is a common thing to do Thefileset element can contain nested include includesfile exclude and excludesfile elements here s an example using fileset as well as include and exclude lt fileset di
91. or space separated list of No files oei Specifies a file containing a list of files you No want to include eerie Specifies whether you want to list the source No Mp files to be compiled Specifies the starting size of the memory for the JVM Applies only if javac IS run No externally PEE NEEE E E E Specifies the maximum size of memory you 3 e want to use for the JVM if you re forking it ae Specifies whether you want to pass the No aer nowarn SWitch to the compiler mE E Specifies whether you want to compile using No nee optimization using the o switch Saurce executable memoryInitialSize NO source source Switch Legal values are 1 3 1 4 and No argument will 1 5 be used Specifies whether you want to use the downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required Default The value of the srcdir sourcepath Specifies the source path to use No attribute or nested src elements SOurcepalL are ne mra celal No given in reference form Yes unless Specifies where to find the Java source files nested src srodir l you want to compile elements are present Specifies that you want to generate class target files for particular Java version e g 1 1 or No 1 2 Specifies the directory where temporary files No default is ee Should go Used only if the task is forked and the current the leng
92. output directory instead No of a jar file jvmdebuglevel downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Attribute Description Required Default aa Specifies if weblogic ejbc should always be used to No o build the jar file Specifies the string that should be added to the suriy deployment descriptor to create the WebLogic J AR No E filename Specifies the classpath for the Weblogic classes to avoid a warning when the home and remote No interfaces of a bean are on the classpath used by weblogic ejbc The weblogic nested element supports nested classpath and wlclasspath nested elementsthe wiclasspath element holds the classpath used by the Weblogic Server as detailed by thewlclasspath attribute in Table 9 16 and it takes the same attributes and nested elements aSclasspath The weblogic element supports nested sysproperty elements to allow J ava system properties to be set wlclasspath Investigating them all would take us many pages deep into the mechanics of these six EJB servers and far from Ant If you re interested you can find the details for using various vendor specific tools in the Ant EJB Tasks User Manual at ant home docs manual OptionalTasks ejb html downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Chapter 10 Optional Tasks A significant number of optional tasks come with Antthe full list appears inTabl
93. p gt 1 lt load o n startup gt lt servlet gt lt servlet mapping gt lt servlet name gt ServletApp lt servlet name gt lt url pattern gt app lt url pattern gt lt servlet mapping gt In this way XDoclet can write deployment descriptors for you if you remember to put all needed information in your source code files using XDoclet tags 9 5 2 Working with EJB Containers This XDoclet Ant task executes EJ B specific sub tasks to support EJB development You can see the attributes of this task in Table 9 12 The legal nested elements appear in Table 9 13 Table 9 12 The ejbdoclet Ant task s attributes Attribute Description SS Required Default Me Specifies you want to add JavaDoc tags to the generated classes Specifies the destination directory to use for If destDir IS not destDir i ae output files specified for a subtask Specifies suffixes that should be removed ejbClassNameSuffix from the bean classname A comma No separated list Specifies the version of EJB specification ejbdoclet should use Possible values 1 1 and 2 0 excludedTags Specifies tags that should not be written to Te output files Specifies whether you want to force the the force No generation of files if needed ejbSpec No Default Is 2 0 downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default Specifies the directory where
94. page by selecting Window Preferences Ant Runtime and clicking the Classpath tab When Eclipse runs Ant it looks for the appropriate classes on the Ant classpath as set in the Ant Home Entries item To change the Ant Home Entries click the Ant Home button and choose the Ant installation you wish to use If you don t want to change the classpath you can run Ant as an external tool from Eclipse To do that select Run External Tools External Tools to open the External Tools dialog Click the Program item and then the New button Enter a name for the new tool such as Ant 1 8 or whatever is appropriate Next to the Location field click the Browse File System button and navigate to ant sh or ant bat whichever is right for your operating system and click Open The External Tools dialog will reappear in the Arguments field enter any arguments you want to pass to Ant Finally in the Working Directory field enter the directory of the build file you want to use and click Run to launch the new version of Ant The problem with doing this is that you won t have easy access to predefined values that you have while working inside Eclipse In most cases it s far better to use Ant from inside Eclipse when building Eclipse projects downloaded from lib ommolketab ir downloaded from lib eommolketab ir 11 4 Using the Ant View Eclipse comes with a dedicated view for working with Antcalled the Ant viewwhich is a window that gives yo
95. project select File New Project opening the New Project dialog Select the Java Project item and click Next On the next page give this project the nameantExample Leave the other defaults as they are and click Finish This opens the new project in Eclipse you can see theantExample project at left in Eclipse s Package Explorer This project is empty so far to add Java code select theantExample project in the Package Explorer and select File New Class opening the New Java Class dialog Give the package name as org antbook the name of the new class aSAntClass and select the checkbox marked public static void main String args to make Eclipse create a main method Click the Finish button This creates the code AntClass java you see in the Eclipse editor at the center ofFigure 11 2 complete with a main method Figure 11 2 A new J ava class Add this code to make this class do something downloaded from lib ommolketab ir downloaded from lib ommoltketab ir public static void main String args System out println No worries Click the Save icon in the toolbar to save the changes toAntClass java and select Run Run As ava Application You ll see the output of this code No worries in the Console tab at the bottom of Eclipse 11 1 3 Writing an Ant Build File in Eclipse To create an Ant build file in Eclipse right click theantExample project in the Package Explorer and select New
96. project from the length default input stream Executes the specified target and any void executeTarget java lang String targetName targets it depends on Executes the specified targets in the given void executeTargets java util Vector targetNames sequence and the targets they depend on Returns the base directory of the project T directory is returned as aFile object jac Aeeeor Govtotienieeenecer 1 Returns the list of build listeners that have been added to the project java io InputStream getDefaultInputStream Returns this sake ect s default Input stream i an InputStream object sen tae a L Returns the name of the default target of tt project as a String E PEE EEEE E EE T E Returns the project description as a string one has been specified java lang String getElementName java lang Object Returns a description of the given element element a string Returns the name of the project if one has java lang String getName been specified java util Hashtable getProperties Returns the project s properties table Returns the value of a property if it has bee java Lang Crin etProperty java lang String name l a A a a set in the project Look java lang Object getReference java lang String key ane a reference in the project by ue java io File getBaseDir downloaded from lib ommolketab ir downloaded from lib ommolketab ir Method Does this Returns a hashtable of the
97. projecthelp Buildfile build xml Main targets compile Compilation target compress Compression target main Main target Default target main 1 5 6 Logging and Libraries downloaded from lib ommolketab ir downloaded from lib ommotketab ir You can log the output of running Ant using the logfile option For example here s how you d sent output to a file named file log sant logfile file log You can log part of a build file s results with therecord task for example if you were using the javac task to compile code and wanted to log the output of this task to a file namedlog txt you could start and stop that logging this way lt record name log txt action start gt aWaAVae cee gt lt record name log txt action stop gt Another handy option is the 1ib option which adds additional directories to be searched for jar or class files Here s an example which adds home ant morejars to the library search path Sant lib home ant morejars The lib option is useful when you re working on a system where you don t have access to the Ant lib directory as is often the case when dealing with Internet Service Providers ISPs Using this option you can make sure Ant has access to JAR files needed for Ant s optional tasks without having to load them into directories you don t have permission to access Before Ant 1 6 all JARS in theant_Home lib would be added to the CLASSPATH used to run Ant Since Ant 1 6 t
98. references in the project jJava util Hashtable getReferences Returns the hashtable of the targets in the java util Hashtable getTargets a i project Returns the current task s definition hashtable java util Hashtable getUserProperties Returns the user properties hashtable java lang String getUser Property javya lang Ering Returns the value of a user property in the name project if it has been set Jjava til Hashtable getTaskDerinitiona Initializes the project readying it for yoid init execution Writes a string message to the log Uses th TORA AO AVA AAEL MERRTE default log level MSG_INFO Writes a project level message to the log void log java lang String message int msgLevel i d J a Uses message level you specify void log Target target java lang String message int Writes a message level message to the log msgLevel Uses message level you specify void log Task task java lang String message int Writes a task level message to the log Use msgLevel message level you specify Replaces any occurences of constructior in the given string with the value of the matching property java io File resolveFile java lang String fileName Returns the full form of a filename Specifies the base directory you want to us for the project java lang String replaceProperties java lang String value void setBaseDir java io File baseDir Specifies the base director
99. results in various output directories In all these cases the target handles piecing together various individual tasks Ant build files are made up of targets like these For example to create themain target you use the target element along with the name attribute lt xml version 1 0 7 gt lt project default main gt lt target name main gt lt target gt lt project gt downloaded from lib ommolketab ir downloaded from lib ommoltketab ir You can see the possible attributes for the target element in Table 1 2 Table 1 2 The target element s attributes Attribute Description Required name Defines the target name Yes depends Comma separated list of targets to execute before this target No if Name of a property needed to run this task No unless Name of a property that can not be set before running this task No description Description of this target s purpose No 1 4 3 Tasks You populate an Ant target with tasks a task is an XML element that Ant can execute to make something happen For example the echo task echoes text messages to the console lt xml version 1 0 gt lt project default main gt lt target name main gt lt echo gt Building the jar file lt echo gt lt target gt lt project To create an Ant target you place Ant tasks like echo inside a target element in this case the main target only has one task but you can include hund
100. should be output Table 9 8 The outputproperty element s attributes Attribute Description Required name Specifies the name of the property to set Yes value Specifies the new value of the property Yes TraX processors can accept factory elements to specify factory settings These elements can contain one attribute name which specifies the fully qualified classname of the transformer factory to use Team LiB downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 9 5 Using XDoclet XDoclet is an open source code generation engine designed for use with Ant and you can pick it up for free at http xdoclet sourceforge net It ll write code for you especially deployment descriptors and is often used for Web and EJB development XDoclet comes with a number of Ant tasks built in shown in Table 9 9 Table 9 9 The XDoclet Ant tasks Ant task Does this doclet Specifies the base class for all XDoclet Ant tasks ejbdoclet Specifies which EJ B specific subtasks to execute hibernatedoclet Specifies which Hibernate subtasks to execute jdodoclet Specifies which J DO specific subtasks to execute jmxdoclet Specifies which J MX specific subtasks to execute mockdoclet Generates mock doclet objects port letdoclet Specifies which portlet specific subtasks to execute webdoclet Specifies which Web specific subtasks to execute XDoclet lets you generate code and deployment descr
101. subtasks will No but should be set if look for files that they should merge with you use the merge their generated files feature verbose Specifies you want verbose feedback No mergeDir Table 9 13 The ejbdoclet Ant task s nested elements Element Description apachesoap Provides support for Apache SOAP subtasks axisdeploy Provides support for axis deployment axisundeploy Provides support for axis undeployment porland Provides support for Borland code castormapping Specifies you want to generate a mapping xml deployment descriptor configParam Specifies configuration parameters that will be included as an attribute value p dao Provides support for DAO dataobject Provides support for data objects for Entity EJ Bs deploymentdescriptor Creates a deployment descriptor easerver Provides support for configuration files for EJB JAR files in EAServer 4 1 entitybmp Creates entity bean classes for BMP entity EJ Bs entitycmp Creates CMP layer code entityfacade Provides support for entity facades entitypk Creates primary key classes for entity EJ Bs fileset Specifies a fileset of files to parse homeinterface Provides support for remote home interfaces for EJ Bs hpas Provides support for an hp ejb jar xml deployment descriptor for HPAS eee Provides support for jboss xml jaws xml and or jbosscmp jdbc xml i deployment descriptors for J Boss jonas Provides support
102. task style task 2nd 3rd stylebook task downloaded from lib ommolketab ir downloaded from lib eommolketab ir styledir attribute report task stylesheetfile attribute javadoc task subant task subject attribute mail task subroutine calls substitution element replaceregexp task subTask element ejbdoclet task webdoclet task success element sound task 2nd suffix attribute weblogic element sunone element ejbdoclet task support element ejbjar task 2nd symlink task sync task syntax checking sysproperty element junit task purpose weblogic element and syspropertyset element 2nd System err 2nd System out 2nd downloaded from lib eommolketab ir downloaded from libeommolketab ir Index A B C D E F G H 0 Y K L M N O P Q R S T U V W X Z tab attribute fixcrlf task tablength attribute fixcrlf task tabs manipulating tabstospaces element FilterChain type 2nd tag attribute cvs task cvschangelog task tag command CVS tailfilter element FilterChain type tar task 2nd tarfileset element tar task target attribute ant task antcall task javac task target element 2nd 3rd targetfile attribute update task uptodate task targetfile element targets Ant view and antcall task and build example build files and 2nd declaring properties and DirSet type and FileSet type and hyphens and master overview 2nd ru
103. task 2nd includefilenames attribute mail task includeJavaRuntime attribute javac task includes attribute cab task chmod task delete task 2nd DirSet type ear task FileSet type fixcrif task jar task 2nd javac task PatternSet type tar task war task xslt style task zip task includes element ispc task and Matching Task class includeSemanticAttribute attribute xmlproperty task includesfile attribute cab task delete task 2nd DirSet type ear task FileSet type fixcrif task jar task 2nd javac task PatternSet type tar task war task xslt style task zip task includesfile element DirSet type and fileset element and FileSet type PatternSet type and index attribute jar task info command CVS inheritAll attribute ant task 2nd antcall task inheritRefs attribute downloaded from lib ommolketab ir downloaded from libeommolketab ir ant task antcall task init command CVS Init method Ant tasks and Project class Task class initialCR attribute telnet task input attribute apply task exec task java task input task 2nd 3rd inputhandler option inputstring attribute apply task exec task java task installing Ant 2nd Anthill int data type Internet Service Providers ISPs IP addresses 2nd iPlanet element iplanet ejbc task EJB 2nd isfalse element condition task isInvalid method Task class ISPs Internet Service Providers isreference element
104. task is intended to run on which platform downloaded from lib ommolketab ir downloaded from lib ommotketab ir In Example 7 3 two platforms are targeted The build file executes thels command on Linux sending the output tols txt and works on Windows via the dir command sending output to dir txt Example 7 3 Targeting operationg systems ch0O7 targeting build xml lt xml version 1 0 gt lt project default main gt lt target name main gt lt exec dir executable 1s os Linux output 1s txt gt lt exec dir executable cmd exe os Windows 2000 output dir txt gt lt arg line c dir gt lt exec gt lt target gt pro ect Here s what you might see in Linux bash 2 05bS ant Buiiatibe butted smd main BULLD SUCCESSFUL Total time U seconds pash Z2 05bs cat Js txt bid oar Los bAe Here s what you might see in Windows C ant ch0O7 exec gt Pant Buildfile build xml main BUILD SUCCESSEUL Total time 0 seconds C ant ch0O7 exec gt type dir txt Volume in drive C has no label Volume Serial Number is 1512 1722 Directory of C ant ch07 exec 06 25 2004 01 06p lt DIR gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir 06725 2004 017065 lt DIR gt E 0672572004 Q2 02p 311 build xml 06 25 2004 2702p 104 dir Cxt 2 File s 455 bytes 2 DICr sS 29 627 777 024 bytes free 7 2 3 Handling Timeouts You can limit the
105. tasks Table 1 10 shows tasks for working with Starteam source control Table 1 10 Starteam Ant tasks Task name Description STCheckout Checks out files from StarTeam projects STCheckin Checks in files to StarTeam projects STLabel Creates a new label for this project SThist Displays a list of files in the project downloaded from lib ommolketab ir downloaded from lib ommotketab ir Table 1 11 shows tasks for the Continuous source control server Table 1 11 Continuous Synergy Ant tasks Task name Description CCMCheckin Checks in files to the source manager CCMCheckout Checks out files from the source manager CCMCheckinTask Checks in all files in the current task CCMReconfigure Reconfigures an existing command CCMCreateTask Creates a task Finally Table 1 12 lists optional tasks for supporting SourceGear s SourceOffSite Visual Source Safe plug in Table 1 12 SourceOffSite Ant tasks Task name Description Sosget Gets a read only copy of a file Soslabel Creates a label for the current project Soscheckin Checks tn files to the source manager henna Soscheckout Checks out files from the source manager In addition to the built in and the optional tasks Ant supports third party and custom tasks yes that s a large number of tasks you can use As you d expect third party tasks add functionality to Ant as an example take a look at the third par
106. that uses this new selector when copying files in particular it copies over its own source code to a directory named sizeOK Example 12 21 Build file for the new selector ch12 selector build xml Tem version 1 lt 0 77 gt lt project basedix default main gt lt property name srce value src gt lt property name output value output gt lt property name sizeOK value sizeOK gt lt target name main depends jar gt lt copy todir sizeOK gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt fileset dir S src gt lt selector gt lt custom classname ProjectSelector classpath Project jar gt lt selector gt lt fileset gt lt copy gt lt target gt lt target name compile gt lt mkdir dir S output gt lt kdir dir 1260K yo lt javac srcdir S src destdir S output gt lt target gt lt target name jJar depends compile gt lt jar destfile Project jar basedir output gt lt target gt lt project gt Here s what you see when you run this build file Sant Buildfile build xml compile mkdir Created dir home steven ant chl12 selector output mkdir Created dir home steven ant chl12 selector writeable javac Compiling 1 source file to home steven ant chl12 selector output Jar jar Building jar home steven ant ch12 selector Project jar main copy Copying 1 file to home steve
107. the Server The cvs task lets you interact with the CVS server after you ve logged in The attributes of this task appear in Table 6 4 to use this task the cvs command must work on the command line ie the cvs binary must be in your path Table 6 4 The cvs attributes Attribute Description Required Default Specifies whether you want to append output append when redirecting text to a file me Specifies the CVS command you want to i command checkout execute Mo compression The same aS compressionlevel 3 The same as compressionleve1 3 The same as compressionlevel 3 No false Specifies the compression level you want to compressionlevel use via a number between 1 and 9 Any other No false value setS compression false cvsRoot Specifies the cvsroorT variable N No eversh Specifies the cvs_RSH variable No Specifies that you want to use the most recent revision as long as it is no later than the given No date MN Specifies the directory where you want No The project s checked out files to be placed basedir Sends errors to the Ant Log as MSG WARN Cailonerror Stops the build if the task encounters an error No false Specifies that CVS actions should report only noexec No false without changing any files Sends output to the Ant Log as MSG_INFO date Specifies the file where you want error error No messages stored Specifies the file to wh
108. to a given keystore get Retrieves files using FTP HTTP and more from a URL gunzip Unpacks a GZip file so gzip Packs a memacam I oaoa a i file import Allows the use of other Ant files the use of other Ant files Displays a message and reads a line of input from the console allowing for input a e EAT during the build process jar Creates a Creates a JAR archive similar to Java s jar command archive similar to Java s jar command a java Executes the Java interpreter to run a class or application javac Compiles the specified source file s javadoc javadoc2 Invokes the javadoc tool to create documentation loadfile Sets a property file to the entire contents of a text file loadproperties Loans an entire property file into Ant properties macrodef Defines a new task as a macro built up upon other tasks mail Sends SMTP mail messages manifest Creates an archive s manifest file a mermi oa Makes a new directory move rename rename Moves a file to another Moves a file to another directory arallel Contains other Ant tasks that can be run simultaneously by multiple J ava j threads atch Uses the patch command assuming it is on the path to apply diff files to a nn Co file or files fpathconvert Converts paths between platforms downloaded from lib ommolketab ir downloaded from lib ommolketab ir Taskname name Description Defines a new task based on an existing task with certain options
109. to look for classname file or resource map The type of file to look for Set this to a ae directory type dir or a file type file Jale Specifies the value you want to set the property No on to for a successful match 2 1 4 2 Checking file modification dates classname Class to search for file The file to search for The uptodate task sets a property to true under certain conditions In this case the property is set to true if a target file or set of target files is more current than a source file or set of source files You can specify the file you want to check with thetargetfile attribute and the source file that is used to create it with the srcfile attribute If you want to check a set of source files use nestedsrcfiles elements If the target or targets is current based on the source file or files the property whose name you specify will be set to true In this example the property Do Not Build will be set to true if the target file classes jar is current when compared to its source java files lt uptodate property Do Not Build targetfile classes jar gt lt srcfiles dir S src includes java gt lt uptodate gt You can use the wildcard to stand for the current directory and any subdirectory of that directory downloaded from lib ommolketab ir downloaded from lib ommotketab ir which makes it easy to work with a directory hierarchy in depth For example
110. use are in a file namedoptions lt javac srcedir src destdir S build gt lt compilerarg file options gt lt javac gt 3 1 3 Using a Different Java Compiler Using javac you can specify the compiler you want to use with the globalbuild compiler property which affects all javac tasks throughout the build or with the compiler attribute Specific to the current javac task Here s an example lt javac srcedir src compiler javac1 3 destdir S out classpath servlet api jar J gt Here are the possible values for thebuild compiler property or the compiler attribute Glass ic downloaded from lib ommolketab ir downloaded from lib ommotketab ir Specifies that you want to use the standard JDK 1 1 1 2 compiler you can usejavacl1 1 and javacl 2 as aliases extuavac Specifies that you want to use modern or classic in a JVM of its own GC Specifies that you want to use the gcj compiler from gce jikes Specifies that you want to use the J ikes compiler Jvc Specifies that you want to use the Command Line compiler from Microsoft s J ava Visual J You can use microsoft aS an alias ae Specifies that you want to use the kopi compiler modern Specifies that you want to use the JDK 1 3 1 4 1 5 compiler Here you can uSejavacl 3 javacl 4 and javacl 5 as aliases sj Specifies that you want to use the Symantec Java compiler You can USesymantec as an alias downloaded from lib ommo
111. want to use a ae eeeeee Specifies the name of a property where you want No PTOPSTEY the CVS server version to be placed Specifies the directory which holds or will hold a Project s dest No checked out project basedir failonerror Makes the build fail if this task encounters an error No false package Specifies the module you want to check out No CV STOOL downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default serie Specifies the password file you want the task to read y A AS passwords from er Specifies the port used to communicate with the CVS server Port 2401 DOTE ma E downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 6 5 Creating Change Logs This task creates an XML formatted report file of the change logs in a CVS repository If you want to track what s been happening with a module this is the way to do it For example take a look at the build file in Example 6 5 which creates a change log changelog xml for the Greet ingApp module Example 6 5 Getting a CVS change log ch0O6 changelog build xml lt xml version 1 0 gt lt project default main basedir gt lt property name cvs dir value project gt lt target name main gt lt cvspass cvsroot pserver steven STEVE home steven repository password opensesame gt lt cvschangelog dir S cvs dir Greetin
112. xalan j The attributes for this task appear in Table 5 7 Table 5 7 The junitreport task s attributes Attribute Description Required Default Specifies the directory where you want XML formatted The current rod No reports to be written directory tofile Specifies the name of the report file Uae TestSuites xml The junitreport task can contain nested fileset elements junitreport collects XML files generated downloaded from lib ommolketab ir downloaded from lib ommotketab ir by the J Unit task as specified in the nested fileset elements The junitreport task can contain nested report elements These elements are the ones that generate the browseable report based on the merged XML documents The attributes of thereport element appear in Table 5 8 Table 5 8 The report task s attributes Attribute Description Required Default Specifies the format you want to use in the report Must be ormat No frames noframes Of frames 1 Specifies the directory where the task should look for stylesheets If you re using frames format the stylesheet must be named junit frames xsl If you re using noframes format the stylesheet must be named junit noframes xsl todir Specifies the directory where output should be written No Embedded stylesheets styledir The current directory In the build file stest5 target create an XML formatted report for the J Unit tests
113. 1 source file to home steve ch02 properties bin compress jar Building jar home steve ch02 properties bin Project jar main echo echo Compiling and compressing echo downloaded from lib ommolketab ir downloaded from lib ommoltketab ir BULLO SUCCESSFUL Total time 3 seconds The value on the command line overrides both of the values within the build file 2 2 3 Setting Properties Using Environment Variables You can access environment variables with the property element s environment attribute which sets the prefix to use for environment variables env is customary in Ant files after you set that prefix you can reference environment variables by name using that prefix Here s an example build file that displays the value of ANT_HOME lt project default main gt lt property file build properties gt lt property name srce location source gt lt property name output location bin gt lt property environment env gt lt target name main depends init compile compress gt lt echo gt S env ANT HOME lt echo gt lt target gt Here s the result of running Ant using this build file Sant Bulldfile build xml init compile compress main echo echo C ant apache ant 1 6 1 echo BUILD SUCCESSFUL Total time 2 seconds downloaded from lib ommolketab ir downloaded from lib ommotketab ir It s easy to pass environment variables from the comman
114. 4 lt time gt lt antnor gt lt CDATA steven gt lt autcher gt lt file gt lt name gt org antbook ch06 GreetingClass java lt name gt lt revision gt 1 2 lt revision gt lt prevrevision gt 1 1 lt prevrevision gt lt file gt lt msg gt lt CDATA empty log message gt lt msg gt lt entry gt SlucCi lt date gt 2005 06 22 lt date gt lt time gt 16 27 lt time gt lt sucnor gt lt CUATA Se event gt lt aunrncr gt lt file gt lt name gt org antbook ch06 GreetingClass java lt name gt lt revision gt 1 4 lt revision gt lt prevrevision gt 1 3 lt prevrevision gt lt file gt lt msg gt lt CDATA OK gt lt msg gt lt entry gt sentry lt date gt 2005 06 22 lt date gt lt time gt 16 29 lt time gt lt author gt lt CDATA steven gt lt author gt lt file gt lt name gt org antbook ch06 GreetingClass java lt name gt lt revision gt 1 5 lt revision gt lt prevrevision gt 1 4 lt prevrevision gt lt file gt lt msg gt lt CDATA New Version gt lt msg gt lt entry gt lt changelog gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir The attributes for this task appear in Table 6 6 Table 6 6 The cvschangelog task s attributes Attribute Description Required Default Specifies the CVSROOT No variable you want to use Specifies the CVS_RSH Oversn No variable you want to use EET E Specifies for how many days
115. 755 username developer group ant gt lt include name S bin bootstrap sh gt lt include name bin build sh gt lt tarfileset gt lt tarfileset dir S dist username developer group ant gt lt include name S dist gt downloaded from lib ommolketab ir downloaded from lib ommoltketab ir lt exclude name dist sh gt lt tarfileset gt a7 ar Want to un TAR a tar archive Ant has an untar task 4 1 2 Compressing Using gzip and bzip2 The gzip and bzip2 tasks pack files using the GZip or BZip2 algorithms Here s an example that GZip a tar file lt gzip src Project tar destfile Project tar gz gt Here s a similar example that BZips a tar file lt bzip2 src Project tar destfile Project tar bz2 gt Ant supports gunzip and bunzip2 tasks for uncompressing archives The supported attributes for these tasks appear in Table 4 3 Table 4 3 The gzip and bunzip2 tasks attributes Attribute Description Required destfile Specifies the file you want to create Exactly one of destfile Or zipfile ora Specifies the file you want to GZip or BZip Yes zipfile Deprecated Use destfile Exactly one of destfile Or zipfile 4 1 3 Creating ZIP Files The zip task creates ZIP files useful for packaging files for deployment Thezip task is easy enough to use here s how to zip all files in the dist docs directory into docs zip If docs zip doesn t exist downloaded from
116. A comma separated list At least one of tolist List of addresses to send a copy of cclist bcclist or the eclist the email to A comma separated i elements to cc list Or bcc Specifies the character set you want charset to use In the email Specifies the encoding to use encoding Possible values are mime uu plain No auto Or auto Specifies whether you want to stop fail ane oar icicle the build if there are errors mala Specifies files you want to send as attachments Use a comma separated list You can use nested fileset elements Specifies the email address of the Either a from attribute or a sender from element Specifies whether you want to include filename s before file No false contents a ee Specifies the hostname of the SMTP No E TE server asnpor Specifies the TCP port of the SMTP No oe server to use nessaae Specifies the email s body One of message messagefile Or a message element Specifies a file to send as the email s One of message messagefile messagefile body Or a message element EAEE E E Specifies the type of the message s ET content Yes if SMTP authorization is required on your SMTP server replyto Specifies the reply to address No ssl Specifies if you want to use TLS SSL No files inc ludetilenames Specifies the password for SMTP assword i j authorization downloaded from lib ommolketab ir downloaded fr
117. Ant rpm Builds Linux RPM installation files scp Moves files to and from a remote SSH server saript Executes an Apache BSF script downloaded from lib ommolketab ir downloaded from lib ommolketab ir Task name Description Scripdef Defines Ant tasks from scripts a serverdeploy fan Ys eee ef sere Runs a hot deployment tool for a J 2EE server fsetproxy Configures web proxy properties web proxy properties Seca After a build plays a sound file letting you know whether the build succeeded or aa enan SSS splash Displays a splash screen a splash screen sshexec Executes a command on a remote server using SSH stylebook Uses Apache Stylebook to generate book documentation symlink Makes deletes or edits Unix symbolic links telnet Controls a Telnet session from ANT test Executes a J Unit test translate Translates keywords in files using values in resource bundles vajload Loads files for Visual Age for Java source control vajexport Exports packages for Visual Age for Java source control vajimport Imports files for Visual age for Java source control wljspe Compiles JSP pages using Weblogic s JSP compiler xmlvalidate Validates XML files and reports any errors In addition to these tasks specific Ant tasks for NET are shown inTable 1 5 Table 1 5 NET Ant tasks Task name Description Csc Invokes the C compiler vbc Invokes the VB NET compiler jsharpe Invokes the
118. Ant from the command line is simple sant options target target2 target3 1 5 1 Command Line Options options are one or more of the command line options that begin with a hyphen listed inTable 1 14 target target2 etc are the specific targets you want to run in the event you don t want to defer to the project element s default target Entering ant help on the command line generates a list of command line options Table 1 14 Ant command line options Name Description ee ee ee Runs the build file specified by file file file Dproperty value Sets a property called property with a value of value and passes it to Ant debug d oo oi Prints debugging information d Lagnostics i I Prints diagnostics about Ant emacs e creates plain emacs friendly logging information Searches for the build file named file along the directory find file OF S file structure towards the root help h a Prints help information downloaded from lib ommolketab ir downloaded from lib ommolketab ir Name Description i handl Hl z l A there nee Specifies the class that will handle user text input keep going K Continues to execute targets even if prior targets fail Only targets that do not depend on failed targets are attempted 1 file Or 1 file Uses file to log to lib path Specifies the classpath on which to search for J ARs and library classes Adds an in
119. Before using the build files for this chapter in the downloadable code make sure you replace the cvsroot attribute value or the cvsrooT environment variable with an appropriate value for your CVS server After running this build file the project directory will hold the checked out module including a CVS downloaded from lib ommolketab ir downloaded from lib ommotketab ir project file and a CVS directory which holds logging and tracking information You re free to work with the code that s been downloaded and when you want to commit the project back to the CVS server specify the same directory you downloaded the project to 6 3 2 Updating Shared Code When you want to update your local copy of a module from the CVS repository you can use the update Command You can see how that works in Example 6 2 as before you can omit the cvspass task if your password is in the cvspass file though it causes no harm to leave it in Example 6 2 Updating a CVS module ch0O6 update build xml lt xml version 1 0 gt lt project default main basedir gt lt property name cvs dir value project gt lt target name main depends login update gt lt echo gt Updating 44 lt echo gt lt targat lt target name login gt lt cvspass cvsroot pserver steven STEVE home steven repository password opensesame gt lt target gt lt target name update depends login gt lt cvs dest S cvs dir com
120. Curent verssor Force Buld Rule Build ae Version i An varsinn 1 7 0 162 Anthill will download the code for this project from the Anthill CVS server and build it The Anthill consol will reappear click Refresh to verify that the project has been built A green box should appear at right CVS Anthill Example line in the console table as shown in Figure 4 3 if the build was successful Figure 4 3 Running a new build downloaded from lib ommolketab ir downloaded from lib ommolketab ir If you click the CVS Anthill Examplehyperlink in the console now you ll get access to the results of the as shown in Figure 4 4 Figure 4 4 Build artifacts of Direcbory Listing for PLYS _Anthill Laample Moroso Intemet Explores File Edt ew Faries Took Help Haak e G A Geach ironies Beds GF Ly BSA tin pees Arh E o Unks i Customize Lr Directory Listing for CVS_Anthill Example Subdirectories dovwenbo scl 25 Jun AU 12 19 16 java harnll 20s Jn 20 11916 poetrica 26 Jun 2000 12 19 16 tedi 25 Jun 00 1219 12 p Agui 11910 teste 26 Jun 2004 12 19 08 byildLogs 29 Jun J00d 12 19 02 CS Ex ets 1 Li 1 454 KB 25 Jun d00d 12 19 08 Arithil E x ample 1 rar 1 42 KE Agum AA 1 TS UG a es The tests hyperlink links to the results of J Unit tests and the buildLogshyperlink links to the build log H what the build log looks like all compile mkdir Created dir D ant
121. DY gt lt xsl apply templates gt lt BODY gt lt HTML gt lt xsl template gt lt xsl template match state gt lt P gt lt xsl value of select name gt lt P gt lt xsl template gt lt xsl stylesheet gt Here s the resulting HTML document lt HTML gt lt BODY gt lt P gt California lt P gt lt P gt Massachusetts lt P gt lt P gt New York lt P gt lt BODY gt lt HTML gt The attributes of this task appear in Table 9 6 downloaded from lib ommolketab ir downloaded from lib ommolketab ir If you are using JDK 1 4 or higher this task doesn t require external libraries If you re using an earlier JDK you ll need Xalan from http xml apache org xalan j index hAtml or another XSLT processor and Ant s optional jar Table 9 6 The xslIt style task s attributes Attribute Description Required Default Specifies the directory to search for the S basedir basedir No source XML file Specifies the classpath to use when es searching for the XSLT processor me T TE Specifies the classpath to use given as a No reference Default excludes are used Specifies if you want to use default excludes or not Set to yes no defaultexcludes Yes unless in and out Specifies the directory in which you want destdi more to store the results have been Specified Specifies the patterns matching files to excludes exclude aS a c
122. File In the File Name box enter build xml and click Finish adding this new file to the AntExample project To JAR the output of this project enter this XML in the build file lt xml version 1 0 gt lt project default main gt lt target name main depends compile compress description Main target gt lt echo gt Building the jar file lt echo gt lt target gt lt target name compile description Compilation target gt lt javac srcdir org antbook gt lt target gt lt target name compress description Compression target gt lt jar jarfile Project jar basedir org antbook includes class gt lt target gt lt l project gt After entering this XML save the new build file The Eclipse support for Ant is evident build xml appears in the Package Explorer at left with an Ant icon and the syntax in the build file is colored witt XML declarations in one color attribute values in another and Ant keywords in another as shown ir glorious black and white in Figure 11 3 The targets of this build file appear at right in the Outline view Figure 11 3 An Ant build file in Eclipse downloaded from lib ommolketab ir downloaded from lib eommolketab ir e aml wersion 1 0 7 gt projecit default msin gt j prayer target nanme sain depend compile HA man defaut Techo H onpi Building the jar file compress lt cha gt zF LAGEL itargzt name compile descrciption
123. JVM 2nd jvmarg elements and format attribute report task taskdef task Format command Eclipse 2nd format element tstamp task formatter element junit task 2nd formatter task formatting Ant build files test results forward slash 2nd 3rd 4th forwardslash attribute apply task from attribute glob mapper and mail task mapper element regular expressions and 2nd slashes and from element mail task fto task 2nd 3rd 4th FIP remote deployment fto schema fullpath attribute tarfileset element zipfileset element 2nd 3rd downloaded from lib eommolketab ir downloaded from lib ommotketab ir downloaded from lib ommolketab ir downloaded from libeommolketab ir Index A B C D E F G H H J K L M N O P Q R S O U M W RX 2 generic element serverdeploy task 2nd genericjarsuffix attribute ejbjar task weblogic element genkey task get task 2nd 3rd getBaseDir method Project class getBuildListeners method Project class getDefaultInoutStream method Project class getDefaultTarget method Project class getDescription method Project class Task class getElementName method Project class getincludedFiles method DirectoryScanner class getLocation method Task class 2nd getName method JUnit framework Project class getOwningTarget method Task class getProject method Task class getProperties method Project class System class ge
124. Linux parsing buildfile home build xml Project base dir set to home Build sequence for target main is compile compress main Complete build sequence is compile compress main clean compile javac Project class skipped don t know how to handle it javac Project jar skipped don t know how to handle it javac Project jJava omitted as Project class is up to date javac build xml skipped don t know how to handle it compress jar Project class omitted as Project class is up to date main echo echo Building the jar file echo BUILD SUCCESSFUL Total time 1 second This output shows that Ant is skipping up to date output targets Here s similar output in Windows cant verbose Apache Ant version 1 6 1 compiled on February 12 2004 B ildfile build xml Detected Java version 1 4 in C jdk1 4 Detected OS Windows 2000 parsing buildfile C ant ch0Ol build xml with URI file C ant ch01 build xml Project base dir set to C ant ch0l Build sequence for target main is compile compress main Complete build sequence is compile compress main clean compile javac Project class skipped don t know how to handle it javac Project jar skipped don t know how to handle it javac Project java omitted as Project class is up to date javac build xml skipped don t know how to handle it compress jar Project class omitted as Project class is up to date main
125. ML gt lt HEAD gt lt TITLE gt Creating a Greeting lt TITLE gt lt HEAD gt lt BODY lt H1l gt Creating a Greeting lt H1 gt lt out prantin Helle from JSP gt Display the greeting T gt lt BODY gt lt HTML gt Example 8 5 shows how to compile this JSP into greeting java Example 8 5 Compiling J SP pages ch08 jspc build xml lt xml version 1 0 gt lt project default main gt lt property name message value Compiling the JSP gt lt property name sre location source gt lt property name output location bin gt lt target name main depends init compile gt lt echo gt S message lt echo gt lt target gt lt target name init gt lt mkdir gag foro gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt target gt lt target name compile gt zjape srecdi7 S terc destdir S output package org antbook jsp verbose 9 gt lt include name jsp gt lt 1opCc gt lt target gt project Here s what you see when you run the build file Sant Buildfile yi Je i i compile jspc Compiling 1 source file to home steven ant ch08 jspc bin org antbook jsp jasperc 2004 06 30 02 20 09 Class name is greeting jasperc 2004 06 30 02 20 09 Java filename is hnome steven ant ch08 jspc bin org antbook jsp greeting java jasperc 2004 06 30 02 20 09 Accepted org apache jas
126. Player soundplayer new AntSoundPlayer public SoundListener soundplayer addBuildSuccessfulSound new File filel wav 1 new Long 500 soundplayer addBuildFailedSound new File file2 wav 1 new Long 500 public void buildStarted BuildEvent event public void buildFinished BuildEvent event soundplayer buildFinished event public void tarde starved builebvyent event ij PubplIC VOLO Taroelriniened buLleevenc event 1 PUDLICG void task tartead BuildEvent event 1 public void taskFinished BuildEvent event public void messageLogged DulldEvent event il To build this listener includeant jmf jar in the classpath to pick up AntSoundPlayer Here s the file this example builds Project java public class Project public void execute downloaded from lib ommolketab ir downloaded from lib ommotketab ir system out printin No worries Here s the build file Nothing special lt am Vereion i gt lt project basedir default main gt lt property name sre value src gt lt property name output value output gt lt target name main depends jar gt lt taskdef name project classname Project classpath Project jar gt lt project gt lt target gt lt target name compile gt lt mkdir dir 0utput gt lt javac srcdir src destdir S output gt lt target gt lt target name jar depends compile gt lt j
127. SUCCESSFUL Total time 1 second Want to work with Ant types like filesets in script Use theproject object s createDataType method Here s an example that creates Java File objects from a fileset all in JavaScript imoorcClass java it F Le fileset project createDataType fileset fileset setDir new File dir fileset setIncludes includes directory Caner fi lesersger Direc ory ocanner pro jJecL files directoryscanner getIncludedFiles for loopiIndex 0 loopIndex lt files length loopIndex var filename files loopIndex var file new File fileset getDir project filename downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 12 3 Creating Custom Listeners Ant tracks build events such as when tasks start and finish and you can catch those events with a listener Listeners implement the org apache tools antBuildListener Interface and will receive BuildEvents for these events e Build started e Build finished e Target started e Target finished e Task started e Task finished e Message logged To add a listener in code you can create an antProject object and then call itS addBuildListener method to add a listener to the project You can attach a listener to a build from the command line a in this example ant listener org apache tools ant XmlLogger which runs Ant with a listener that generates an XML version of the build progress Listeners and logge
128. T 2000 and XP OS 2 Warp Novell Netware 6 and MacOS X When you run Ant on this first build file here s what you d see in Unix using thebash Shell bash 2 05bS ant Buildfile build xml compile javac Compiling 1 source file compress jar Building jar home httpd vhosts builder Project jar main echo echo Building the jar file echo BUILD SUCCESSFUL Total time 2 seconds You ll get the same results in any supported operating system For example here s what you d see ir Windowsverything except the build time is identical Ce ant chol gt zant Bulldfile build xml compile javac Compiling 1 source file compress jar Building jar C ant ch01 Project jar main echo echo Building the jar file echo BUILD SUCCESSFUL Total time 4 seconds For the most part Ant builds are independent of operating system and for that reason s is used as a generic command prompt in this book If anything is operating system dependent it will be listed explicitly When Ant finishes executing the build file you ll havebuild xml Project java the compiled Project class and Project jar all in the same directory Project jar will contain a manifest file and Project class Fortunately Ant handles 10 20 or 100 source files in this same way making your life easy at build time downloaded from lib ommolketab ir downloaded from lib ommoltketab ir downloaded from lib ommolketab ir
129. T employee name hiredate projects gt lt ELEMENT name lastname firstname gt lt ELEMENT lastname PCDATA gt lt ELEMENT firstname PCDATA gt lt ELEMENT hiredate PCDATA gt lt ELEMENT pro jects project gt lt ELEMENT project product id price gt lt ELEMENT product PCDATA gt lt ELEMENT id PCDATA gt lt ELEMENT price PCDATA gt gt COCument gt lt employee gt lt name gt lt lastname gt Kelly lt lastname gt xi irstcnhame gt Grace lt s firstnamne gt lt name gt downloaded from lib ommolketab ir downloaded from lib eommolketab ir lt hiredate gt October 15 2005 lt hiredate gt lt projects gt lt projyect gt lt produ uct gt Printer lt product gt sid Lik 7 lt price gt 111 00 lt price gt lt s project gt lt project gt sprod c Laptop product gt 102225740 lt price gt 989 00 lt price gt lt project lt projects gt lt employee gt lt employee gt lt name gt lt lastname gt Grant lt lastname gt lt firstname gt Cary lt firstname gt lt name gt lt hiredate gt October 20 2005 lt hiredate gt lt projects gt lt project gt lt product gt Desktop lt product gt Lid 3354 10 lt price gt 2995 00 lt price gt lt I project lt project gt product gt Scanner lt produc i gt ic 424 7 10 gt lt price gt 200 00 lt price gt lt oro eee A Gro octe lt employee gt lt employee gt lt name gt
130. Time elapsed 0 04 sec tees junit Running org antbook Project junit Tests run 3 Failures 0 Errors 0 Time elapsed 0 04 sec COSCE Junit Running org ancbook Proj ject junit Tests run 3 Failures 0 Errors 0 Time elapsed 0 01 sec junitreport Using Xalan version Xalan Java 2 4 1 junitreport Transform time 1191ms test echo echo Tested OK echo compress jar Building jar home ant ch05 junit jars Project jar deploy mkdir Created dir home ant ch05 junit user copy Copying 1 file to home ant ch05 junit user main echo echo Building the project echo BUILD SUCCESSFUL Total time 7 seconds Because all tests ran successfully the build was allowed to continue on to deployment downloaded from lib ommolketab ir downloaded from lib ommotketab ir 5 5 Extending JUnit There are many extensions for J Unit designed to help test specific types of builds such as web applications You can find many extensions on the J Unit site at http www junit org news extension index htm Here s a starter list of J Unit extensions e Abbot is a scripted Java GUI testing framework e dbUnit is a database testing framework which sets up your database before executing your tests e HtmlUnit is a Java unit testing framework for testing Web based applications e HttpUnit is a framework for accessing websites from a Java program with support for following links submitting form
131. Version 1 0 Ant Version Apache Ant 1 6 1 Created By 1 4 2_03 b02 Author Steven Holzner Name Shared Title Example Vendor MegaAntCo Build 3 Date June 10 2005 Name Copyright Copy C MegaAntCo 2005 This task has only one attribute prefix which is optional and sets a prefix for theDSTAMP TSTAMP Microsystems Inc and Topay properties For example if prefix time these properties will be time TSTAMP time TSTAMP and time TODAY allowing you to name the properties created by this task yourself at least to the extent of calling giving them names like name TSTAMP instead of just TSTAMP The tstamp task Supports a format nested element that lets you set the date and time format Here s an example that creates a timestamp in the property timestamp lt ECSCANp lt POrmar property timestanp petrern MM od yyyy hiim ga lt tstamp gt You can see the attributes of the format element in Table 3 12 The date time patterns used by format are the same as used by the Java SimpleDateFormat Class For more info on those patterns see http java sun com j2se 1 4 2 docs api java text SimpleDateFormat html downloaded from lib ommolketab ir downloaded from lib ommolketab ir Table 3 12 The format task s attributes Attribute Description Required Specifies the locale for the date time string Make this of thelanguage locale No country variant The possible values are defined i
132. Yes Fests downloaded from lib ommolketab ir downloaded from lib ommotketab ir 6 6 Finding Changes Between Versions The cvstagdiff task generates an XML formatted report file of the changes between two tags or dates recorded in a CVS repository Here s an example that creates a report datediff xml for all the changes that have been made in theGreetingApp module in January 2005 lt cvatagdiri destfile datediff xml package GreetingApp startDate 2005 01 01 endDate 2005 31 01 JF You can see the attributes of this task inTable 6 8 Table 6 8 The cvstagdiff task s attributes Attribute Description Required Default Specifies the compression you want to use Set to compression true false or a number 1 9 for compression No level Specifies the CVSROOT cvsroot No variable you want to use Specifies the CVS_RSH voran No variable you want to use estie sestine Species the file where the report should be stored Sets the latest date for differences to still be One of the endtag enddate included in the report or enddate Bees Sets the latest tag for differences to still be One of the endtag included in the report or enddate No compression downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default Makes the build fail if this task encounters an failonerror error false No Specifies the module you want t
133. a new object of the custom datatype and displays the files in it Sant B ildfile buabdsxml compile javac Compiling 3 source files to home steven ant ch12 type output jar jar Building jar home steven ant ch12 type Project jar downloaded from lib ommolketab ir downloaded from lib ommotketab ir main projectTask ed txt projectTask george txt BUILD SUCCESSFUL Total time 3 seconds Customizing data types for use with custom tasks can be a powerful technique as you develop and extend Ant to better fulfill your needs downloaded from lib ommolketab ir downloaded from lib ommotketab ir Team LiB Colophon Our look is the result of reader comments our own experimentation and feedback from distribution channels Distinctive covers complement our distinctive approach to technical topics breathing personality and life into potentially dry subjects The animal on the cover of Ant The Definitive Guide Second Edition is a horned lizard There are 1 Species of the horned lizard in North America Horned lizards prefer a dry warm climate such as the desert or a dry woodland and they can be found in Texas Oklahoma Kansas and New Mexico Adults grow to 3 5 inches They depend on their environment to control their body temperature and use burrows and shade to prevent overheating The horned lizard has a wide flat body ideal for desert camouflage and a short neck and short legs It has spines
134. ab ir java java Time 0 01 java OK 3 tests Each dot indicates a test case that s running and three test cases are in the example As you can see from the last line the tests all passed OK but this isn t exciting and it doesn t stop a build if there s a problem 5 2 1 Using the Plain Formatter for Reports The second test test2 will use junit to run the test No results are printed out by successful J Unit tests unless you use a formatter so the plain formatter is used here set by aformatter element classpath IS used to specify where junit should search for the class to test and thetest nested element sets up the test giving the name of the class to test and the directory in which to store the formatted results of the test lt target name test2 depends compile gt lt junit printsummary yes errorProperty test failed failureProperty test failed haltonfailure yes gt lt formatter type plain gt lt classpath path gt lt test todir results name org antbook Project gt lt junit gt lt fail message Tests failed if test failed gt lt target gt Note that if you set haltonfailure to true the build will halt if the test failswhat to do if you want to avoid deploying a defective build You can use attributes like errorProperty Instead of haltonfailure to set properties indicating the build had problems That s useful if you want to clean up after the partial build with othe
135. ab ir Buildfile bull main war Building war home steven ant ch08 war login war BUILD SUCCESSFUL Total time 2 seconds That creates the war file Besides packaging the files specified Ant supplies a default manifest file Manifest mf in the resulting war file which contains these contents Manifest Version 1 0 Ant Version Apache Ant 1 6 1 Created By 1 4 2_03 b02 Sun Microsystems Inc After you create your war file you can deploy it by copying it to your web server s deployment directory such as to the webapps directory in Tomcat The attributes of the war task appear in Table 8 1 The war task is a shortcut for specifying the particular layout of a war file The same thing can be accomplished using theprefix and fullpath attributes of zipfilesets in a zip Or jar task Table 8 1 The war task s attributes Attribute Description Required Default Specifies the source directory for files to include basedir No in the compressed file PEN Specifies you want to not only store data but No eae compress It Default No excludes are used je faultexcludes SPecifies if you want to use default excludes or not Set to yes no Exactly one of destfile Specifies the WAR file you want to create destfile or warfile Specifies what to do if a duplicate file is found duplicate Valid values are add preserve and fail Specifies the character encoding to use for Sens Fred in the WAR file x E une
136. ads the header that is the first few lines from the filtered data Supports two optional attributes lines number of lines to read and skip number of lines from the beginning to skip headfilter Filters out those lines that don t include lines that contain specified strings 1 ae One required attribute contains the substring to search for Filters out lines that don t contain text matching specified regular expressions ti eee ro 7 E attribute regexp Pattern of the substring to be searched for prefixlines Adds a Adds a prefix to every line Required attribute prefix the prefix to use to every line Required attribute prefix the prefix to use pon eae n Filters text and replaces text between begintoken and endtoken with the text replacetokens you specify stripjavacomments Strips Java comments Java comments Strips line breaks from the filtered data Set the optionallinebreaks attribute striplinebreaks to the line break text PEE EE EET EE E Filters out lines that start with comments as you specify Set thecomment ana liess to the a that starts the line ftabstospaces Filters out tabs and Filters out tabs and replaces them with spaces default is 8 00 them with spaces default is 8 Reads the tail of the text that is the last few lines from the filtered text Supports two optional attributes lines number of lines to read and skip number of lines from the end to skip tailfilter
137. ages it into an ear file for deployment Example 8 6 A J boss EJB build ch08 ejb build xml lt xml version 1_ 0 7 gt lt project default main basedir gt lt target name main depends init compile war ear gt lt target name init gt lt property name src value basedir src gt lt property name bin value basedir output gt lt property name web value basedir web gt lt property name descriptors value S basedir output deploymentdescriptors gt lt property name eardir value S basedir output ear gt lt property name wardir value S basedir output war gt lt property name warfile value app war gt lt property name earfile value app ear gt lt mkdir dir S wardir WEB INEF gt lt mkdir dir wardir WEB INF classes gt lt mkdir dir S eardir META INE gt lt target gt lt target name compile gt lt javac destdir S bin srcdir S srce includes java gt lt targer gt lt target name war gt lt copy todir wardir gt lt fileser Gair Siweb ancludes J gt lt Copy gt lt copy file S descriptors web xml todir wardir WEB INF gt lt copy todir wardir WEB INF classes gt lt fileset giv Sioint includasg 4 class 7 gt lt copy gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt jar jarfile S eardir S warfile basedir S wa
138. ain nested fileset elements By now this should be old hat to you 4 1 6 Setting Creation Time and Date When you re deploying files you can set the creation date and time of those files to a single value to make the deployment look more professional as you ll usually see with commercial software The touch task will do this for you besides setting the creation time and date for a single file you can do the same thing for whole directories of files if you include a fileset If you only specify a single file its modification time and date is set to the current time and date lt touch file Project jar gt Here s an example that sets the modification time and date of all the files ins src to January 1 2005 at 5 00 PM lt touch datetime 01 01 2005 5 00 pm gt lt Tidese dir are sJ couch If the file you re touching doesn t exist touch will create it for you which is one of the few ways you can use Ant to create empty files you can create files with text in them with the echo task using the file attribute Want to give the file a name that s guaranteed to be unique Use Ant Stempfile taskfor example lt tempfile property temp file gt Will store the unique name of a file in the temp file property and lt touch file temp file gt will create that file You can see the attributes of this task in Table 4 8 Table 4 8 The touch task s attributes Attribute Description Required Specifies the new modi
139. ains string S build type substring gold gt lt j or gt lt isfalse value S explicitly include debug info gt lt and gt lt condition gt Here s another example which sets the property use property file true If the files build properties and version properties are available or if the file core jar is not current lt condition property use property file gt LOL lt and gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt available file build properties gt lt available file version properties gt lt and gt lt O lt uptodate srcfile core java targetfile core jar gt lt not gt lt a gt lt Cong taon gt 2 1 2 Performing Conditional Actions Actions can be conditionally executed based on two factors if a certain condition has been met usin the if attribute and if a certain condition has not been met using theunless attribute You can determine if a task runs using if and unless to check the values of properties Three elements Support if and unless attributes target patternset which can group file matching patterns like x java class and so on See Working with Patterns in this chapter fail target Is the simplest as shown here lt target name buildModule if code complied OK gt lt target gt The buildModule target is executed only if the code complied oK property Is true Example 2 1 demonstrates the unless attribut
140. ally Here s an example lt filelist 1d docfiles di r s7cdec files type html using html gt You can see the filelist attributes in Table 2 11 FileLists are not supported by as many tasks as FileSets are You might try using a FileSet with nested filename elements to add individual files to the FileSet Table 2 11 The filelist type s attributes Attribute Description Required dir The base directory you want to use for this file list Yes files A comma separated list of filenames to include in the file list Yes l 2 3 5 Working with Patterns A powerful way of working with multiple files is to use patterns such as the pattern java which will match all files with the extension java class which matches files with the extension class and so on If you want to work with multiple patterns simultaneously in Ant patterns can be groupec into sets and later referenced by their id attribute These sets are defined with the patternset type which can appear nested into a FileSet or an implicit FileSet Here s an example where I m creating a file set using a pattern set that will match all of a project s downloaded from lib ommolketab ir downloaded from lib ommotketab ir documentation files excluding beta documentation lt fileset dir src casesensitive yes gt ADalLlLernisel gt lt include name docs html gt lt include name prof atml if professional gt lt
141. amount of time you want to wait for an external program to execute by setting the timeout attribute to a millisecond value If the timeout is reached and the program hasn t returned it s killed and the java tasks s return value will be 1 In that case the build will halt iffailonerror is true Here s an example lt xml version 1 0 gt lt project default main gt lt target name main gt lt exec dir executable databaseConnect timeout 100 failonerror true gt lt target gt lt project gt 7 2 4 Executing Shell Commands How about shell and batch scripts In Unix executing shell scripts is no problem Assign the executable attribute the name of the script In Windows it s a different story To execute a batch bat file execute the command line processor cmd exe and pass the name of the batch file using an arg nested element and the c switch lt exec dir executable cmd os Windows 2000 gt lt arg line c backup bat gt lt exec gt If you re running a Unix like shell in Windows execute the command shell sh and use the c switch which sends the output to a file lt exec e xecutable bin sh gt lt arg value c gt lt arg value run sh amp gt results gt lt exec gt 7 2 5 Checking for External Programs Before Executing Them When you start launching external programs ensure the desired programs are available before downloaded from lib ommolketab ir dow
142. an example using serverdeploy to deploy to a JOnAS server downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt serverdeploy action deploy source S eardir app jar gt lt jonas server JOnAS5 Jjonasroot S jonas root gt lt Classpati lt pathelement path jonas root lib RMI_jonas jar gt lt classpath gt lt jonas gt lt serverdeploy gt downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Chapter 9 XML and XDoclet XML support is built into Ant and not only as far as build files go You can validate XML documents using XML DTDs and schemas using the xmlvalidate task You can read properties from an XML document using xmlproperty You can use the xslt style task to transform XML documents using XSLT And you can use the antstructure task to generate an XML DTD for all the tasks Ant knows about Besides covering these and other XML tasks I m going to discuss XDoclet in this chapter XDoclet is an open source code generation engine that is designed to run in Ant Using codes that you embed ir Java source code XDoclet can generate code deployment descriptors such asweb xml and other artifacts for Web and EJB applications l Il also round out the discussion of EJB from the previous chapter by discussing the Ant EJB tasks a specially designed set of optional tasks for developing Enterprise JavaBeans EJ Bs downloaded from lib ommolketab ir downl
143. and exec task and 2nd 3rd executing shell commands downloaded from lib eommolketab ir downloaded from lib eommoltketab ir filename lengths installing Ant scheduling automatic builds spaces in username verbose build windowtitle attribute javadoc task wiclasspath attribute weblogic element wiclasspath element weblogic element wljspc task wlrun task EJB 2nd 3rd wlstop task EJB 2nd write element WsdlToDotNet task downloaded from lib eommolketab ir downloaded from lib ommolketab ir Index A B C D E F G H H fy K L M N O P Q R S CO U V W X Z Xalan processor 2nd XDoclet 2nd XML documents 2nd 3rd XML files XML formatter 2nd 3rd XML transforming xmicatalog element 2nd XMLCatalog type xmlproperty task 2nd 3rd xmlivalidate task 2nd XSLT 2nd xslt task 2nd 3rd downloaded from lib ommolketab ir downloaded from lib ommotketab ir Index A B C D E F G H 1 fy K L M N O P Q R S M U V W RX Z zip task description ilink task and overview war files and zipfileset element and 2nd zipfile attribute gzip bzip2 tasks zip task zipfileset element attributes ear task and war task and zip task and ZipFileSet type zipgroupfileset element downloaded from lib ommolketab ir
144. ang String message long Tests if two lon r expected long actual ests O IONS are equa static void assertEquals java lang String message java lang Object expected java lang Object actual Tests if two objects are equal static void assertEquals java lang String message short J 2 4 a Tests if two shorts are equal expected short actual Static void assertEquals java lang String expected Tests if two Strin r Java lang Cring actual Sana OS go te See Static void assertEquals java lang String message Tests if two Strin r jJeVes Lond olrlin expected Ja avd lang tring Actual Sana OS gs are equa static void assertFalse boolean condition Tests if a condition is false static void assertFalse java lang String message boolean a a J a Tests if a condition is false condition static void assertNotNull java lang Object object Tests if an object isn t null Static void assertNotNull java lang String message java lang Object object Tests if an object isn t null Tests if two objects do not refer to the same object Static void assertNotSame java lang Object expected java lang Object actual static void assertNotSame java lang String message Tests if two objects do not java lang Object expected java lang Object actual refer to the same object static void assertNull java lang Object object Tests if an object is null
145. ant sent MailLogger mailhost Specifies the mail server to use default localhost MailLogger port Specifies the default port for SMTP default 25 MailLogger from Specifies the mail from address required MailLogger failure notify Specifies if to send on failure default true MailLogger success notify Specifies if to send on success default true MailLogger failure to Specifies the address to send failure messages to required if failure mail to be sent MailLogger success toSpecifies The address to send success messages to required if success mail to be sent MailLogger failure subject Specifies the subject of failed build default Build Failure downloaded from lib ommolketab ir downloaded from lib ommotketab ir MailLogger success subject Specifies the subject of successful build default Build Success 4 3 7 Setting File Protections with chmod The chmod task changes the permissions of a file or files and it s useful in deployment after you ve got your files deployed in case you need to set file permissions You set the permissions in Unix style just as the arguments for the Unix chmod command Here s an example that makes run sh readable writable and executable for the owner on a Unix system and readable and executable for others lt chmod file S dist run sh perm 755 gt This makes all sh files in and below s dist readable and executable for anyone on a Uni
146. ant to create links to the No Javadoc output at the given URL Specifies you want to link to the linkoffline documentation at a specific URL using a No package list at at another URL Indicates you want to generate linksource hyperlinks to source files available No no since Ant 1 6 Sets the locale to be used for locale generating documentation such as No en US Specifies you do not want to include nodeprecated deprecated information in the No generated documentation P E E T Specifies you do not want to generate a No deprecated list downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default Specifies you do not want to generate a aaa link to help documentation poses Specifies you do not want to generate soreness you don t want a navigation Allows you to use the noqualifier argument Set this attribute to all or a colon separated list of packages Available since Ant 1 6 pees Specifies you don t want a class No hierarchy to be generated Specifies you want to generate output using J DK 1 1 Specifies where to get the overview overview documentation P Indicates you want to include No package protected public information Specifies the name of a file that holds the packages to include in the No generated documentation packagenanes Specifies a list of packages to include No ee Specifies you want to show all
147. ar destfile Project jar basedir output gt lt target gt lt project gt To attach the listener to the build run Ant this way Zant listener SoundListener If the build finishes successfully you ll hear the sound you ve added for a build otherwise you ll hea the sound you ve set for failure Want to Know what task or target fired a build event Use theBuildEvent object s getTask OF getTarget methods in which a BuildEvent object is passed to each listener method downloaded from lib ommolketab ir downloaded from lib ommotketab ir 12 4 Creating Custom Loggers You can handle build events with custom loggers as well if you extend the AntDefaultLogger class Example 12 17 shows a logger that will log each task as it s executed Like listeners loggers must not access System out and System err directly so to display messages to the standard out device this code uses the Ant log method which defaults to standard out Example 12 17 A new logger ch12 logger ProjectLogger java import org apache tools ant BuildEvent import org apache tools ant DefaultLogger import Org edpaecie TOOlLS ant 20011 SscringUciiS public class ProjectLogger extends DefaultLogger public void taskStarted BuildEvent event String text Running task event getTask SeEPinguciis LINE EF printMessage text out event getPriority log text For this example use a simple custom task p
148. arentheses in the regular expression in thefrom attribute can be referenced in the to attribute as 1 a match to a second pair of parentheses may be referenced as 2 and so on Copy todir Dackup gt lt fileset dir development includes java gt lt mapper type regexp from a z java to l backup gt lt 7 Copy gt Another mapper is the flatten Mapper which lets you copy files while stripping off any directory information from the filenames That s how mappers typically work you specify a file set and then add a mapper to refine or manipulate the set of files you want to work with To use a mapper you use the Ant mapper element which has the attributes you see in Table 2 17 The mapper classpath attribute holds a path which means you can use a nested classpath element if you prefer Table 2 17 Mapper attributes Attribute Description Required Default classname Specifies the mapper using a class name Either type or classname E Specifies the classpath you want used when No searching for classname classpathref Specifies the classpath to use No from Sets the value of the from attribute Depends an implementation to Sets the value of the to attribute Depends an implementation Either type or type Specifies a built in mapper classname Experience shows that Ant will not automatically convert or characters in the to and from attributes to the correct directory separator for you
149. arget Target target Specifies the target that contains this task void Sets the wrapper class that should be used setRuntimeConfigurableWrapper RuntimeConfigurable runtime configuration wrapper Specifes the task name use for logging messages void setTaskTyp e Java lang String type Specifies type of task in string format void setTaskName java lang String name 12 2 1 The Task Life Cycle Tasks go through a well defined life cycle and here are the specific stages 1 The task is instantiated using a no argument constructor 2 The task s references to its project and location inside the build file are initialized via inherited proj and location variables 3 If the user specified anid attribute in this task the project registers a reference to this newly creat task 4 The task gets a reference to the target it belongs to through its inherited target variable 5 The init method is called to initialize the task 6 All child elements of the task s element are created through the task Screatexxx methods or instantiated and added to this task with its addxxx methods 7 All attributes of this task get set via their correspondingsetxxx methods 8 The character data sections inside the task s element are added to the task using itSaddText method if there is one 9 All attributes of all child elements get set using theirsetxxx methods 10 The execute method is call
150. ater this task supports any URL schema including http ftp jar and httg This task is great if you want to download online content or as in this case issue commands via URLs t online code Before getting to deployment here s an example that usesget to retrieve the Ant home page and stores in ant Atm lt get srce http ant apache org dest ant html gt You can upload Web applications to Tomcat using the manager servlet passing the local location of the application to upload For example to upload a Web application fromC ant ch08 app in Windows you d this location filet 7Ci ant Co a0 To upload a war file you add an at the end of the location to indicate you re uploading a file not the contents of a directory like this in Unix jaretilet 7 ances cn0e apn wari Example 8 3 shows how this works in practice In this case the build file deploys a Web application fron C ant deploy app that consists of a servlet org antbook ch08 Deploy that displays the message Proje Deployment to Tomcat Here s the URL you pass to theget task to tell the Tomcat manager servlet wh you want to do http localhost 8080 manager deploy path deployment amp war file c ant deploy You can see this at work in Example 8 4 Example 8 4 Deploying with get ch08 get build xml lt xml version 1 0 encoding UTF 8 gt lt project default main basedir gt lt property name tomcat port value 8080
151. ation xml from using the appxmi attribute Here s an example that creates an ear file lt ear destfile S output app ear appxml S src application xml gt eTLIese dir vardir inelides war lt ear gt 8 8 2 Supporting Hot Deployment The serverdeploy task is designed to support hot deployment where you don t have to take the server down before deploying to EJ B aware servers You set theaction attribute to values you ve seen like those used for the Tomcat manager servlet deploy delete and undeploy You ll need vendor specific deployment software to make this one work Ant provides the build end but your server will need to provide a deployment facility that Ant can connect and interact with downloaded from lib ommolketab ir downloaded from lib ommotketab ir As of this writing this task only supports Weblogic servers and the JOnAS 2 4 Open Source EJB server but Support for other EJB containers should be added soon This task has only two attributes which appear in Table 8 7 and requires some nested elements Table 8 7 The serverdeploy task s attributes Attribute Description Required Specifies the action you want to perform such aSdeploy delete list undeploy OF update action Yes Specifies the path and filename of the component you want to deploy source This may be an ear jar war or other file type supported by the server Depends on the server The serverdeploy task S
152. attributes Attribute Description Required Specifies the location of the DTD you want to use Set this to a file a resource Lecation or a URL Yes publictd Specifies the public ID of the DTD to resolve Yes You can use nested xmlcatalog elements an XMLCatalog is a catalog of public resources such as DTDs or entities that are referenced in an XML document The attributes of this element appear in Table 9 3 downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Table 9 3 The xmlicatalog element s attributes Attribute Description Required ia Specifies a unique ID for an XMLCatalog This ID can be used to reference the No XMLCatalog from another XMLCatalog Specifies the ID of another XMLCatalog whose contents are used in this refid No XMLCatalog The xmlcatalog element can contain nested dtd classpath and catalogpath elements the catalogpath element is an Ant path like element which as you know means it can contain nested fileset elements pathelement elements and so on The xmlvalidate element can contain nested attribute elements which set SAX Parser features as defined at http xml org sax features The attributes of this element appear in Table 9 4 Table 9 4 The attribute element s attributes Attribute Description Required name Specifies the name of the feature to set Yes value Specifies the boolean setting of the feature Yes 9 1 1 Validating with XML Schema It s easy
153. ause the dependencies of a task are executed before the task the actual order of execution here IS find inspect test and then purchase 1 4 5 Properties In addition to targets and tasks the third pillar of an Ant build file is itsoroperties Properties are name value pairs that act much like constants in Java code You set the value of a property with the property element and can refer to that property by name throughout your build file You can insert the value of a property in task attributes by dereferencing the property name withs property name For example if you had a property named bin corresponding to the output directory of your build and wanted to refer to that directory you could refer to it aS bin when you assign it to task attributes in your build file If you wanted to refer to thearchives subdirectory in that output directory you could refer to it aS bin archives The advantages to this approach should be obvious to anyone who s had to change a directory name in 300 different places throughout an application A forward slash will work as a directory delimiter even on Windows systems Ant is smart enough to know what you mean 1 4 5 1 Property attributes Properties are used the same way as constants are in Java they let you collect definitions in one centralized place rather than having them dispersed throughout a build file When you want to change property values you can make changes in one location and know that
154. b application and need to start a web server The tasks in this chapter do more than the usual internal Ant tasks and because they re designed to deal with the external run time environment so they re a little more involved than usual downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 7 1 Executing Java Code The java task is part of Ant s core functionality it executes a Java class in the current J VM or forks another JVM and runs the class in the new JVM You can recover the exit code of the Java class and stop the build if the build results you re testing create an error Here s an example using this task Say you have this code Project java which reads what the user enters on the command line and displays it public class Project pPublIAG static void main String args oystem 0 tprintlin rou said T args 0 System exit 0 After compiling this code you can run it with thejava task by setting up the classpath with a classpath element and passing a command line argument OK in a nestedarg element The build file appears in Example 7 1 Example 7 1 Using the java task ch0O7 java build xml lt xml version 1 0 gt lt project default main gt lt property name srce location source gt lt property name output location bin gt lt property environment env gt lt target name main depends init compile run gt lt echo gt Bu uilaing and PUnn
155. b ir downloaded from lib eommolketab ir build files See Ant build files build numbers 2nd 3rd 4th build process See Ant build process Java build process build property deploy task build xml file 2nd 3rd BuildEvent object BuildException constructor buildfile option 2nd buildFinished method 2nd buildnumber task 2nd buildStarted method bunzip2 task 2nd byline attribute reolaceregexp task bzip2 task 2nd 3rd downloaded from lib ommolketab ir downloaded from libeommolketab ir Index A B C D E F G H H J K L M N O P Q R S O U V W RX 2 cab files Ant tasks and creating 2nd deploying 2nd cab task 2nd 3rd cabarc tool Microsoft cabfile attribute cab task cache attribute depend task carriage returns fixing casesensitive attribute DirSet type FileSet type castormapping element ejbdoclet task catalogpath element xmicatalog element cc element mail task CCCheckin task CCCheckout task cclist attribute mail task CCLock task CCMCheckin task CCMCheckinTask task CCMCheckout task CCMCreateTask task CCMkattr task CCMkblI task CCMkdir task CCMkelem task CCMklabel task CCMklbType task CCMReconfigure task CCRmtype task CCUnCheckout task CCUnluck task CCUpdate task lt CDATA gt section XML chacl command CVS change logs char data type charset attribute javadoc task mail task message element checkout comman
156. b ommoltketab ir 5 2 Running Test Cases To run the J Unit test cases add atest target to the build file introduced at the beginning of the chapter and make the main target depend on the test target as part of the build process lt target name main depends init compile test compress deploy gt lt SCno gt S message lt echo gt lt target gt The test target will run the six targets you re going to create in this chapter lt property name testsOK value Tested OK gt lt target name test depends test1l test2 test3 test4 test5 test6 gt lt echo gt testsOK lt echo gt lt target gt If you re not using Ant or a Java IDE you usually run J Unit tests from the command line and use the junit textui TestRunner Class like this testing the example class created earlier in the chapter org antbook Project 6java junit textui TestRunner org antbook Project You can do essentially the same thing in Ant using thejava task and that looks like this in the build file for the first test task test1 Note that I m adding junit jar to the classpath lt target name test1 depends compile gt lt java fork true classname junit textui TestRunner classpath S ant home lib junit jar gt lt arg value org antbook Project gt lt java gt lt target gt Here s what this task looks like when it s running testl downloaded from lib ommolketab ir downloaded from lib ommotket
157. b ommotketab ir replace an XML comment gt Tileser dir ineludes 4 7 ami J gt lt replaceregexp gt lt target gt lt project gt Changing the contents of other files this way will be useful if you need to rewrite build files that you re about to call with the ant task Here s an example of editing build files to convert from a local to an FTP install lt reml vers1on 1 0 7 gt lt project default main basedir gt lt target name main gt lt replaceregexp match lt copy file Project jar todir dist gt replace lt ftp server ftp isp com gt lt fileset dir bin gt lt ftp gt lt fileset dir subproject includes xml gt lt replaceregexp gt lt target gt lt ant dir subproject gt lt project gt Unless it s unavoidable editing build files this way is not good programming practice It s better to pass parameters along with theant call Here s another example this time of replacing all whitespace in documentation files with spaces lt replaceregexp match s replace flags g gt lt fileset dir docs includes html gt lt replaceregexp gt The attributes of this task appear in Table 10 3 Support exists for the regular expression library built into Java 1 4 you should have jakarta oro jar in the Ant lib directory downloaded from lib ommolketab ir downloaded from lib ommotketab ir Table 10 3 The replaceregexp attributes At
158. base attribute jsoc task uriroot attribute jspc task url attribute property element property task 2nd URL schemas use attribute javadoc task useexternalfile attribute javadoc task usefile attribute formatter element formatter task user attribute mail task user element userid attribute fto task telnet task user element username attribute generic element get task sshexec task tarfileset element weblogic element usernames 2nd usersfile attribute cvschangelog task usetimestamp attribute get task utilobject element ejbdoclet task downloaded from lib eommolketab ir downloaded from libeommolketab ir Index A B C D E F G H 1 fy K L M N O P Q R S M U V W RX Z V option vajexport task vajimport task vajload task validargs attribute input task validate attribute xmlproperty task value attribute argument element attribute element 2nd available task compilearg element condition task env element filter task outproperty element property element property task setting property values system properties and update task valueobject element ejbdoclet task vbc task verbose attribute apply task cab task chmod task copy task delete task ejbdoclet task fto task get task javac task javadoc task ispc task webdoclet task verbose option 2nd verifyproperty attribute checksum task version attribute javadoc task version command CVS
159. ber of times to play the sound file No 0 Specifies the time measured in milliseconds you want to play the duration No sound file downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 10 2 Creating Splash Screens This task creates a splash screen displayed while the build is progressing nExample 10 1 I m using a splash screen that the Apache Jakarta Project makes available at http jakarta apache org images akarta logo gif and I m displaying it for five seconds Example 10 1 Using a splash screen ch10 splash build xml lt xml version 1 0 gt lt project default main basedir gt lt property name cvs dir value project gt lt target name main depends splash gt lt echo gt Checking out and updating lt echo gt lt target gt lt target name splash gt lt splash imageurl http jakarta apache org images jakarta logo gif showduration 5000 gt lt target gt xJ project You can see the Apache Jakarta logo that appears when this task executes inFigure 10 1 This task provides a nice touch if you re distributing your build files to a team Figure 10 1 Sample build splash logo The attributes of this task appear in Table 10 2 downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Attribute imageurl showduration Table 10 2 The splash attributes Description Required Default Specifies an URL that points to the
160. ble 6 9 The patch task s attributes Attribute Description Required Default Backus Specifies you want to keep backups of unpatched No files Aeees te Specifies the file you want to send the output to No Since Ant 1 6 Specifies the directory where you want to run the The project s patch command basedir Specifies that you want to ignore whitespace ignorewhitespace Caan Species he eon foriginalfile Specifies the file you want to patch the file you want to patch patchfile Specifies the file that contains the patch e eee Specifies you want to supress messages unless an No error occurs Specifies you want to create the patch with old and reverse No new files in reverse order Swapped downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Chapter 7 Executing External Programs Part of the build process involves testing what you ve built and an obvious way of doing that is to ru the results of a build Doing so from Ant involves using the tasks detailed in this chapter java exec and apply You can check the return code from your build to ensure things worked out if not you can halt the build before you deploy faulty build results Executing code to test it is a fundamental part of the build process and this chapter covers that aspect of Ant Besides running your code you can start and stop external programs needed to test your code such as when you want to run a J Unit test on a We
161. blic void testEquals public void testNotNull public boolean returnTrue return true public int return4 retu urn 2 23 public Object returnObject return new Integer 1 p bli static void main String 2rge Project project new Project project vocem CuCC Princ Ore Cte recurnIrue System out printin project return4 PysvelsOUul princi PrO otre C rnob ect 17 Use the J Unit methods assertTrue assertEquals and assertNotNull to test the results from the three methods in Project javafor example testing if the return value of return4 really is 4 as it should be If any of these assertions don t work an exception is thrown and that exception causes the build to fail downloaded from lib ommolketab ir downloaded from lib eommolketab ir package org antbook import junit framework TestCase public class Project extends TestCase public Project String name public void testTrue assertTrue assertTrue test returnTrue public void testEKquals assertEquals assertEquals test 4 return4 public void testNotNull assertNotNull assertNotNull test returnObject public boolean returnTrue return true public int return4 FeLuIn 2 2 public Object returnObject return new Integer 1 pPuDLIG statie void main tring args Project project new Pro
162. by SQL type tasks MatchingTask Abstract task that should be extended by tasks required to include or exclude files based on patte matching Pack Abstract base class for pack tasks Task Generic task and the one most commonly extended Unpack Abstract base class for unpacking tasks The Task class i e org apache tools ant Task is used for most of this chapter though some samples will USe MatchingTask The methods of the Task class appear in Table 12 2 Table 12 2 The Task class s methods downloaded from lib ommolketab ir downloaded from lib ommolketab ir Method Does this void execute Specifies the task should execute java lang String getDescription Returns the task s description Returns the file and location at which the ta Location getLocation supported Target getOwningTarget j Returns the target that contains this task Returns the wr rcl instance the task RuntimeConfigurable getRuntimeConfigurableWrapper een ee ARR oo AE ne uses for runtime configuration Returns the task name used when when logging messages from the task java lang String getTaskType Returns the type of task as a String Returns the runtim nfigurable structure f protected RuntimeConfigurable getWrapper a aie Me an gu able s a ae this task aS a RuntimeConfigurable object protected void handleErrorFlush java lang String Handles errors by logging them with ERR output priority protect
163. c task arguments and description file permissions and overview execon task executable attribute apply task exec task 2nd javac task Execute class 2nd execute method Ant tasks and 2nd 3rd Execute class nested elements and Task class execute I arget method Project class execute Il argets method Project class executing Ant batch programs external programs Java code setting order and exit method System expandproperties element FilterChain type export command CVS expression attribute containsregexp selector param element extdirs attribute javac task 2nd javadoc task path type extension attribute formatter task xslt style task external programs executing running 2nd External Tools dialog box Eclipse downloaded from lib ommolketab ir downloaded from libeommolketab ir Index A B C D E F G H 1 J K L M N O P Q R S M U V W RX Z f option 2nd factory element TraX fail element sound task 2nd fail method JUnit fail task 2nd 3rd 4th failifexecutionfails attribute apply task exec task 2nd failonany attribute parallel task failonerror attribute apply task copy task custom tasks and cvs task cvschangelog task cvstagdiff task cvsversion task delete task exec task 2nd java task 2nd javac task javadoc task ispc task loadfile task mail task scp task sshexec task tasks and xmlivalidate task failureproper
164. chapter covers the tasks specifically designed for packaging web applications such aSwar cab ear and jspc and for deploying them such aS get serverdeploy and scp I ll also cover the custom Ant tasks targeted to specific servers such aSdeploy reload and undeploy Chapter 9 XML and XDoclet You can validate XML documents using XML DTDs and schema using thexmivalidate task You can read properties from an XML document usingxmlproperty You can use the xslt style task to transform XML documents using XSLT In this chapter discuss XDoclet an open source code generation engine designed to run in Ant XDoclet can generate code deployment descriptors such as web xml and other artifacts for web and EJB applications Chapter 10 Optional Tasks Ant comes with a number of optional tasks and this chapter covers the highlights including tasks that create sounds to indicate where you are in a build tasks that display splash screens tasks that work with regular expressions to match text and more Chapter 11 Integrating Ant with Eclipse Eclipse is the premiere integrated development environment IDE for Java programmers Eclipse is great at visual development whereas Ant is great for builds Eclipse comes with Ant built in and there s an extensive Ant interface in Eclipse The Ant Eclipse connection is extremely useful to Java developers and it s covered in this chapter Chapter 12 Extending Ant This chapter covers how to create ne
165. condition task isset element condition task istrue element Condition task downloaded from lib eommolketab ir downloaded from libeommolketab ir Index A B C D E F G H 1 J K L M N O P Q R S M U V W RX Z jar attribute java task jar files adding creating ejbjar task and optional tasks and running scripts and unpacking jar task creating jar files description ear task and ilink task and nesting and war task and 2nd zipfileset element and jar schema jarlib available task jarlib manifest task jarlib resolve task jarsign task Jasper JSP compiler Java build process calling other tasks compiling code creating jar files documenting code importing build files 2nd setting build numbers setting timestamps user input and Java classes data types and dependencies and 2nd filters and generic element and java task and recognizing updated test element and Java Media Framework Java Native Interface JNI java task description downloaded from lib ommolketab ir downloaded from lib eommotketab ir overview running test cases timeouts and java io File data type JAVA HOME environment variable JavaBean Tester tool javac task alternatives compiling code compiling JSPs 2nd compiling source files depend task and description file sets and forking compiler java task and setting command line options 2nd src element and srcdir attribu
166. d CVS downloaded from lib eommolketab ir downloaded from lib eommotketab ir checksum element condition task checksum task 2nd chgrp task chmod attribute ftp task chmod task 2nd 3rd 4th 5th Choose Location dialog box Eclipse chown command CVS chown task classconstants element FilterChain type 2nd classes element war task classname attribute available task formatter task generic element java task jonas element mapper element taskdef task xmivalidate task classpath attribute available task depend task 2nd ejbjar task generic element java task javac task 2nd javadoc task jonas element ispc task junit task mapper element path type property element taskdef task 2nd 3rd weblogic element 2nd xslt style task classpath element depend task and ejbjar task example java task and jonas element and nesting path type and serverdeploy task and taskdef task and weblogic element and xmicatalog element and xslt style task and classpathref attribute available task java task downloaded from lib ommolketab ir downloaded from lib eommolketab ir javac task javadoc task ispc task mapper element property element xmlivalidate task xslt style task classpathref element jspc task clearcase task Clearcase version control system 2nd closure attribute depend task 2nd cmpversion attribute ejbjar task code assist Eclipse 2nd collapseAttributes attribu
167. d line as well USe D VAR ENV_VAR Windows or D VAR ENV_VAR Unix You can then access these variables inside your build file aS VAR You ve got a good handle on properties at this point and they re a major building block of Ant build files The next step up is to work with the built in Anttypes downloaded from lib ommolketab ir downloaded from lib ommolketab ir 2 3 Handling Data Using Types Ant supports a number of types and the rest of this chapter is devoted to understanding them and how to work with them These types work much like data types in programming languages and as you re going to see types and properties are intertwined The data structures you create using types can be assigned to properties and the data you use to set up those data structures is often stored in properties Now that you ve got properties under your belt it s time to move on to types Much of what a build tool like Ant does is work with files in directory structures so you might expect that many of the Ant types have to do with handling files and directories You can see the available Ant core that is built in types in Table 2 7 Table 2 7 Core Ant types Type I __ Description Assertions Enables or disables Enables or disables Java 1 4 assertions 1 4 assertions ae jessie Holds a description of the project that can be viewed if you use theant Description projecthelp command Dirset Con
168. ded from lib eommolketab ir downloaded from lib eommoltketab ir Problems view Eclipse processor attribute xslt style task Project class 2nd project element 2nd lt project gt tags projecthelp option 2nd projects accessing in code creating modules and overview setting classpath properties See also types See also types accessing in code built in 2nd conditional actions declaring outside targets defined loading from XML files loading text files name value format overriding passing with ant task setting conditions setting values setting with environment variables 2nd setting with tasks stopping builds text strings and values as tooltips property attribute available task checksum task condition task format task loadfile task update task Property class property element attributes environment variables 2nd 3rd nesting property files property task declaring properties description example 2nd param elements and propertyfile option 2nd propertyfile task 2nd propertyref element propertyset element 2nd downloaded from lib eommolketab ir downloaded from lib eommolketab ir PropertySet type protected attribute javadoc task provider attribute checksum task public attribute javadoc task publicld attribute dtd element pvcs task 2nd downloaded from lib ommolketab ir downloaded from lib ommotketab ir Index A B C D E F G H
169. ded from lib ommolketab ir downloaded from lib ommoltketab ir 8 3 Creating Simple Web Deployment With a WAR file or CAB file it s time to turn to the deployment side of the Web development equation If you re working on the same machine as a Web server deployment can be as easy as copying a war file to the application base directory for the server Example 8 2 illustrates the point this build file creates and copies a war file over to the Tomcat webapps directory When you re start Tomcat the war file will expand automatically into a directory of the same name minus the war extension and the Web application will become available in this case athttp localhost 8080 app If you re deploying a servlet the URL will reflect the servlet s package as in http localhost 8080 org antbook ch08 app for the servlet class org antbook ch08 app Example 8 2 Build file for Tomcat deployment ch0O8 simple build xml lt xml version 1 0 encoding UTF 8 gt lt project default main basedir gt lt property name src location source gt lt property name wardir location ca tomcat jakarta tomcat 5 0 19 webapps gt lt property name warfile location S wardir app war gt lt target name main depends war gt lt echo message Deploying the Web app gt J target lt target name war gt lt war destfile warfile webxml S src app xml basedir bin gt lt target gt
170. deployment It uses the remote machine s IP address instead of naming the remote server Example 8 3 Using scp ch08 scp build xml lt xml version 1 0 gt lt project default main gt lt property name message value Deploying the jar file gt lt property name sre location source gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt property name output location bin gt lt target name main depends init compile compress deploy gt lt echo gt message lt echo gt lt J targat gt lt target name init gt lt mkdir dir output gt lt target gt lt target name compile gt lt javac srcdir S sre destdir S output gt lt target gt lt target name compress gt lt jar destfile S output Project jar basedir output gt lt include name class gt lt include name txt gt lt jar gt lt target gt lt target name deploy gt lt scp trust true file S output Project jar todir user password 000 000 000 000 cgi bin gt lt target gt lt project gt Here s what that build file output looks like when run on a Windows machine Sant Buildfile build xml inni mkdir Created dir C ant ch08 scp bin compile javac Compiling 1 source file to C ant ch08 scp bin compress jar Building jar C ant chO8 scp bin Project jar deploy sep Connecting to 000 000 000 000 scp Sending Pr
171. developers No longer do you have to try to remember the 50 steps to build your projec and make sure you do them in the right order or try to get finicky makefiles just right Now you ve got a true build tool that s genuinely easy to work withand outstandingly powerful If you ve never used Ant you re in for a treat We re going to push the envelope in this book working from the basics through the advanced doing nearly everything that Ant can do This book was designed to open up Ant and make it more accessible than any other book on the subject It s a programmer to programmer book written to make you an Ant pro without wasting time If you re a programmer this book is written to give you exactly what you want to see which is the good stuff and only the good stuff There s as much Ant crammed into this book as you need to master the topic and mastering Ant is the goal downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Team LiB What s Inside From cover to cover this book is pure Ant covering hundreds of topics and techniques We start from the most basic Java development up to extending Ant yourself it s all here Here are a few of the topics in this book e Getting and installing Ant e Creating build files e Running a build e Handling build failures e Specifying build targets e Using property files e Handling datatypes and properties e Handling filesets e Using selectors filterset
172. ding to use For use when Deau ta To encoding ar No default J VM copying files using l encoding filters Specifies whether you failonerror want the task to fail if No TRue there is an error TR Specifies the file you Yes unless a nested fileset want to copy element is used Specifies whether you downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default want to use filtering Nested filterset Fi lpering elements will always be No false used you don t have to set this attribute to true for that flatten includeEmptyDirs Specifies you want to ignore the directory structure of source files copying all files into the directory given by the todir attribute Specifies you want to copy any empty directories as well No No Specifies the encoding you want to use when No writing files Available since Ant 1 6 No No Defaults to the value of the encoding attribute if given or the default JVM encoding otherwise outputencoding vn preservelastmodified Codir tofile Specifies the file you want to copy to downloaded from lib ommolketab ir Specifies whether you want to overwrite existing files Specifies you want copied files to have the same modified time as the source files If you use the file attribute tofile Or todir can be used If you use nested fileset
173. e In this case the build file won t compile the source files if the file enduser agreement exists which sets a property named final version Example 2 1 Using the unless attribute ch0O2 if build xml lt xml version 1 0 gt lt project default main gt lt property name message value Building the jar file gt lt property name src location source gt lt property name output location bin gt lt available file S output enduser agreement property final version gt lt target name main depends init compile compress gt lt echo gt message lt fecho lt target gt lt target name init gt lt mkdir dir oreo J gt lt target gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt target name compile unless final version gt lt javec Sroo ra S srci destdir output z gt lt target gt lt target name compress gt lt jar destfile S output Project jar basedir output includes class gt lt target gt lt project 2 1 3 Stopping Builds You can make a build fail at runtime using property values and thefail task The fail task has been made more useful since Ant 1 5 with the addition of Support for the if and unless attributes For example this build will fail with a message unless the specified classes are found in the classpath lt target name lt condition property classes available gt lt
174. e opens Specifies the prefix to prepend to each No property automatically Z i basedi rootDirectory Specifies the root directory to search for files No ase aa eee eee Specifies you want to use semantic handling No ee of attribute names validate Specifies you want to validate the input file No Talse downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 9 3 Creating Ant Task DTDs The Ant documentation is useful but at times hard to use if you re looking for the definitions of nestec tasks and elements because they re not listed at the top level On the other hand if you can read a DTD and want to know how any Ant task or element is defined use theantstructure task This task will create a DTD for all Ant tasks that Ant knows about including optional tasks with their attributes and nested elements This task only has one attribute output which specifies the output file to hold the DTD Example 9 4 shows how to use this task storing the DTD for all Ant tasks inproject dtd Example 9 4 Using the antstructure task ch0O9 antstructure build xml lt xml version 1 0 gt lt project default main gt lt target name main gt lt antstructure output project dtd gt lt target gt lt project gt Here s part of the DTD project dtd generated lt ELEMENT project target tasks ttypes gt lt ATTLIST project name CDATA IMPLIED default CDATA IMPLIED basedir
175. e value Building the jar file gt lt target name main depends compile compress gt lt echo gt message lt echo gt lt target gt lt project gt Properties are frequently used to hold pathnames and theproperty element s location attribute is useful in this context Suppose you re storing your source code in a subdirectory of the current directory named source and want to deploy the jar file created by this build file to a directory named bin You can create properties corresponding to these directories lt xml version 1 0 gt lt project default main gt lt property name message value Building the jar file gt lt property name src location source gt lt property name output location bin gt lt target name main depends init compile compress gt lt echo gt message downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt echo gt lt target gt lt project gt The default target in this build file main depends on an init target where the mkdir task detailed in Chapter 3 is used to create the output directory lt xml version 1 0 gt lt project default main gt lt property name message value Building the jar file gt lt property name srce location source gt lt property name output location bin gt lt target name main depends init compile compress gt lt echo gt S message lt ech
176. e 1 5and you ll see several of them in this chapter Some of the optional tasks are specialized but a number are useful in everyday builds You ve seen optional tasks likejunit and ftp and this chapter expands that coverage with a look at tasks like sound splash replaceregexp and depend downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 10 1 Using Sound The sound task plays a sound file at the end of the build according to whether the build failed or succeeded You can specify one sound file to play or if you specify a directory thesound task will randomly select a sound file to play If you re using Java 1 3 or later you need the Java Media Framework on the classpath javax sound The sound task can contain success and fail elements The success element specifies the sound you want played if the build succeeds and failures the sound if it fails Here s an example where the build file specifies the sounds to play depending on if the build succeeded or failed lt target name sounds gt lt Sound gt lt sucocess Ssource Siuser home sounds success wayr gt lt fail source S user home sounds noway wav gt lt sound gt lt target gt These success and failure elements support the attributes you see in Table 10 1 Table 10 1 The success and fail elements attributes Attribute Description Required Default source Specifies the name of a sound file Yes loops Specifies the num
177. e FTP server Specifies whether you want to see information on each file as it s No no transferred Set to yes no The condition task lets you probe if remote systems are available before attempting an FTP operationYou can use two nested elements incondition http which can test can probe for remote servers and socket which can send messages to remote servers verbose The ftp task Supports any number of nested fileset elements which is how you specify the files to be retrieved deleted or listed or whose mode you want to change 4 3 4 Deploying Remotely Using Telnet Ant includes a telnet task that you can use when deploying remotely For security reasons Telnet is losing popularity in favor of SSH but I ll take a look attelnet followed by the sshexec task This is one of Ant s optional tasks so you ll needcommons net jar available from http jakarta apache org commons net index html in the Ant lib directory This task uses nested read elements to indicate strings to wait for andwrite elements to specify text to send Here s an example that connects to a server and asks for a listing of the directory home steven downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt telnet userid steven password l1et_me_in server 000 000 000 000 gt lt read gt home steven lt read gt lt write gt ls lt write gt lt telnet gt You can see the attributes of this task inTable 4 13
178. e fileset attributes and the additional attributes you see in Table 4 2 The tarfileset type gives you control over the access mode username and groupname to be applied to the TAR entries This is handy for example when preparing archives for Unix systems where certain files need to have execute permissions Table 4 2 The additional tarfileset attributes Attribute Description Required Default Specifies a 3 digit octal string which gives the user and group using normal Unix conventions Applies to No directories only Available since Ant 1 6 ieee Using this attribute means the file in the fileset is a written with this path in the compressed file group Specifies the group name for the TAR item o Specifies a 3 digit octal string which gives the user mode and group using normal Unix conventions Applies to No plain files only Specifies a path with which to prefix all files in the prefix No compressed file peace E E Specifies if you want to preserve leading slashes ee In mana username username Specifies the username for this TAR item the username for this TAR item dirmode This next longer example uses GNU extensions for long paths and useStarfileset elements to mark some files as executable specifically using Unix file mode 755 which means executable and readabl by all and writeable by the owner lt tar longfile gnu destfile dist gt lt tarfileset dir S bin mode
179. e to a single directory Here s an example lt copy todir backup gt lt fileset dir development includes java gt lt mapper type flatten gt lt copy gt The merge Mapper copies multiple files to the same target file Here s an example lt mapper type merge to backup tar gt In the glob Mapper you can use filename patterns in the to and from attributes and those patterns may contain at most one asterisk lt copy todir backup gt lt fileset dir development includes java gt lt mapper type glob from java to old gt lt 1 CON The regexp mapper lets you use regular expressions in theto and from attributes You can create downloaded from lib ommolketab ir downloaded from lib ommotketab ir regular expression matches using parentheses in theto attribute value and refer to the matched values as 1 through 9 in the from attribute value We ve seen an example of this mapper at work lt copy todir backup gt lt fileset dir development includes java gt lt mapper type regexp from a z java to l backup gt lt GOP For more on regular expressions see Mastering Regular Expressions by Jeffrey Friedl O Reilly The package mapper is an interesting one as it replaces directory separators found in the matched source pattern with dots in the target pattern placeholder reproducing Java package syntax This inspiration here is that thi
180. eation date 2nd creation time 2nd crontab utility Unix 2nd 3rd Cruise Control build tool 2nd csc compiler Csc task CVS Concurrent Version System Anthill and 2nd change logs changes between versions commands 2nd creating patches CVSROOT environment variable and logging in and 2nd servers and source control and version data and cvs task checking out modules CVS commands and CVS servers and description 2nd downloaded from lib eommolketab ir downloaded from lib eommolketab ir CVS RSH environment variable 2nd 3rd cvschangelog task 2nd 3rd 4th cvsclientproperty attribute cvsversion task cvspass task checking out modules description 2nd logging in with updating shared code cvsroot attribute cvs task 2nd 3rd cvschangelog task cvspass task 2nd 3rd cvstagdiff task cvsversion task CVSROOT environment variable CVS servers and cvs task and cvspass task and cvstagdiff task and cvsversion task and Windows and cvsrsh attribute cvs task cvschangelog task cvstagdiff task cvsversion task cvsserverproperty attribute cvsversion task cvsServerVersion property cvsversion element cvstagdiff task 2nd 3rd cvsversion task 2nd Cygwin environment downloaded from lib eommolketab ir downloaded from libeommolketab ir Index A B C D E F G H H J K L M N O P Q R S O U V W RX 2 D option d option D option daemons eleme
181. ecated Index Heip Project PREV CLASS HET CLASS FEANES HD FRAMES SUMMER Y NESTED FIELD CONSTR METHOD DETAIL FIELD CONSTA METHOD Class Project java lang On ect Project public dass Project extends jeve leng Opject This spplicaton prints out Ho woeres You can see the huge number of attributes of this task in Table 3 9 Since the javadoc tool calls the System exit method javadoc cannot be run inside the same JVM as Ant For this reason javadoc always forks the J VM downloaded from lib ommolketab ir downloaded from lib ommolketab ir Table 3 9 The javadoc task s attributes Attribute Description Required Default Sets the access mode you can use access these values public protected No protected package OF private Specifies additional parameters for the ee javadoc command line Any parameters ddit I l with spaces should be quoted using me egur ae ee Specifies you want to include author No paragraphs Specifies you want to override the f cel th Mo T classpath set by the boot class loader Specifies you want to override class file oe cal thre aerer C ba a references set by the boot class loader bottom Sets Sets the bottom text for each page bottom text for each page Specifies you want to use the breakiterator algorithm which is used No aan h satin Ga rT Set to yes or no breakiterator charset Specifies the character set to use the
182. ecking any classes which depend on an item from the classpath and which are older than that item will be deleted If you re going to include a classpath to check for dependencies don t end up including the entire J ava library structure by mistake doing so will slow this task down Checking dependencies can become involved For example what if a class depends on another whic in turn depends on a third If the third class is out of date only the second class would normally be rebuilt even if you use the depend task But you can ensure the depend task catches all dependencies including indirect ones like this by setting theclosure attribute to true downloaded from lib ommolketab ir downloaded from lib ommotketab ir Nonpublic classes can also cause a couple of problems with this task For example depend cannot connect the class file containing a non public class to a source file depend can t detect when a nonpublic class is missing If you ve set the Java compiler to optimize its compilation that can also cause problems Inner classes on the other hand are no problem Normal Ant processing usually handles dependencies with no problem but if you ve got a complex dependency situation or indirect dependencies this task can work wonders If you can t handle your dependencies with depend wipe the output directories before compiling to start with a clean slate downloaded from lib ommolketab ir downloaded
183. ectory layout only thedin and lib directories are needed to run Ant Ant bin Ant launch scripts lib Ant jars docs Ant documentation etc XSL for formatting Ant XML output You need to perform the following steps to complete the setup process 1 Add the Ant bin directory to your path 2 Set the ANT_HoME environment variable to the directory where you installed Ant On some operating systems the Ant scripts can gueSSANT_HomEspecifically in Unix and Windows NT 2000but it s better not to rely on them doing so accurately 3 Set the JAVA_HOME environment variable to the directory where your J DK is installed downloaded from lib ommolketab ir downloaded from lib ommotketab ir If you ve expanded Ant in c ant on Windows you ll end up with a new directory c ant apache ant 1 6 1 If you ve installed the JDK inc jdk1 4 and the J ava bin directory is C jdk1 4 bin set the environment variables like this set ANT _HOMEF C ant apache ant 1 6 1 set JAVA_HOME C jdk1 4 set PATH PATH S SANT _HOME bin In Unix bash assume Ant is installed in usr local ant Here s how you d set up the environment export ANT_HOME usr local ant export JAVA_HOME usr local jdk1 4 export PATH S PATH S ANT_HOME bin In Unix csn you d do something like this setenv ANT HOME usr local ant setenv JAVA_HOME usr local jdk1 4 set path Spath SANT_HOME bin There are great instructions on how to set environment variables
184. ed authserver Specifies authentication mode for the server downloaded from lib ommolketab ir downloaded from lib ommolketab ir Does this int aad ooon lchacl Specifies the access list for a directory the access list for a directory checkout Checks out source code from the repository chown Changes the owner of a directory in the repository commit Checks source code files into the repository diff Displays the differences between source code revisions edit Specifies you want to edit a file editors Specifies you want to watch who has been editing a particular file export Exports source code from a CVS repository similar to checkout history Displays the CVS repository access history import Imports source code into a CVS repository info Displays information about the CVS repository and its supported protocols log Displays information on file history login Asks for a password if needed logout Logs out of a server le Lists the files in the CVS repository lsacl Lists the CVS directories access control list n o E Sets a user s CVS password Frannotate Displays the revision in which source lines were modified the revision in which source lines were modified Creates patch files by comparing two files and outputting a file that be used to vdir m j a I one into the other release Specifies that a module will not be used anymore that a module will not be used anymo
185. ed globally for all Ant builds 11 2 3 Setting Property Values You can set global Ant properties using the Ant preferences page which you open by selecting downloaded from lib ommotketab ir downloaded from lib ommotketab ir Window Preferences Ant Runtime and clicking the Properties tab To add a new property click the Add Property button and fill in the Name and Value fields in the dialog that appears This wil set the global properties for all Ant builds in Eclipse and since properties are immutable you will be setting the final value for such properties You can set properties on a project by project basis by setting the project s Ant launch configuration Click the Properties tab in the launch configuration as seen inFigure 11 8 deselect the Use global properties as specified in the Ant runtime preferences checkbox and click the Add Property button to set new properties Figure 11 8 Setting properties AinvtEstannple bauibel soml Modify attributes and launch Crease a configuration Hist will pun an Ant buldtle Marre AntExample bild rel Main lt Refresh ize Buid Targets Classpath O Properties m ape B environment La Use global properties as specified in the Ant runtime preferences Properties d y eclipse home ds ecipseSieclinse oomtribuked by Ant Build Tool Core eclipse running true contributed by Ant Build Tool Cone Edt Property
186. ed to run the task 12 2 2 Accessing the Project and Properties in Code When you extend the Task class you have access to a great deal of data about the project The Task clas inherits the getProject method which returns a Project object that holds such items as the project s name and properties You can see selected methods of theProject class in Table 12 3 You can do nearl anything with these methods from setting a project s default target and logging text to reading propert downloaded from lib ommolketab ir downloaded from lib ommolketab ir values and setting property values That s a typical way for custom tasks to perform their work reading property values with the Project object s getProperty method and setting property values with setProperty After a property has been set it can be accessed in the build file letting the custom ta communicate with the rest of the build file Table 12 3 Selected Project class methods Method Does this void addbuilalistener buildiistener listener Adds a bulla listener to the current project catch build events void addTarget Target target Adds a new target to the project at runtime vyold a0ddTaskDeri nation java lang String tack lame Adds the definition of a new task to the java lang Class taskClass project Task creavelask java lang String taskType Creates a new task instance int defaultInput byte buffer int offset int Reads input data for the
187. ed void handleErrorOutput java lang String Handles errors by logging them with warn output priority Handl rror ing them with INF protected void handleFlush java lang String output 2 dles Ser by OggIng lt k priority rotected int handleInput byte buffer int offset i R Handles input requests using byte buffers int length Handl trin tput ing it USING INF Provected void handleouroul java lang string Ourpul a dies g output by logging It using priority os Called automatically so the task can be v id init MR initialized protected boolean isinvalid Returns a value of TRue if this task is invalid Voie oroa aae mee Logs a string message giving it default IN priority void LOC javea langsstring msg int Ins qlevel Logs a SUNG Tee Sees Chane pOT y ou specify veld meeecConcare i Configures the task if it has not already bee configured Performs this task If the task is not still val a replacement version will be created and tt task will be performed with that coid seca eure Reconfigures a task forcing the reconfiguration if necessary void setDescription java lang String desc Specifies a string description for this task java lang String getTaskName _ void perform downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Method Does this Wold G2 eleee a cao Specifies the file and location where this tas was first defined void setOwningT
188. element element catalogpath element and location attribute nesting and paths absolute converting references to exec task and nested elements and pattern attribute format task patterns DirSet type attributes and fixcrif task and glob mapper and replaceregexp task and downloaded from lib eommolketab ir downloaded from lib eommolketab ir selectors and working with patternset element cab task and conditional actions depend task and DirSet type and fileset element and jar task and javac task xslt style task and zip task and PatternSet type 2nd 3rd perforce task Perforce Ant tasks for perform method Task class perm attribute chmod task permissions setting with chmod tarfileset type and Unix and 2nd permissions element 2nd Permissions type plain formatter 2nd plug in manifest files pollilnterval attribute parallel task port attribute cvs task cvschangelog task cvstagdiff task cvsversion task fto task scp task sshexec task telnet task portletdoclet task XDoclet pramati element ejbdoclet task prefix attribute property element tarfileset element tstamp task xmlproperty task zipfileset element 2nd 3rd prefixlines element FilterChain type 2nd present selector preservelastmodified attribute copy task fto task preserveLeadingSlashes attribute tarfileset element preseidef task printsummary attribute junit task private attribute javadoc task downloa
189. ems Inc Author Steven Holzner Name Shared Title Example Vendor MegaAntCo Name Copyright Copy C MegaAntCo 2005 Want to sign your JAR file for distribution Use thejarsign task like this lt signjar jar jarfile jar alias development keystore local keystore storepass secret gt The attributes of the jar task are listed in Table 3 10 For more on creating manifests take a look at the Section 3 6 2 Table 3 10 The jar task s attributes Attribute Description Required Default Specifies the directory where the task should find basedir No files to JAR PES you want to compress data besides te No gt a P E PEEN E EE E Specifies whether you want to use default excludes uan la not set to eT or no ldestfile Specifies the new JAR file to create the new JAR file to create Specifies what you want to do when a duplicate EC duplicate is found Possible values are add preserve and No add fail EEP NA Specifies the character encoding to use for file No oe names in the JAR file downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default No files Specifies files to exclude Give as a comma or except default Space separated list excludes are excluded ee Specifies the name of a file containing exclude No patterns one to a line No excludes filesetmanifest Specifies what you want the task to do w
190. enough to use the xmlvalidate task to validate XML documents with schema as shown in Example 9 1 which validates document xml This example turns on schema validation by setting the parser attribute identified by the URI http apache org xml features validation schemato true Example 9 1 Valiating with a schema ch09 schemat build xml lt xml version 1 0 encoding UTF 8 gt lt project default main gt lt target name main gt lt xmlvalidate lenient no warn yes file document xml classname org apache xerces parsers SAXParser gt lt attribute name http apache org xml features validation schema value true gt lt xmlvalidate gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt target gt lt project gt Here s document xml the document to validate which uses the xsi noNamespace SchemaLocation attribute to specify the name of the schema document document xsd lt xml version 1 0 encoding UTF 8 gt lt document xsi noNamespaceSchemaLocation document xsd xmins xmlns xsi http www w3 org 2001 XMLSchema instance gt lt hello gt lt document gt Here s the schema document xsd lt xml version 1 0 encoding UTF 8 gt lt xs schema xmlns xs http www w3 org 2001 XMLSchema xmilns elementFormDefault qualified gt lt xs element name document gt lt xs complexType mixed false gt lt xs sequence gt lt xs element
191. ense to deploy a build that has been broken and using the J Unit framework with Ant you can run tests on your code and deploy a build only if it satisfies those tests This is a great way to make sure changes to your code haven t broken anything To test the results of a build automatically you ll need to use one of Ant s most powerful optional tasks junit This task is part of the repertoire of every serious Ant developer especially those working in teams If someone else on your project has broken your code you should know about it before you deploy or upload to a shared code repository and junit will let you Know about these problems automatically To demonstrate how J Unit works with Ant in this chapter we re going to useProject java shown in Example 5 1 as a guinea pig Example 5 1 A simple Project file package org antbook public class Project public Project String name public boolean returnTrue return true public int return4 return 2 t 23 i public Object returnObject return new Integer 1 public static void Maim Sering argol Project project new Project project downloaded from lib ommolketab ir downloaded from lib ommotketab ir System out printin project returnTrue System out printin project return4 System out println project returnObject ee ee This application Project java has three simple methods each of which ret
192. ent FilterChain type 2nd linecontainsregexp element FilterChain type 2nd link attribute javadoc task linkoffline attribute javadoc task linksource attribute javadoc task Linux environment list action JOnAS servers weblogic tool listener option listeners custom listfiles attribute javac task listing attribute ftp task loaderRef attribute taskdef task loadfile task 2nd 3rd loadproperties task 2nd 3rd locale attribute format task javadoc task Locale class Java localhomeinterface element ejbdoclet task localinterface element ejbdoclet task location attribute did element pathelement element property element 2nd log command CVS log method loggers and Project class 2nd Task class 2nd Log4Unit downloaded from lib ommolketab ir downloaded from lib eommolketab ir logError attribute apply task exec task java task logfile option logger option loggers logging custom 2nd output 2nd 3rd logging in source control and 2nd login command CVS 2nd logout command CVS longfile attribute tar task loops attribute Success fail elements ls command CVS 2nd lsacl command CVS downloaded from lib eommolketab ir downloaded from libeommolketab ir Index A B C D E F G H 1 Y K L M N O P Q R S CO U V W RX Z Mac OS environment macrodef task mail task 2nd 3rd mailhost attribute mail task 2nd MailLogger failure notify prope
193. erverdeploy task 2nd servlets 2nd 3rd session element ejbdoclet task setBaseDir method Project class 2nd setDefault method Project class setDefaultInputStream method Project class setDescription method Project class Task class setinheritedProperty method Project class setKeepGoingMode method Project class setLocation method Task class setName method JUnit framework Project class setNewProperty method Project class setOwningTarget method Task class downloaded from lib eommolketab ir downloaded from lib eommolketab ir setProjectReference method Project class setProperty method Project class setproxy task 2nd setRuntimeConfigurableWrapper method Task class setlaskName method Task class setlaskI ype method Task class setUp method JUnit 2nd 3rd setUserProperty method Project class setValue method Commandline object EnumeratedAttribute class shell commands 2nd short data type showduration attribute splash task showoutput attribute junit task signjar task SimpleDateFormat class Java 2nd size selector skipemptyfilesets attribute apply task skipFailedTransfers attribute ftp task sleep task 2nd 3rd SMTP servers 2nd socket element condition task 2nd Soscheckin task Soscheckout task Sosget task Soslabel task sound task 2nd 3rd source attribute javac task javadoc task serverdeploy task success fail elements source code accessing projects properties in
194. es xml version 1 0 encoding UTF 8 gt aj lt ample buildfile for jar components Project neme sample default build gt Selecting Window Preferences Ant Editor lets you configure the build file editor by setting tab widths margins highlighting and more 11 2 6 Adding New Ant Tasks and Types You can add new Ant tasks and types covered in detail in the next chapter to Eclipse by using the Ant preferences page at Window Preferences Ant Runtime These tasks and types will be available for build files without having to use thetaskdef Or typedef tasks which are normally needed To add a new task select the Tasks tab shown inFigure 11 11 click the Add Task button and navigate to the JAR file in which the new Ant task is located To add a new type click the Types tab and follow the same steps Figure 11 11 Adding Ant tasks downloaded from lib ommotketab ir downloaded from lib eommolketab ir Preferences If you can t find the JAR files you need add them to the Ant classpath first Alternatively you can add additional classes defining tasks and types to the Ant classpath by clicking the Classpath tab downloaded from lib ommotketab ir downloaded from lib ommotketab ir 11 3 Using a Different Version of Ant Eclipse comes with Ant 1 6 1 but it s possible to use a different version Open the Ant preferences
195. es a new JAR file with an included manifest MANIFEST MF that contains several attributes Example 3 4 Using the jar task ch0Q3 jar build xml lt xml version 1 0 gt lt project default main gt lt property name message value Building the jar file gt lt property name sre location source gt lt property name output location bin gt lt target name main depends init compile compress gt lt echo gt message lt echo gt lt target gt lt target name init gt lt mkdir dir output gt lt target gt lt target name compile gt lt javac srcdir src destdir output gt lt target gt lt target name compress gt lt jar destfile S output Project jar basedir output includes class gt lt manifest gt lt attribute name Author value S user name gt lt section name Shared gt lt attribute name Title value Example gt lt attribute name Vendor value MegaAntCo gt lt section gt lt section name Copyright gt lt attribute name Copy value C MegaAntCo 2005 gt lt section gt lt manifest gt lt jar gt lt target gt sI project gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir The created J AR file contains Project class and MANIFEST MF this latter file contains these contents Manifest Version 1 0 Ant Version Apache Ant 1 6 1 Created By 1 4 2_03 b02 Sun Microsyst
196. es to the inheritAll new Ant project Properties passed to the new project will No true override the properties that are set in the new project If true means the task should pass all current references to the new Ant project No false i1nhneritRers target Specifies the target you actually want to run Yes You can set properties in the new project with nested param elements which supports the same attributes as the property task Such properties will be passed to the new project no matter how inheritAll IS set Properties defined on the command line cannot be overridden by nestedparam elements downloaded from lib ommolketab ir downloaded from lib ommotketab ir You can use nested reference elements to copy references from the calling project to the new project See the attributes of this element inTable 3 5 References 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 Table 3 5 The reference element s attributes Attribute Description Required Default Specifies the ia of the reference you want to use in the refid 7 Yes original project Specifies the ia of the reference you want to use in the The value of corefid No new project refid As of Ant 1 6 you can specify sets of properties to be copied into the new project with nested propertyset elements This element works much like other
197. escription Required Default Specifies the patterns matching files to No files except excludes exclude as a comma or space separated No default excludes list are excluded Specifies the name of a file where each line excludesfile i is a pattern matching files to exclude No filesonly Stores only file entries No false Specifies the patterns matching files to All files are includes include aS a comma or Space separated No l included list Specifies the name of a file where each line includesfile i i is a pattern matching files to include No Preserves the compression as it has been fal using the compress attribute Available iG E since Ant 1 6 No No keepcompression in archives you re compressing instead of Specifies whether you want to update or update overwrite the destination file in case it false exists Specifies what you want to do when no whenempty files match Possible values are fail skip skip and create S One of destfile zipfile Deprecated Use dest file Or zipfile This task supports any number of nested fileset elements to specify the files to be included in the ZIP file The zip task supports any number of nested zipfileset elements which support all the attributes of fileset see Table 2 8 as well as the ones you see in Table 4 5 Table 4 5 The additional zipfileset attributes Attribute Description Required Specifies a 3 digit octal string wh
198. ested fileset element at all if you don t want to because the built in attributes of the task give you all the support you need Each time we come across such a task I ll be sure to mention this The FileSet dir attribute becomes srcdir In the javac task because a dir attribute would be ambiguous in the javac task Is it the source or destination directory 2 3 2 1 Default excludes Some files are excluded by default from file sets since they correspond to system or temporary files of various kinds Here are the patterns excluded by default recall that means the current directory or any subdirectory of the current directory kAx e xx downloaded from lib ommolketab ir downloaded from lib ommotketab ir CVS e cvsignore 0CCU 2073 Vssver scc 83y e syn e x DS Store If you do not want these default excludes applied you can disable them with defaultexcludes no In types such aS FileSets You can modify the list of default excludes by using thedefaultexcludes task 2 3 3 Working with Groups of Directories Directory sets DirSets are types corresponding to groups of directories This type is great for grouping directories together and handling them at one time with various tasks DirSets can appear inside various tasks or at the same level aStarget like file sets directory sets can contain nested include includesfile exclude
199. etab ir downloaded from lib ommoltketab ir Team LiB Chapter 1 Getting Started Build tools are one of the most boring items developers must have available in their development cycle They aren t sexy they aren t going to impress your friends and you ll hardly notice a build too at all until it s time to redeploy that 1 000 class Java application you ve been working on Then all tr interesting code killer IDEs and amazing design patterns aren t worth nearly as much as typingant and calmly watching your boring build tool handle complicated dependencies deployment onto multiple servers via FTP and SSH and log errors It is here that build tools like Ant truly shine At its most basic all a good build tool does is take source code compile it and create a working application When you re writing a single class application this isn t a big deal in fact it can be annoying to manage a build system instead of typingjavac But it s a different story when you start working with multiple source files with multiple dependencies need to check code out of a central repository automatically test the code and deploy it to some remote destination You can end up with dozens of tasks to complete each time you want to build your application which is the last thing you want to spend time on when you re already brain dead from an all night debugging session When new members join your team you ll have to walk through this whole process agai
200. ethod params gt lt method params gt lt method gt lt trans attribute gt Mandatory lt trans attribute gt lt container transaction gt downloaded from lib eommolketab ir downloaded from lib ommotketab ir lt ejb jar gt XDoclet is a powerful tool that s still developing Currently you can only run it in Ant but a command lil tool is in the works Once you get the hang of it XDoclet helps with Web and EJB application develoome in a way that makes sense when you modify your code you modify the deployment descriptors and the EJB code you generate at the same time It s a tool worth watching downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 9 6 Developing Enterprise JavaBeans Ant provides a number of optional tasks for developing EJ Bs Generally these tasks are specific to the particular vendor s EJB Server Currently these tasks support these servers e Borland Application Server 4 5 e IBM WebSphere 4 0 e iPlanet Application Server 6 0 e JBoss 2 1 and above EJB servers e JONAS 2 4 x and 2 5 Open Source EJB server e Weblogic 4 5 1 through to 7 0 EJB servers The Ant EJB tasks and the servers they target appear in Table 9 14 Table 9 14 The Ant EJ B tasks Task Does this Application servers Specifies you want to create a client jar file corresponding to an EJB jar file Borland Application Server 4 5 and 5 x blgenclient Specifies you want to
201. etting you batch your executions and work with external programs as if they supported filesets In Example 7 5 the build file is running the C compilergcec on a fileset In this case the apply task executes the command line gcc c o target source for each c file In src where source with the name of each matching c file in turn and target is replaced with the name of the corresponding o output file you want created Example 7 5 Using the apply task ch0O7 apply build xml lt xml version 1 0 gt lt project default main gt lt property name src location source gt lt target name main gt lt apply executable gcc gt lt arg value c gt lt arg value o gt lt targetfile gt lt srcfile gt Ti lese div Si1 ere anclides c J gt lt mapper from c to o0 type glob gt lt apply gt lt target gt lt projyect gt You can see this task s attributes Table 7 4 Table 7 4 The apply task s attributes Attribute Description Required Default Specifies if you want source filenames to be addsourcerile added to the command automatically Since No Thue Ant 1 6 downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default a Specifies whether you want to append to No stad output and error files Yes If you specify a nested mapper Specifies the directory where the command Should be e
202. exclude name beta gt lt patternset gt lt fileset gt You can see the attributes of this type inTable 2 12 Table 2 12 The patternset type s attributes Attribute Description A list of the patterns matching files you want exluded Comma or space separated excludes list excludesfile Specifies a name of a file each line of the file is interpreted as anexclude pattern A list of the patterns matching files you want included Comma or space separated includes list includesfile Specifies a name of a file each line of the file is interpreted as aninclude pattern PatternSets can include nested include includesfile exclude and excludesfile elements and you can nest PatternSets within one another 2 3 6 Selectors Besides all the types we ve seen selectors are powerful types and go far beyond selecting files basec on filenames They let you select files that make up a file set based on many criteria such as what text a file contains the date a file was modified the size of a file and more Selectors have become one of the coolest things in Ant and you can see Ant s core selectors which come built into Ant in Table 2 13 Table 2 13 The core selectors Selector Means contains Selects files that contain particular text containsregexp Selects files whose contents contain text that matches a given regular expression downloaded from lib ommolketab ir downloaded from lib om
203. f a is false where a is a boolean value assertNotNull a Tests if ais not null where a is an object or null assertNotSame a b Tests if a and b do not refer to the identical object assertNull a Tests if ais null where a is an object or null assertSame a b Tests if a and b refer to the identical object downloaded from lib ommolketab ir downloaded from lib ommolketab ir assertTrue a Tests if ais frue where a is a boolean value To work with J Unit you modify your code to extend the junit framework TestCase Class which in turn extends the junit framework Assert Class After Subclassing the TestCase class you can use the various assert xXxx methods to test the results from your newly compiled code Each of these methods along with their various versions are listed inTable 5 1 Though your code extends the Testcase Class these methods are part of TestCase S base class the Assert class Table 5 1 The junit framework Assert methods Method Does this Tests if two booleans are equal Static void assertEquals boolean expected boolean actual Static void assertEquals byte expected byte actual Tests if two bytes are equal static void assertEquals char expected char actual Tests if two chars are equal Tests if two doubles are equal within a value named delta Static void assertEquals double expected double actual double delta static void assertEquals fl
204. f the latest version of a project before eve and tags the repository with a unique build number after every build It Supports many repository adapters including Concurrent Version System CVS Visual Source Safe Perforce Clearcase PV StarTeam MKSIntegrity and Filesystem Anthill automatically updates a project intranet site with from the latest build Anthill comes in two versions Anthill Pro fairly expensive and Anthill OS free To install Anthill dowr the binary distribution you want and expand it Copyanthill war from the expanded dist directory to a We server s application deployment directory such as thewebapps directory of a Tomcat server installation Anthill is designed to be used with a Web server that can execute Java code like Tomcat and you can c Tomcat free from http jakarta apache org tomcat Anthill was developed and has only been tested Lt the Tomcat server though it s supposed to work with any servlet container Anthill gives you a serviet based console hosted by Tomcat or similar server that lets you configure yo automatic build process Anthill is designed to check source code out of a code repository automatically build that code For example you can test your Anthill installation by logging into the Anthill CVS server to retrieve the a project named anthill test using the password anthill example cvs d pserver anthill example cvs2 urbancode com usr local anthill test login Logging in to
205. fication time of the file Use the formats MM DD YYYY HH MM AM_or_PM or MM DD YYYY No HH MM SS AM_or PM datetime tide Specifies the name of the file whose time and or date Yes unless you use a Information you want to change nested fileset element downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required millis Specifies the new modification time of the file given in epoch No milliseconds that is since midnight Jan 1 1970 The touch task can contain nested fileset elements to touch multiple files at once downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 4 2 Preparing to Deploy Ant supports several tasks for setting up a deployment environment such aSdelete and mkdir Both these tasks can be used locally or on a network to set up the directory structure you need to deploy applications If you want to create and delete directories remotely take a look at theftp task coming up later in this chapter 4 2 1 Deleting Existing Files When deploying delete IS great to clean up a previous installation or to clean deployment directories before installing This task deletes a single file a directory and all its files and subdirectories or a set of files specified by one or more FileSets Using this task you can delete a single file lt delete file lib Project jar gt Or you can delete an entire directory includi
206. fies the location of the script if it s stored in a file as opposed to being No inline downloaded from lib ommolketab ir downloaded from lib ommotketab ir IN script you can access Ant tasks with the Name createTask method where Name is the project s nar For instance Example 12 15 shows how to use the echo task from JavaScript to display numbers using loop Ant properties are available to your script s code as in this case where themessage property s valu is displayed You have access to a built in project object in scripts so for example you could find the value of the message property aS project getProperty message Example 12 15 Build file for executing J avaScript ch12 script build xml lt project name js default main basedir gt lt property name message value No worries gt lt target name main gt lt script language Javascript gt lt CDATA echo js createTask echo main addTask echo for loopiIndex 1 lLoopiIndex lt 10 loopiIndex echo setMessage LoopIndex echo execute echo setMessage message Lie Jeri ot lt target gt lt project gt Here s what this build file looks like at work where JavaScript is executing the Antecho task Cool Sant Buildfile build xml main OO oF Ol e w NH Ae downloaded from lib ommolketab ir downloaded from lib ommolketab ir echo 9 echo 10 echo No worries BUILD
207. for the deployment descriptor for JOnAS jrun Provides support for jrun localhomeinterface Generates local home interfaces for EJ Bs downloaded from lib ommolketab ir downloaded from lib ommolketab ir Element Description localinterface Generates local interfaces for EJ Bs nvesoft Generates MVCSoft s XML oc4j Generates OC4J specific deployment descriptor orion ejb jar xml openejb Provides support for openejb jar xml deployment descriptors for OpenEJ B orion Provides support for Orion s orion ejb jar xml packagesuns ituren you want to substitute a new package for the package in generated pramati Provides support for Pramati deployment files remotefacade Provides support for stage 2 of remote facade generation remoteinterface Provides support for remote interfaces for EJ Bs resin ejb xml Provides support for Resin session Provides support for sessions strutsform Provides support for a Struts ActionForm based on an entity EJB subTask Specifies a subtask for this task sunone Provides support for configuration files for EJB jars in iPlanet SUnONE utilobject Provides support for util objects valueobject Provides support for value objects for Entity EJ Bs weblogic Generates deployment descriptors for WLS 6 0 6 1 and 7 0 Generates EJ B related files from one or a set of EJB bean source files that uses websphere custom EJ BDoclet JavaDoc tag
208. from lib ommoltketab ir Chapter 11 Integrating Ant with Eclipse Ant is the premiere build tool for Java developers and Eclipse is the premiere integrated develoomer environment IDE for Java programmers Eclipse is great at visual development and Ant is great for builds For that reason the latest Eclipse version 3 0 comes with Ant 1 6 1 the version of Ant this book was written with and there s an extensive Ant interface in Eclipse Doesn t Ant have its own IDE Well sort of Antidote started in 2000 was Supposed to have been the Ant IDE see http ant apache org projects antidote index html Unfortunately that project appears to be more or less moribund largely because the big guys behind Eclipse have been integrating Ant into their IDE now downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 11 1 Introducing Eclipse If you re a Java developer you know how finicky Java can feel at times Missedimport statements forgotten variable declarations omitted semi colons garbled syntax and typos will cause the Java command line compiler javac to cough and display pages of error messages The error messages tell you that javac Knows what the error is so why doesn t it just fix the problem and let you continue developing javac can t fix the problem to do that you can use an IDE which will catch errors before you compile and suggest solutions Java is badly in need of a good IDE and the p
209. g modifying text lists of files mappers as path like structures selectors as 2nd working with groups of directories working with groups of files working with patterns downloaded from lib eommolketab ir downloaded from libeommolketab ir Index A B C D E F G H 1 Y K L M N O P Q R S M U V W X Z umask attribute ftp task UMASK permissions Unix 2nd undeploy action JOnAS servers weblogic tool undeploy task 2nd unedit command CVS Unicode characters 2nd unit attribute format task Unix environment build process 2nd chmod task and crontab utility 2nd 3rd end of line characters exec task and executing shell commands file permissions and installing Ant MAC OS and permissions and scheduling automatic builds 2nd verbose build 2nd unjar task 2nd unless attribute batchtest element elements supporting 2nd fail task and 2nd formatter task param element target element test task Unpack class unpackage mapper 2nd untar task 2nd unwar task unzip task 2nd update action JONAS servers weblogic tool update attribute ear task jar task 2nd war task downloaded from lib eommolketab ir downloaded from lib eommolketab ir zip task update command CVS 2nd uptodate element condition task uptodate task attributes for description file modification dates and mappers and package mapper and uri attribute taskdef task uri
210. gApp destfile changelog xml gt lt target gt lt project gt Here s the resulting change log changelog xmI lt xml version 1 0 encoding UTF 8 gt lt changelog gt ie lt date gt 2005 02 24 lt date gt lt time gt 16 18 lt time gt lt author gt lt CDATA steven gt lt author gt lt file gt lt name gt org antbook ch06 GreetingClass java lt name gt lt revision gt 1 1 lt revision gt lt file gt lt msg gt lt CDATA The Greeting App gt lt msg gt lt entry gt lt Lentry gt lt date gt 2005 06 22 lt date gt lt time gt 16 25 lt time gt suc nor gt lt ICDATA sSteven l gt lt 7 author gt lt file gt lt name gt org antbook ch06 GreetingClass java lt name gt lt revision gt 1 3 lt revision gt lt prevrevision gt 1 2 lt prevrevision gt downloaded from lib ommolketab ir downloaded from lib eommolketab ir lt file gt lt msg gt lt CDATA empty log message gt lt msg gt lt entry gt Sulit y lt date gt 2005 02 25 lt date gt lt time gt 16 24 lt time gt lt author gt lt CDATA steven gt lt author gt lt file gt lt name gt classpath lt name gt lt revision gt 1 1 lt revision gt lt file gt lt file gt lt name gt project lt name gt lt revision gt 1 1 lt revision gt lt file gt lt msg gt lt CDATA The Greeting App gt lt msg gt lt entry gt Sule lt date gt 2005 02 25 lt date gt lt time gt 16 3
211. get gt lt target name jJar depends compile gt lt jar destfile Project jar basedir S output gt lt target gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt project gt Here s what the build output looks like Sant Bulldfile build xml compile javac Compiling 1 source file to home steven ant chl2 attributetask output jar jar Building jar home steven ant chl2 attributetask Project jar main project The language is English BUILD SUCCESSFUL Total time 4 seconds 12 2 4 Making Builds Fail Want to make a build fail Make your task code throw anorg apache tools ant BuildException For example if your custom task supports a failonerror attribute you might use code something like this public void setFailonerror boolean failOnError this fail failOnError public void execute throws BuildException if real 4 if error throw new BuildException Attribute language is required else Ant will display the text you pass to theBuildException constructor in the fail message 12 2 5 Handling Nested Text Ant tasks can support nested text and custom tasks can support such text as well Take a look at Exam 12 7 which includes a project task that contains the nested text No worries downloaded from lib ommolketab ir downloaded from lib ommotketab ir Example 12 7 Build file for accessing nested text ch12 nestedtext bu
212. gt lt exclude name java gt lt exclude name class gt lt exclude name txt gt lt fileset gt eens lt target gt lt project gt Here s what running this build file looks like in Windows when uploading the results of a build to a remote server C ant chO04 ftp gt ant Dname steven Dpassword let_me_in Buildfile build xml ie mkdir Created dir C ant ch04 ftp bin compile javac Compiling 1 source file to C ant ch04 ftp bin compress jar Building jar C ant ch04 ftp bin Project jar deploy ftp sending files fte transferring C ant ch04 ftp bin Project jar ftp 1 files sent main echo echo Deploying the jar file echo BUILD SUCCESSFUL Total time 10 seconds That s it you ve deployed the results of the build remotely Very cool downloaded from lib ommolketab ir downloaded from lib ommotketab ir If you want to build in delay times to take into account delays in getting responses from a server use the Ant waitfor task You can use the sleep task for this purpose To retrieve files from the server using ftp you set action to get the remotedir attribute to the remote directory and the dir attribute to the directory you want the retrieved files stored in locally lt ftp action get server 000 000 000 000 remotedir cgi bin userid name password password gt lt fileset dir docs gt lt include name html gt lt fileset gt
213. gt lt property name tomcat username value admin gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt property name tomcat password value password gt lt target name main gt lt get srce http localhost 8080 manager deploy path deployment amp amp war file ant deploy app dest deploy txt username S tomcat username password S tomcat password gt lt target gt lt project gt Here s what the build file looks like in action Sant Puildfile uild xml maini get Getting http localhost 8080 manager deploy path deployment amp war file c ant ch08 get app BUILD SUCCESSFUL Total time 1 second Here s what Tomcat wrote to the output file deploy txt OK Deployed application at context path deployment After deployment navigating to http localhost 8080 deployment org antbook ch08 Deploy shows the deployed servlet as seen in Figure 8 1 Figure 8 1 Deploying to Tomcat downloaded from lib ommolketab ir downloaded from lib ommotketab ir For more information on using the Tomcat manager servlet look atmanager html manager howto html in your Tomcat installation The attributes of the get task appear in Table 8 4 Table 8 4 The get task s attributes ee Attribute SS eee Description Paas Required oe dest Specifies the file where you want to store the retrieved data the file where you want to store the retrie
214. he heading font is Adobe Myria Condensed and the code font is LucasFont s TheSans Mono Condensed The illustrations that appear in the book were produced by Robert Romano J essamyn Read and Lesley Borash using Macromedia FreeHand MX and Adobe Photoshop CS The tip and warning icons were drawn by Christopher Bing This colophon was written by Colleen Gorman The online edition of this book was created by the Digital Books production group John Chodacki Ken Douglass and Ellie Cutler using a set of Frame to XML conversion and cleanup tools written anc maintained by Erik Ray Benn Salter John Chodacki Ellie Cutler and J eff Liggett downloaded from lib ommolketab ir downloaded from lib ommotketab ir Index A B C D E F G H H Y K L M N O P Q R S CO U V W X Z downloaded from lib ommolketab ir downloaded from lib eommolketab ir Index A B C D E F G H OY J K L M N O P Q R S CO U V W BX 2 Abbot framework JUnit extension absolute paths AbstractCvsTask class access attribute javadoc task action attribute fto task 2nd 3rd 4th 5th serverdeploy task 2nd actions conditional adapter attribute taskdef task adapito attribute taskdef task add command CVS addBuildFailed Sound method addBuildListener method Project class addBuildSuccessfulSound method addedTags attribute ejbdoclet task webdoclet task additio
215. he optional attribute iS type which holds the name of the datatype or task you expect this reference to be isset Checks if a given property has been set The required attribute isproperty Checks if a string equals any of the strings Ant considers true that iS true yes or on There is one required attribute value holds the value to test not Logically negates the results of a condition r True if at least one of the contained conditions is true True if the operating system matches the attributes you specify The attributes all optional of this element are family Windows dos unix mac win9x sunOS etc name arch meaning architecture and version l LStrue Mi Checks for the existence of a TCP IP listener The required attributes areserver an IP address or DNS name and port socket Hi Identical to the uptodate task True if the target file is at least as up to date as its source code The required attributes are property the property to set srcfile source file to check andtarget file the file you want to check for up to dateness uptodate Here s an example that sets the property omit debug info to true if the property build type contains either of the words release or gold and if the property explicitly include debug info is false lt condition property omit debug info gt lt and gt LOC lt contains string S build type substring release gt lt cont
216. he output fal append file to be appended NG ones to or overwritten Specifies the command command to run Yes remotely Specifies whether you want to stop fail v ailonerror the build if there eeu are errors Specifies the host host you want to work Yes with Specifies the name Yes if you are keyfile of a file holding a using key based private key authentication knownhosts OUT DUEL Output propercy passphrase Specifies the known hosts file Used to check the identity of remote hosts Must be an SSH2 format file Specifies the name of a file in which No you want output written Specifies the name of a property in N O which you want output written Specifies a passphrase you want to use for your private key No user home ssh known_hostswn_hostts Specifies the password to use for SSH downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Attribute Description Required Default poe pore Specifies the port 22 De to connect to mo Specifies whether you want the timeout operation stopped No o wait forever if it timed out in milliseconds Specifies if to trust TRust all unknown hosts No no if set to yes Specifies the username username you Yes want to use 4 3 6 Deploying Remotely Through Email You can deploy using email with themail task attachi
217. hen a manifest is found in a zipfileset or a zipgroupfileset a No skip file is found Valid values are skip merge and mergewithoutmain Filesenly Specifies you want to store only files in the JAR file No false Specifies files to include Give as a comma or includes No Space separated list of patterns Specifies the name of a file containing include includesfile patterns one to a line Specifies whether to create an index This can aid when loading classes Specifies what you want to do with items from keepcompression existing archives as with nested J AR files false Available since Ant 1 6 Specifies the manifest file to use Set to the location of a manifest or the name of aJAR added through manifest a fileset If you re using the name of an added JAR No file the task expects the manifest to be in the JAR at META INF MANIFEST MF PT T Specifies the encoding used to read the J AR No The platform manifest o a Specifies whether if you want to update or ase overwrite the output file in case it exists Specifies what this task should do when when no files match Possible values are fail skip and skip Groan You can refine the set of files to JAR with theincludes includesfile excludes excludesfile and defaultexcludes attributes The jar task forms an implicit FileSet and supports all attributes of fileset though dir becomes basedir as well as the nested include exclude and patternset elements Yo
218. hill work nthill Example build temp mkdir Created dir D anthill work Anthill Example build temp classes javac Compiling 1 source file to D anthill work nthill Example build temp cla copy Copying 1 file to D anthill work Anthill Example build temp classes Tars jar Building jar D anthill p publishDir CVS_Anthill Example Anthill Example 1 compile compile tests mkdir Created dir D anthill work Anthill Example build temp tests classes javac Compiling 1 source file to D anthill work Anthill Example build temp tests classes downloaded from lib ommolketab ir downloaded from lib ommolketab ir jar Building jar D anthill publishDir CVS_Anthill Example Anthill Example tests 1l 1 Jjar run Leste mkdir Created dir D anthill work Anthill Example build temp tests data mkdir Created dir D anthill publishDir CVS_Anthill Example tests junit Running example WidgetTestCase junit Tests run 2 Failures 0 Errors 0 Time elapsed 0 651 sec junit Testsuite example WidgetTestCase junit Tests run 2 Failures 0 Errors 0 Time elapsed 0 651 sec junitreport Using Xalan version Xalan Java 2 2 D11 junitreport Transform time 105l1ms doc javadoc mkdir Created dir D anthill publishDir CVS_Anthill Example api javadoc Generating Javadoc javadoc Loading source files for package example Constructing davaedoc InToOrmaciols s javadoc Standard Doclet version 1 4 0
219. hree predefined formatters e The xmu formatter prints the test results in XML format e The plain formatter prints plain text e The brief formatter will give only brief details only printing in depth information for test cases that failed l Il look at formatting the results of J Unit tests using these formatters in this chapter The attributes of the formatter element appear in Table 5 4 Table 5 4 The formatter task s Attributes Attribute Description Required Default Specifies the name of the custom formatter class you Exactly one of type or classname want to use classname Yes If classname has extension Specifies the extension for the output filename been used Specifies J Unit will only use this formatter if a specified property is set No TRue if downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default eee Specifies a predefined formatter you want to use Exactly one of type or ne Possible values xml plain Or brief classname Specifies J Unit should use the formatter if a specified unless true a a is not set lusefile Specifies if you want to send output toa file if you want to send output to a file No true 5 1 2 2 Specifying the test class You use the test nested element to specify a class to test The attributes of this element appear in Table 5 5 Table 5 5 The test task s Attributes Attribute Description
220. ibute basedir cabfile compress defaultexcludes downloaded from lib ommolketab ir Table 8 2 The cab task s attributes Description Specifies the directory to archive files from Specifies the name of the cab file you want to create Specifies you want to not only store data but compress it Specifies if you want to use default excludes or not Set to yes no Required Default No Yes No yes Default excludes No are used downloaded from lib ommolketab ir Attribute Description Spader ane cowade al Required Default Specifes the patterns matching files to exclude as excludes a comma or space separated list Specifes the name of a file where each line is a excludesfile No pattern matching files to exclude Specifes the patterns matching files to include as includes No a comma or space separated list l Specifes the name of a file where each line is a includesfile No pattern matching files to include Specifies any additional command line options you N CpLions want to pass to the cabarc tool verbo Specifies you want full verbose output Set to p yes OF no You can use nested fileset elements to specify the files to be included in the archive As with other Ant tasks this task forms an implicit FileSet and supports all attributes of thefileset element dir becomes basedir as well as the nested include exclude and patternset elements downloa
221. ibutes of a file cab Creates CAB files Microsoft archives chgrp Changes file groups on Unix chown Changes file ownership depend Determines which class files are out of date compared to their source echoproperties Lists the project s properties ftp Supports a basic FTP client icontract Generates a property file for iContract an application for controlling assertions image Performs bulk image manipulation jarlib available Checks for the presence of an extension jenit gt cispte Displays the Optional Package and Package Specification information for J AR files jarlib manifest Generates a manifest with required dependencies downloaded from lib ommolketab ir downloaded from lib ommolketab ir Task name Description jarlib resolve Searches for the location of a JAR file setting the location to an ANT property javace Invokes the JavaCC compiler javah Generates C header and source files for the Java Native Interface J NI JPCoverage Runs the J Probe coverage analyzer JcovMerge Merges J Probe coverage snapshots JcovReport Takes a J Probe coverage snapshot and creates a report jdepend este oper pte generate ae wat es Uses the J Depend parser to generate code quality metrics jaos Invokes the JJ Doc documentation generator used with Invokes the JJ Doc documentation generator used with JavaCC ee Inserts parse tree building actions
222. ich gives the user and group dirmode i i using normal Unix conventions Applies to directories only ts1enoae Using this attribute means that the file in the fileset is written with ful leern l this path in the compressed file Default N Specifies a 3 digit octal string which gives the user and group using normal Unix conventions Applies to plain files only me daa i downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required Default prefix Specifies a path to with which prefix all files in the compressed file No Src Specifies a ZIP file instead of a directory as the source of files No You can nest zipgroupfileset elements in a zip task These elements allow you to add multiple ZIP files in the archive The attributes for the zipgroupfileset type are the same as for the fileset type and include the extra attributes for zipfileset elements see Table 4 5 Because the zip task forms an implicit FileSet dir becomes basedir you can use nested include exclude and patternset elements This example zips all files in thedocs directory into the docs guide directory in the archive adds the file readme txt in the current directory as docs readme txt and includes all the html files in examples zip under docs examples lt zip destfile dist docs zip gt lt zipfileset dir docs prefix docs guide gt lt zipfileset dir
223. ich standard output should be directed package Specifies the module you want to check out No gutrut No downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default pace ie Specifies a password file you want to have the No cvspass task read passwords from Specifies the port used by the task to ae communicate with the CVS server we Pores m Suppresses messages This is the same as No Taisi using q on the command line Suppresses all messages This is the same as ae using Q on the command line Since Ant 1 6 me aoi ae Specifies the module to check out by tag No eect This task is designed to pass commands on to CVS verbatim For example here s how you d pass a CVS diff command to the CVS server lt cvs command diff u N output diff txt gt You can nest commandline elements and use the value attribute of argument elements to pass arguments to the CVS server you can pass thediff command this way lt CvVs OUCpuUC patch gt lt commandline gt lt argument value diff gt lt argument value u gt lt argument value N gt lt commandline gt eee or this way using the argument element s line attribute lt cvs output patch gt lt commandline gt lt argument line q diff u N gt lt 7 Command Line lt Ove gt 6 3 1 Checking Out Modules To check out a module from the CVS server you can use thecvs tas
224. ild right under the XDoclet directory xdoclet 1 2 1 is the current version as of this writing while the servlet s code is stored in the directorybuild src java app web Example 9 7 The servliet s build file chO9 serviet build xml lt xml version 1 0 7 gt lt project default main basedir gt lt property name lib dir value lib gt lt property name app dir value gt lt property name app dist dir value S app dir output gt lt property name app src dir value S app dir src gt lt property name app java dir value S f app src dir java gt lt property name app generated srec dir value S app dist dir generated src gt lt property name app web inf dir value S app dist dir web inft gt lt property name app classes dir value S app dist dir classes gt lt property name app xdoclet force value false gt lt path id app class path gt lt fileset dir S lib dir gt lt include nane 7ar gt lt fileset gt lt path gt lt target name init gt L_Slalmp lt format property TODAY pattern d MM yy gt lt tstamp gt lt taskdef name webdoclet classname xdoclet modules web WebDocletTask classpathref app class path gt lt mkdir dir app classes dir gt lt mkdir dir S app generated sre dir gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt target gt lt target name webdoclet depe
225. ild x lt sml wersi0on 1 0 7 gt lt project basedir default main gt lt property name srce value src gt lt property name output value output gt lt target name main depends jar gt lt taskdef name project classname Project classpath Project jar gt lt project gt No worries lt project gt lt target gt lt target name compile gt lt mMkKadLe dir S output gt lt javac srcdir S src destdir S output gt lt target gt lt target name jar depends compile gt lt jar destfile Project jar basedir S output gt lt target gt sJ project In your task s code you can receive access to an element s nested text with theaddText method The text will be passed to this method and Example 12 8shows how to retrieve that text and display it Example 12 8 Accessing nested text ch12 nestedtext src Project java import org apache tools ant Task public class Project extends Task SCring text public void addText String text this text text public void execute System out printin text Here s what you get when you run this build file and the custom task with the nested text No worries Example 12 7 downloaded from lib ommolketab ir downloaded from lib ommotketab ir Sant Buildfile build xml compile mkdir Created dir home steven ant ch12 nestedtext output javac Compiling 1 source file to home steven a
226. image you antlogo gif from the No want the splash screen to display classpath Sets the length of time the splash screen should No ane be visible Set to a value in milliseconds If you need to retrieve an image from behind a firewall use the Antsetproxy task downloaded from lib ommolketab ir downloaded from lib ommotketab ir 10 3 Subtituting Text Using Regular Expressions The replaceregexp task can replace every occurrence of a given regular expression with a Substitution pattern in a selected file or set of files The output file is written only if it differs from the existing file Example 10 2 uses replaceregexp where text in the XML comment in the build file matching Here s a comment is converted to Here s an XML comment Example 10 2 Using regular expression substitutions ch10 regexp build xml lt xml version 1 0 gt lt project default main basedir gt lt Here s a comment gt lt target name main gt lt replaceregexp match a comment replace an XML comment gt lt fileset dir includes xml gt lt replaceregexp gt lt target gt lt project gt Here s what the build file looks like after you run it lt xml version 1 0 gt lt project default main basedir gt lt Here s an XML comment gt lt target name main gt lt replaceregexp match a comment downloaded from lib ommolketab ir downloaded from li
227. inG xx lt echo gt lt target gt lt target name init gt lt mkdir dir S output gt lt target gt lt target name compile gt lt javac srcdir srce destdir S output gt lt target gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt target name run failonerror true gt lt java classname Project fork true gt Clasepaci lt pathelement location output gt lt claseoacn gt lt arg value 0OK gt lt java gt lt target gt lt project gt Here s what you see when you run this build file the code ran without problem and recovered the command line argument passed to it Sant Buber ales D uild xml ini mkdir Created dir home steven ch07 bin compile javac Compiling 1 source file to home steven ch0O7 bin run java You said OK main echo echo Building and Panning echo BUTLE SUCCHOCE UL Total time 4 seconds The many attributes for this task appear in Table 7 1 If things go wrong when you run this task there may be a conflict with the current JVM which is running Ant In that case setfork true to use a new JVM Table 7 1 The java task s attributes downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default Oe Specifies whether you want to append to output and No T error files Deprecated Use nested arg elements
228. into source code using the JJ Tree i preprocessor for the J avaCC compiler a slink Deprecated Merges archive contents Use thezip and jar tasks with the ae a T and zipgroupfileset attributes instead jprooe Runs various tools from the Runs various tools from the J Probe suite Probe suite Deprecated Compiles JSP pages to Java source code Use Tomcat sjspc task jspc Sone an et ng oO ae Runs unit tests aicbis cure lL a eaiea la Rog Runs unit tests using J Unit Unit junitreport Merges separate XML files Merges separate XML files generated by the J Unit task into a single XML file by the J Unit task into a single XML file ee Highlights stylistic and potential execution problems using the Metamata a peprectea You mer T T wee Analyzer fmimemail Deprecated You can still send mail using thenail task You can still send mail using themail task metrics Generates metrics using the WebGain s Metameta Metrics Quality Analyzer mparse Takes a grammar file and compiles it with MetaMata s MParse compiler native2ascii Takes a native encoded file and converts it to ASCII netrexxc Compiles all NetRexx source files propertyfile Creates or modifies property files pves Gets latest source code from a PVCS repository l Deprecated You can achieve the same results by using themove task and using renamescxtensions a glob mapper replaceregexp Replaces matched text with new text rexec Controls a rexec session from
229. ipse with your own views and editors you ll use a plug in manifest file namedplugin xml If you right click the manifest file and select the Create Ant Build File item Eclipse will create a build file for you If you select Project Generate Javadoc the Javadoc wizard will create an Ant build file that runs thejavadoc tool which you can edit as needed downloaded from lib ommotketab ir downloaded from lib ommoltketab ir 11 2 Running Ant Build Files You have two options to run these build files from within Eclipse You can right clickouild xml in the Package Explorer and select Run Ant Build Doing so runs Ant and gives you the results in Eclipse s Console view Eclipse 3 0 runs Ant in a separate JVM solving many problems that used to plague previous versions The output in the Console view is the same as you d see from Ant if you ran the build file on the command line Buildfile D eclipse3 eclipse workspace AntExample build xml compile javac Compiling 1 source file compress jar Building jar D eclipse3 eclipse workspace AntExample Project jar main echo Building the jar file BULLD SUCCESSFUL Total time 2 seconds If there are problems you can see Ant s output in the Console view Eclipse will give you a summary in the Problems view which you can see by clicking the Problems tab at the bottom of Eclipse The other option to run a build file is to right clickbuild xml in the Package Explorer a
230. iptors by embedding tags in your code much like tags you d use for Javadoc There are entire books written about XDoclet because it s an extensive tool Though there s not room for that level of coverage herethis is a book about Ant not XDocletl Il take a lo at several examples creating Web and EJB applications here giving the XDoclet story from Ant s point o view 9 5 1 Developing Applications You use the XDoclet webdoclet task to develop Web applications The attributes of this task appear in Ta 9 10 and the possible nested elements in Table 9 11 Table 9 10 The webdoclet Ant tasks Attribute Description Required MT Specifies you want to add JavaDoc tags to the No generated classes downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Specifies the destination directory for the generated If destDir is not specified by a dest Dir oul subtask E tae Specifies tags that should not be automatically written to output files force Specifies you want generation of files to be forced K No Er Specifies the directory where subtasks will look for files No but should be set if you i that they should merged with their generated files want to use the merge feature verbose Specifies you want verbose feedback No Table 9 11 The webdoclet Ant task s nested elements Element Description configParam Specifies configuration parameters you want to use deploymen
231. ire permission Answering a question by citing this book and quoting example code does not require permission Incorporating a significant amount of example code from this book into your product s documentationdoes require permission We appreciate but do not require attribution An attribution usually includes the title author publisher and ISBN For example Ant The Definitive Guide Second Edition by Steve Holzner Copyright 2005 O Reilly Media Inc 0 596 00609 8 If you feel your use of code examples falls outside fair use or the permission given above feel free tc contact us at permissions oreilly com downloaded from lib ommolketab ir downloaded from lib ommoltketab ir We d Like to Hear from You Please address comments and questions concerning this book to the publisher O Reilly Media Inc 1005 Gravenstein Highway North Sebastopol CA 95472 800 998 9938 in the United States or Canada 707 829 0515 international or local 707 829 0104 fax O Reilly maintains a web page for this book which lists errata examples and any additional information You can access this page at http www oreilly com catalog lt BOOK gt To comment or ask technical questions about this book send email to bookquestions orelilly com For more information about our books conferences Resource Centers and the O Reilly Network see the following web site http www oreilly com downloaded from lib ommolk
232. jar task and you can use nested dtd elements to specify the local location of DTDs to be used when parsing the EJB deployment descripto see Table 9 2 for the dtd element s attributes You can use nested support elements to specify additional class files to be included in the generated Jar files The support element is a fileset so it can reference a fileset declared elsewhere or it can be defined with the appropriate include and exclude nested elements The ejbjar task Supports vendor Specific nested elements which let you use the vendors deployment tools Vendor specific nested elements provide support for various vendor deployment tools If no nested vendor specific deployment elements are present the task will create a generic EJ B jar file For each nested deployment element the vendor specific deployment tool is run to generate a jar file for deployment to that vendor s EJB server Here are the legal vendor specific nested elements borland For Borland Application Server 4 5 and 5 x i1Planet For iPlanet Application Server 6 0 jboss For J Boss jonas For JOnAS 2 4 x and 2 5 weblogic For Weblogic 5 1 to 7 0 downloaded from lib ommolketab ir downloaded from lib ommolketab ir websphere For IBM WebSphere 4 0 These vendor specific elements can become involved For example the attributes of theweblogic element used to control the weblogic ejbc compiler for generating Weblogic EJB jar files appear
233. ject project oote CUC DrINUIN pro ject reruralrue J17 System out printin project return4 System out printlin project returnObject downloaded from lib ommolketab ir downloaded from lib ommotketab ir Besides writing test cases like these you can add two additional methods setUp and tearDown to your code These methods act much like constructors and destructors for your tests protected void setUp Lets you perform initialization for example opening a network connection protected void tearDown Lets you clean up after the tests are completefor example closing a network connection For further details on how J Unit works see the J Unit site at http www junit org index htm 5 1 2 Performing Tests with the junit Task The Ant junit task lets you run J Unit tests from Ant It s an optional task so you ll need need to install junit jarwhich you get from http www junit org eein the Ant lib directory Using junit you can tell Ant which class files you want tested and J Unit will run the test cases in those files The attributes of the junit task appear in Table 5 3 Table 5 3 The junit attributes Attribute Description Required Default ae Specifies the directory where you want to run the No JVM Ignored if fork is disabled EEEE ES Specifies the name of a property you want set in No case there was an error PAET es Specifies the name of a property in case the task No failed Remo
234. k primarily to ensure the sequential executio of a subset of tasks in the parallel task The sequential task has no attributes and has no nested elements besides the Ant tasks you want to run Here s an example which uses thewlrun task to start the Weblogic Web server waits for it to Start runs a J Unit test and then stops Weblogic lt parallel gt lt wlrun taskname server classpath S weblogic boot classpath wlclasspath weblogic classes code jars name antserver home weblogic home properties antserver antserver properties gt lt sequential gt lt sleep seconds 60 gt lt junit printsummary yes haltonfailure yes gt lt formatter type plain gt lt batchtest fork true todir reports tests gt lt batchtest gt lt uno lt wlstop gt lt sequential gt lt parallel gt downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Chapter 8 Developing for the Web Developing for the Web is bread and butter for Ant developers There is a wide spectrum of tasks at your disposal Chapter 4 introduced packaging and deploying applicationsincluding Web applicationsi with the move copy ftp telnet sshexec and mail tasks but Ant offers more This chapter covers the tasks specifically designed for packaging Web applications such aSwar cab ear and jspc and for deploying them such aS get serverdeploy and scp I ll cover the custom Ant tasks targeted to specific se
235. k without specifying a CVS command the default for the command attribute is checkout In Example 6 1 a module named GreetingApp Is checked out and stored in a directory named project downloaded from lib ommolketab ir downloaded from lib ommotketab ir In this and the following CVS related build files you can omit thecvspass task If you ve stored your password in the cvspass file which is what cvspass does If you omit cvspass set the cvsroot attribute in the cvs task or set the CVSROOT environment variable Example 6 1 Checking out a CVS module ch06 checkout build xml lt xml version 1 0 gt lt project default checkout basedir gt lt property name cvs dir value project gt lt target name checkout gt lt cvspass cvsroot pserver steven STEVE home steven repository password opensesame gt lt cvs package GreetingApp dest S cvs dir gt lt target gt lt project gt Here s what this build file looks like in action Sant Bulldfile build xml checkout evs Using cvs passfile home cvspasss cvs cvs server Updating GreetingApp U GreetingApp project cvs cvs server Updating GreetingApp org cvs cvs server Updating GreetingApp org antbook evs cvs server Updating GreetingApp org antbook ch06 cvs U GreetingApp org antbook ch06 GreetingClass java cvs U GreetingApp classpath Levee BUILD SUCCESSFUL Total time 2 seconds
236. ke structure As you can imagine you have to work with paths frequently For example a task likejavac Supports the path attributes srcdir classpath Scurcepalh bool classpetn and extDirs all of which are handled as path like structures That means you can set them as attributes lt javac destdir build classpath classes jar srcdir src gt debug on gt lt javac gt You can set paths as nested elements not just as attributes and you do that with thesrc classpath sourcepath bootclasspath and exTDirs elements For the javac task the srcdir attribute becomes the src element Nested elements are a good idea when you have multiple paths you want to work with that would otherwise be assigned to the same attribute Here s an example lt javac destdir S build classpath classes jar debug on gt lt srce path src gt lt srce path srce2 gt lt javac gt In addition when you want to specify path like values a nested element can be used with internal pathelement elements which specify paths like this lt javac destdir S build classpath classes jar debug on gt lt STe path sra gt lt src gt lt pathelement path src2 gt lt pathelement path src3 gt lt src gt lt javac gt IN pathelement the location attribute specifies a single file or directory relative to the project s base directory or an absolute filename while thepath attribute holds colon separated
237. l the XML document to transform which holds data about three U S states lt xml version 1 0 encoding UTF 8 gt States slace lt name gt California lt name gt lt population units people gt 33871648 lt population gt lt 2000 census gt lt capital gt Sacramento lt capital gt lt pird Quail lt bird lt flower gt Golden Poppy lt flower gt lt area units square miles gt 155959 lt area gt lt state gt lt SLavte gt lt name gt Massachusetts lt name gt lt population units people gt 6349097 lt population gt lt 2000 census gt lt capital gt Boston lt capital gt lt bird gt Chickadee lt bird gt lt flower gt Mayflower lt flower gt lt area units square miles gt 7840 lt area gt lt state gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt SLalLe lt name gt New York lt name gt lt population units people gt 18976457 lt population gt lt 2000 census gt lt capital gt Albany lt capital gt lt bird gt Bluebird lt bird gt lt flower gt Rose lt flower gt lt area units Square miles gt 47214 lt area gt lt state gt lt states gt In this example the names of the states are extracted and used to create an HTML document with style xsl lt xml version 1 0 encoding UTF 8 gt lt xsl stylesheet version 1 0 xmins xsl http www w3 org 1999 XSL Transform gt lt xsl template match States gt lt HTML gt lt BO
238. l task timediffauto attribute ftp task timediffmillis attribute ftp task timeout attribute apply task exec task 2nd java task junit task parallel task sshexec task telnet task timeouts handling timestamp property format element timestamps 2nd timezone attribute format task TimeZone class Java to attribute glob mapper and mapper element regular expressions and slashes and to element mail task TODAY property tstamp task 2nd todir attribute batchtest element checksum task copy task 2nd junitreport task report task scp task 2nd test task tofile attribute copy task junitreport task token attribute filter task tokenfilter element FilterChain type tokens 2nd tolist attribute mail task Tomcat web servers Anthill and deploying to Jasper JSP compiler war files and tooltips torefid attribute reference element toString method JUnit downloaded from lib eommolketab ir downloaded from lib eommolketab ir totalproperty attribute checksum task touch task 2nd translate task translatePath method Project class TraX processor true false tests 2nd trust attribute scp task 2nd sshexec task TSTAMP property tstamp task 2nd tstamp task 2nd type attribute apply task available task chmod task formatter task mapper element type selector typedef task 2nd types See also properties See also properties adding core 2nd creating file filters 2nd filterin
239. lang String toProcess specific form Letting a custom task interact with the rest of the build through the use of properties is an important pa creating custom tasks Take a look at Example 12 3 which is the code for an Ant task that reports the name of the project using the ant project name property and the current location in the build file with t getLocation method Example 12 3 Accessing projects and properties ch12 projecttask src Project java import org apache tools ant Task public class Project extends Task public void execute DUELING name GeLPro ject getProperty ant sprol ecl name System out printin Welcome to project name TH pC GeChocacion 73 Example 12 4 shows the build file for this custom task Example 12 4 Build file for accessing properties ch12 projecttask build x xi version LUT gt lt project name TheTask basedir default main gt lt property name src location src gt lt property name output location output gt downloaded from lib ommolketab ir downloaded from lib ommoltketab ir lt target name main depends jar gt lt taskdef name project classname Project classpath project jar gt lt project gt lt target gt lt target name jar depends compile gt lt jar destfile project jar basedir output gt lt target gt lt target name compile gt lt mkdir dir S output gt lt Javac
240. lays the values of the properties created byproperties xml name1 firstName and namel lastName This example defines attributes for the name1 and firstName properties creating an attribute named language which can be accessed aS namel language and as namel firstName language The build file displays the values of these properties Example 9 3 Loading XML properties ch09 xmlproperty build xml lt xml version 1 0 gt lt project default main gt lt xmlproperty file properties xml gt lt target name main gt lt echo gt S namel language S namel firstName S namel firstName language S namel lastName lt echo gt lt target gt lt project gt Here s what the build file displays when run Sant Bulldfile build xml downloaded from lib ommolketab ir downloaded from lib ommolketab ir main echo echo english echo Stefan echo german echo Edward echo BUILD SUCCESSFUL Total time Q seconds The attributes of this task appear in Table 9 5 Table 9 5 The xmlproperty task s attributes Attribute Description Required Default E E EAN Specifies you want to treat attributes as No utes nested elements e Specifies the XML file you want to parse for Yes properties POPE E EEEE peewee S Specifies you want to include the semantic No E attribute name as part of the property name E Specifies you want to make the XML root tag No ae the first value in the property nam
241. ld xml Init mkdir Created dir C ant ch an eall bin compile javac Compiling 1 source file to C ant ch03 antcall bin compress jar Building jar C ant ch03 antcall bin Project jar main displayMessage echo msg Building the jar file BULLD SUCCESSFUL Total time 6 seconds This is something like a subroutine call and when using it there s a tendency to start turning build files into programs That s almost always a mistake however if you find yourself uSingant call frequently you re probably not using Ant the way it was intended There s a tendency to start writinc build files as if you were writing programming code with subroutines but the best way to write build files is to let Ant doing its thing and check the dependencies If this seems like this is the second time you ve heard this it is because it s that important 3 3 2 Calling Ant Tasks in Other Build Files The ant task Is nearly identical to the antcall task except that it lets you call targets in other build downloaded from lib ommolketab ir downloaded from lib ommotketab ir files Using this task you can create subproject build files which let you divide your builds into a cor build file with ant tasks to call the other build files as needed This kind of technique can be useful when your build files are enormous and things are getting too complex to handle in single files this i one of the ways that Ant scales to meet project needs
242. le code for Ant has multiple build filenames to make the separation of examples clearer For example if you have a build file named project xml that you want to use you can specify that Ant should use that build file with or file or buildfile sant f project xml downloaded from lib ommolketab ir downloaded from lib ommotketab ir If you use the fina file option Ant will search for a build file first in the current directory then in the parent directory and so on until a build file with the supplied name is found or the root of the filesystem is reached 1 5 3 Customizable Environment Variables Ant scripts which start Ant use some customizable environment variables JAVACMD Holds the full path of the Java executable Use this to launch a different JVM than JAVA_HOME bin java exe ANT_OPTS Command line arguments that should be passed to the JVM unchanged ANT_ARGS Ant command line arguments These may be used for example to point to a different logger a new listener or to include the fina flag in all invocations of Ant The Ant wrapper script for Unix will read the file antrc before it starts running On Windows the Ant wrapper batchfileant bat invokes SHOME antrc_pre bat at the start of the Ant process and sHome3 antrc_post bat at the end of that process You can use these files to set or unset environment variables that should only be used during the execution of Ant 1 5 4 Failed
243. lement end up in WEB INF classes e Files contained in the 1ib element end up in WEB INF lib e Files contained in the metainf files end up in META INF downloaded from lib ommolketab ir downloaded from lib ommotketab ir 8 2 Creating CAB Files The cab task creates Microsoft cab archive files and you use this task as you would the jar or zip tasks The cab files are the NET equivalent of war files packaging NET applications for server deployment This task works in Windows using the externalcabarc tool this tool comes from Microsoft which must be in your executable path I m not going to spend much time on this task because the Microsoft Visual Studio IDE has many powerful integrated build tools and wizards that create cab files most Microsoft developers do not need Ant to solve their build problems Here s a quick example using the Antcab task lt cab cabfile S deploy app cab basedir Sf output gt You can get a free copy of the Microsoft C command line compiler csc If your version of Windows doesn t have it Install the NET Framework s Software Development Kit SDK which you can find at http msdn microsoft com downloads The csc compiler is included The attributes of the cab task appear in Table 8 2 It s possible to use this task on other platforms besides Windows but you need to get and compile the libcabinet tool from http trill cis fordham edu barbacha cabinet library Attr
244. lib ommolketab ir downloaded from lib ommotketab ir it s created if it does the files in it are updated lt zip destfile S dist docs zip basedir dist docs update true gt This next example zips all files in the dist docs directory Only html files in the directory api will be zipped and files with the namebeta html are excluded lt zip destfile S dist docs zip basedir S dist docs includes api html excludes beta htmL gt The attributes of this task appear in Table 4 4 A JAR archive is a ZIP file with a manifest if you don t want a manifest in a JAR file use zip instead of jar Table 4 4 The zip task s attributes Attribute Description Required Default eee Specifies the directory where the files you No want to Zip are Specifies that you don t want to store data compress No trus but want to compresses it EE E T Specifies whether you want default No Default excludes excludes to be used or not yes no are used Exactly one of destfile destfile Or zipfile Specifies what you want to do when a duplicate duplicate file is found Valid values areaaa No add preserve and fail encoding No Specifies the ZIP file you want to create The platform s default character encoding Specifies the character encoding you want to use inside the ZIP file downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute D
245. lipse 3 0 can catch syntax errors in Ant build files For example ending a target withk targe gt instead of a lt target gt tag is immediately caught by the Eclipse Ant editor as shown inFigure 11 5 If you let your cursor rest over the circled X icon to the left of the problem line you ll see Eclipse s explanation of the problem Expected lt target gt to terminate element starting on line 3 This kin of syntax checking and corrections alone are worth the price of admission Figure 11 5 Handling syntax errors downloaded from lib ommolketab ir downloaded from lib eommolketab ir ave toiled Eclipse Flall irm lt Paml wersion 71 07 1 gt lt peoject default main gt ey project harget name nain depends compile cc EH main dof ec hos Building tht jar file c hoe JLESTIES Car ger nee compile descr iptirion T Lamp ajevec srodir gt lt Learget gt SLaEGet Hane compresa descriptions Compe jar Jertile Projecr jac basedir EF tar et gt lt praject gt You can reformat an Ant build file indenting everything nicely using the Format command Ctrl Shift F from the Ant editor s context menu or by selecting Edit Format Want to see the value of a property Let the mouse hover over it and its value will appear in a tooltip Under some circumstances Eclipse can generate Ant scripts for you For example if you re creating an Eclipse plug in which extends Ecl
246. lketab ir downloaded from lib ommotketab ir 3 2 Getting Input from the User At some point in a build you may need input from the user For example you might want to ask before deleting a directory with the delete task The delete task is covered in detail in Chapter 4 To get input from the user use the input task which creates a new property based on user input Example 3 1 puts input to work This build file asks whether it s OK to delete thebin directory and if it s not the build fails It queries the user using theinput task and creates a new property do delete based on the user s input Example 3 1 Using the input task ch03 input build xml lt xml version 1 0 gt lt project default main gt lt property name message value Building the jar file gt lt property name src location source J gt lt property name output location bin gt lt target name main depends init compile compress gt lt echo gt message lt echo gt lt target gt lt target name init gt lt input message Deleting bin directory OK validargs y n addproperty do delete lt condition property do abort gt lt equals argl n arg2 S do delete gt lt condition srail if do abort t gt Build aborted lt fail gt lt delete dir S output gt lt mkdir dir 5 output gt lt target gt downloaded from lib ommolketab ir downloaded from lib omm
247. lt projyect gt You can use Ant s ftp task see Chapter 4 for remote deployment to a Web server s base directories downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 8 4 Deploying with SCP Another deployment task available since Ant 1 6 is thescp task which copies a file or FileSet to or from a remote machine running the SSH daemon This task is an optional one and you needjsch jar in the Ant lib directory to use it you can get jsch jar at http www jcraft com jsch index html This task is handy for deployment For example here s how to deploy a single file to a remote host any host you connect to must be listed in your Knownhosts file unless you specifically set theTRust attribute to yes or true lt scp file Project jar todir user password antmegacorp com home steven cgi bin gt You can use the password attribute explicitly to set the password lt scp file Project jar todir user antmegacorp com home steven cgi bin password password gt Here s how to copy a remote file to a local machine lt scp file user password antmegacorp com home steven cgi bin Project jar todir archiva gt Here s how to copy a set of files using a fileset lt scp todir user passwordQantmegacorp com home steven source gt lt fileset dir S src gt lt include name java gt lt fileset gt A SC Example 8 3 gives a complete example build file using thescp task for
248. lt target name test2 depends compile gt lt junit printsummary yes errorProperty test failed failureProperty test failed fork S junit fork haltonfailure yes gt lt formatter type plain gt lt classpath path gt lt test todir results name org antbook Project gt lt 7 Junit gt lt fail message Tests failed if test failed gt lt target gt lt target name test3 depends compile gt lt junit printsummary yes fork yes haltonfailure yes gt lt formatter type brief usefile true gt lt classpath path gt lt test todir S results name org antbook Project gt lt junit gt lt target gt lt target name test4 depends compile gt lt junit printsummary yes fork yes haltonfailure yes gt lt formatter type xml gt lt classpath path gt lt test todir results name org antbook Project gt lt un LtS lt target gt lt target name test5 depends compile gt lt junit printsummary yes fork yes haltonfailure yes gt lt formatter type xml gt lt classpath path gt lt test todir S results name org antbook Project gt lt junit gt lt junitreport todir results gt lt fileset dir S results gt lt include name TEST xml gt lt fileset gt lt report format frames todir S results gt lt Juni treport gt lt target gt lt target name test6o depends compile gt lt junit print
249. lt target name test5 depends compile gt lt junit printsummary yes fork yes haltonfailure yes gt lt formatter type xml gt lt classpath path gt lt test todir S results name org antbook Project gt lt 7 jute Then use junitreport to merge and translate any XML reports into something you can look at ina browser Here s what it looks like in the build file lt target name test5 depends compile gt lt junit printsummary yes fork yes haltonfailure yes gt lt formatter type xml gt lt classpath path gt lt test todir results name org antbook Project gt lt junit gt lt junitreport todir results gt lt fileset dir results gt lt include name TEST xml gt lt fileset gt lt report format frames todir results gt lt junitreport gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt target gt The junit task creates TEST org antbook Project xml and the junitreport task creates TESTS TestSuites xml and the browseable report To see the report open the createdindex html shown in Figure 5 1 Figure 5 1 A J Unit report T Unst Test Results Microsoft Internet Explorer File Edt View Faroribes Took Help sack gt BLE Aeh GiFovontes Meds F G Se Ge Unit Test Results Packages Cesigned for wre vith Joi and Ant org pete pok O _ eee a Sum
250. lters text and can modify that text ArilterChain iS a group of FilterReaders applied in order and functions much like piping one command to another in Unix Using FilterReaderS and FilterChains you Can process text data in advanced ways A number of Ant tasks Support filterchain elements e concart e copy e loadfile e loadproperties move You can create filter chains with your own Java classes or with one of the elements you see inTable 2 16 Table 2 16 FilterChain nested elements Element Does this classconstants Filters and outputs constants as defined in a J ava class Appends a file to the filtered file or prepends a file to the filtered file Two concatfilter optional attributes prepend name of the file to prepend and append name of the file to append E eee eee meee Deletes characters that you specify in the filtered content The required attribute chars holds the characters to delete downloaded from lib ommolketab ir downloaded from lib ommolketab ir Element Does o oesthis Changes non US ASCII characters into the matching Unicode escape escapeunicode E E ed a plus 4 digits lexpandproperties _ Replaces Ant properties of the form 1 with the property s actual value Ant properties of the forms with the property s actual value EE E Defines a generic filter Has one parameter the requiredclassname attribute Supports classpath and param nested elements Re
251. m lib ommotketab ir lt project dir S basedir gt lt include name JjJava gt lt project gt lt target gt lt target name compile gt lt mkdir dir S ourput gt lt javac srcdir S srce destdir S output gt lt target gt lt target name Jar depends compile gt lt jar destfile Project jar basedir output gt lt target gt lt project gt To handle filesets you extend the MatchingTask class In this example the code that supports the custo task reads the value assigned to the dir attribute and uses the org apache tools ant DirectoryScanner class S getIncludedFiles method to scan that directory This method returns an array of filenames which the code displays All the support code appears in Example 12 12 Example 12 12 Supporting filesets ch12 fileset src Project java import java io File import org apache tools ant Task import org apache tools ant BuildException import org apache tools ant DirectoryScanner import org apache tools ant taskdefs MatchingTask public class Project extends MatchingTask privato File direcloryj public void setDir File directory this directory directory public void execute throws BuildException DirectoryScanner directoryscanner getDirectoryScanner directory String files directoryscanner getIncludedFiles for int lLoopIndex 0 loopIndex lt files length lLoopIndex System out prin
252. mand update gt lt target gt lt project gt Here s what you see when running this build file Sant Buildfile build xml login evs Using cvs passfile home cvspass update cvs Using cvs passfile home cvspass cvs cvs server Updating GreetingApp Cvs server Updating GreetingApp org antbook cvs cvs server Updating GreetingApp org s cvs server Updating GreetingApp org antbook ch06 downloaded from lib ommolketab ir downloaded from lib ommotketab ir main echo echo Doda CiG esei echo BULLO SUCCESSFUL Total time 3 seconds This updates your local copy of a module with what s currently in the CVS repository 6 3 3 Committing Source Code After you ve made changes to the code in a checked out module you can send the revised module back to the CVS repository by setting the command attribute to commit as shown in Example 6 3 In this example the build file commits a new version of a checked out module adding the comment New Version Example 6 3 Committing a CVS module ch06 commit build xml lt xml version 1 0 gt lt project default main basedir gt lt property name cvs dir value project gt lt target name main depends l1ogin commit gt lt echo gt Orn CCI sw lt echo gt lt target gt lt target name login gt lt cvspass cvsroot pserver steven STEVE home steven repository password opensesame gt lt target gt
253. mary as Tests Failures Errors Suecensrate 0000 Time 3 a a 100 00 0 050 Prevce Hote fates are anticipated aed checked for with assertions while eors are unanticipabed Packages Nama Tats Evrae allure Tie epee Ot bo ale 3 D D D050 OE A arte You can browse through the results of your tests by clicking the Project link in the frame labeled Classes opening the page you see in Figure 5 2 which reports on each test case Figure 5 2 Browsing test case results downloaded from lib ommolketab ir downloaded from lib eommolketab ir Lindt Test Results Microsoft Internet iI splo Pi Unit Test Results Cariqzved far are vith Jer and Ant Class org anthook Project ineas Name ests trues Fares Thanet Project Bropect 2 Lf Lt 0 050 Tests testTrue Success o 000 testiquals Success gga tasthothiull Swccass o 000 Propertas Clicking the Properties link displays a page showing all property names and values downloaded from lib ommotketab ir downloaded from lib ommolketab ir 5 3 Testing in Batches When you re working with J Unit you can set uptest suites which run multiple tests by extending the TestSuite class import junit framework TestCase import junit framework TestSuite public class NewSuite extends TestSuite static public Test testSuite TestSuite suite new TestSuite suite addTestSuite Project class suite addTestSuite Connector class suite addTestSui
254. me org steve Math property Math present gt Here s another example which sets file present to true if the file build properties exists in the current directory lt available file build properties property file present gt You can see the attributes of this task inTable 2 4 You can set the property value to something other than the default by using the value attribute This task is handy for setting properties that avoid or allow target execution depending on system parameters or the presence of various files For example you may want to load in properties from a property file seeSection 2 2 in this chapter rather than use default values if that property file exists Table 2 4 The available task s attributes Attribute Description Required Default downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default One of classname file or resource Classpath to use when searching for classname glasspath No OF resource h t for EE ET A reference to the classpath to use fo No searches One of classname file or resource filepath The path to use when searching for a file No Set to true to ignore Ant s runtime classes in ignoresystemclasses Searches using only the specified classpath No false instead Affects the classname attribute Pet The name of the property to set with the results ves A of the search One of resource The resource
255. ml Execute runner new Execute runner setCommandline commandline getCommandline try runner execute downloaded from lib ommolketab ir downloaded from lib ommotketab ir catch IOException e System out printin e getMessage In this case the code creates anorg apache tools ant types Commandline object holding the path and name of the executable to launch uses the commandline object s createArgument setValue method to specify the file to open and uses theexecute method of the org apache tools ant taskdefs Execute class to open WordPad The build file for this custom task appears in Example 12 14 Example 12 14 Build file for executing external programs ch12 executetask build xml lt Ia version 1 0 lt project basedir default main gt lt property name srce value src gt lt property name output value output gt lt target name main depends jar gt lt taskdef name project classname Project classpath Project jar gt lt project gt lt target gt lt target name compile gt lt mkdir Gdir S output gt lt javac srcdir srce destdir S output gt lt target gt lt target name jar depends compile gt lt jar destfile Project jar basedir output gt lt target gt si project If you run this build file in Windows after updating the hardcoded paths in the Java code as needed it launch WordPad opening build xml
256. molketab ir downloaded from lib ommoltketab ir 1 3 Ant at Work Rather than go on and on about what Ant can do for you an example can illustrate how easy Ant makes the build process Assume that you have a J ava file calledProject java as shown in Example 1 1 Example 1 1 A simple J ava class public clase Project Public static void main String args 1 Ssystem out printin No worries Assume you want to compile this code and store the results Project class in a JAR file Project jar With Ant and a build file this is a piece of cake By default Ant looks for a build file namedbouild xml That file is a valid XML document Example 1 2 shows the build file for this example Example 1 2 A simple Ant build file lt xml version 1 0 gt lt project default main gt lt target name main depends compile compress gt lt Scno gt Building the jar file lt echo gt lt target gt lt target name compile gt lt javac srcdir gt lt target gt lt target name compress gt lt jar jarfile Project jar basedir includes class gt lt target gt lt project gt To run this Ant build file make sure it s in the same directory asProject java and enter ant at the downloaded from lib ommolketab ir downloaded from lib ommotketab ir command line prompt Ant has been tested on many platforms including Linux Unix versions from Solaris to HP UX Windows 9x N
257. molketab ir Selector Means Selects files that were modified before a particular date and time or that date and time date depend depth diftierent Selects files that are different from a set of target files you specify filename Selects files using a pattern to match filenames modified Selects files if an algorithm gives a different result from that stored Selects files that were modified more recently than files you compare them to Selects files based on how far down they appear in a directory tree present Selects files based on their presence or absence at some other location size Selects files larger or smaller than a particular size type You can nest selectors inside file sets to select the files you want For example here s how to create a file set of HTML documentation files that contain the text selector using thecontains selector Selects files based on their type regular files or directories lt fileset dir S docs includes html gt lt contains text selector casesensitive no gt lt fileset gt The date selector lets you choose file sets based on date as here where I m selecting all documentation files before 1 1 2005 lt fileset dir docs includes html gt Gace Gatrecime O1702 7 2005 2200 2M when bDerore 7 gt lt illeset gt You can use the filename selector much like the include and exclude tags inside a fileset Here s an
258. mple Custom Ant Task Creating new Ant tasks Is simple since all you need IS anexecute method Example 12 1 is a Java class named Greeting that displays the text No worries Example 12 1 A simple Ant task ch12 greetingtask src Greeting java public class Greeting public void execute System out printin No worries To install this class as a new Ant task you compile this code and use thetaskdegf task to declare it in Ant The attributes of the taskdef task are shown in Table 12 1 The taskdef task is based on the typedef task except that the values of two attributes adapter and adapto are preset to fixed values org apache tools ant TaskAdapter and org apache tools ant Task respectively Table 12 1 The taskdef task s attributes Attribute Description Required Default Specifies the adapter which adapter adapts the defined class to No org apache tools ant TaskAdapter another interface class Specifies the interface class to adaptto which to adapt Used with the No org apache tools ant Task adapter attribute Specifies the classname that Yes unless file classname will Support perform the type or resource have or task been specified downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default Specifies the classpath you classpath want to use when searching for No classname Specifies the name of the file file
259. n a server named STEVE anda repository location of home steven repository cvspass would look like lt xml version 1 0 gt lt project default main basedir gt property Name Cvs cir value project gt lt target name main gt lt cvspass cvsroot pserver steven STEVE home steven repository password opensesame gt lt target gt lt project gt The CVS related tasks can read the CVS root value from thecvsroot attribute if they support that attribute or from the cvsroot environment variable In Windows when your username includes a space or spaces you might run into problems with the cvsroot attribute In that case assign a value to the CVSROOT environment variable instead e g C ant ch06 gt set CVSROOT pserver Steven Holzner STEVE home steven repository and then use cvspass Or Other CVS related tasks in your build file normally The attributes of the cvspass task appear in Table 6 3 Table 6 3 Attributes for the cvspass task downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default cvsroot Specifies the CVS repository you want to add an entry for Yes passfile Specifies the password file you want to add the entry to No Ccvspass pasovord Pee the password you want to be added to the password Yes downloaded from lib ommolketab ir downloaded from lib ommolketab ir 6 3 Working with
260. n showing them the ropes and hoping they don t break anything in the process It s for all of these reasons that developersand especially Java programmersturn to Ant Though there are still powerful alternatives to Ant likemake Jam Cons gnumake and nmake nothing is as integrated into the Java programming language Ant is pure Java you ll find line after line of Java code and java files if you obtain a source release of the tool Further some of the most popular projects in the Java universe are built using Ant everything from Tomcat to J Boss to Turbine can go from source to binary by typing ant downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 1 1 Ant s Origins Ant was originally the brainchild of James Duncan Davidson and the word Ant stands for Another Neat Tool a fact that relatively few developers realize Ant 1 0 first appeared in March 2000 J ames Original inspiration was to create a build tool that used a simple XML based format for build files as opposed to the shell commands and involved formatting thatmakefiles used Ant caught on rapidly and newer versions followedAnt 1 1 July 2000 1 2 October 2000 1 3 March 2001 1 4 September 2001 and 1 5 July 2003 The version this book usesversion 1 6 lappeared in February of 2004 Although James Davidson has moved on to work with other build tools Ant continues to evolve on an almost daily basis Ant is an open source Apache communit
261. n 8 5 Deploying to Tomcat Section 8 6 Deploying to Tomcat Section 8 7 Compiling JSPs Section 8 8 Deploying to EJB Containers Chapter 9 XML and XDoclet Section 9 1 Validating XML Documents Section 9 2 Loading Properties from XML Files Section 9 3 Creating Ant Task DTDs Section 9 4 Transforming XML Using XSLT Section 9 5 Using XDoclet Section 9 6 Developing Enterprise JavaBeans Chapter 10 Optional Tasks Section 10 1 Using Sound Section 10 2 Creating Splash Screens Section 10 3 Subtituting Text Using Regular Expression Section 10 4 Handling Dependencies Chapter 11 Integrating Ant with Eclipse Section 11 1 Introducing Eclipse Section 11 2 Running Ant Build Files Section 11 3 Using a Different Version of Ant Section 11 4 Using the Ant View Chapter 12 Extending Ant Section 12 1 Creating a Simple Custom Ant Task downloaded from lib ommotlketab ir downloaded from lib eommolketab ir Section 12 2 Extending the Task Class Section 12 3 Creating Custom Listeners Section 12 4 Creating Custom Loggers Section 12 5 Creating Custom Filters Section 12 6 Creating Custom Selectors Section 12 7 Creating New Types Colophon Index downloaded from lib eommolketab ir downloaded from lib ommotketab ir Copyright 2005 O Reilly Media Inc All rights reserved Printed in the United States of America Published by O Reilly Media Inc 1005 Gravenstein Highway No
262. n Source at sun reflect NativeMethodAccessorImpl invoke0 Native Method at sun reflect NativeMethodAccessorImpl invoke Unknown Source at sun reflect DelegatingMethodAccessorimpl invoke Unknown Source If there s a problem you can use the formatter s output to track it down 5 2 2 Using the Brief Formatter for Reports The brief formatter prints little unless there s been an error Here s how to use it in a new test test3 lt target name test3 depends compile gt lt junit printsummary yes fork yes haltonfailure yes gt lt formatter type brief usefile true gt lt classpath path gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt test todir results name org antbook Project gt lt un lt target gt If everything goes well this formatter displays a brief message during the build test3 J nit Running org a tb ook Project Junit Tests run 2 Failures 1 Errors 0 Time elapsed 0 01 sec And it puts a brief message in TEST org antbook Project txt Testsuite org antbook Project Tests run 3 Failures 0 Errors 0 Time elapsed 0 01 sec Thol OrTg anl book Pro eOr ECRL On the other hand if you reproduce an error as iIntest2 changing the expected value from 4 to 5 you ll see more information in TEST org antbook Project txt Testsuite org antbook Project Tests run 2 Failures 1 Errors 0 Time elapsed 0 01 sec Testcase testHEgquals o
263. n ant ch12 selector sizeOK BULLD SUCCESSFUL Total time 3 seconds In this case the code only copies files less than a megabyte in length but custom seletors like this can select on anything e g file creation date read write status filename and so on downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 12 7 Creating New Types When creating new tasks it s sometimes useful to create new datatypes to be used by those tasks In this example I ll create a new datatype that extends the AntrileList type and interfaces easily to attributes in a custom task This example centers around a new data type ProjectType which extends the AntFrileList class To use that data type I ll develop a new custom task projectTask that Supports nested elements named multiFile each of which supports an attribute named files You can set the files attribute to a string containing multiple file names such as ed txt george txt and the code will create an object of a custom data type ProjectType to contain that list of files Example 12 22 holds the code for the new datatype ProjectType which extends the org apache tools ant types FileList Class In this example the code simply passes the list of files on back to the FileSet base class but you can adapt this code to handle the list of files any way you want Example 12 22 The new data type ch12 type src ProjectType java package data import org apache tool
264. n the J avaLocale class Specifies the offset you want to add to or subtract from the current time if offset No any Specifies the date time pattern you want to use The possible values are pattern Yes defined in the Java SimpleDateFormat class Yes No No property Specifies the property in which you want to store the date time string Specifies the time zone used for generating the time Possible values are timezone i defined in the Java Timezone class Specifies the unit of the offset you ve specified inoffset Possible values are millisecond second minute hour day week month OF year unit downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Chapter 4 Deploying Builds This chapter starts coverage of one of the things Ant does best deployment This chapter covers tasks to package applications for deployment liketar gzip and zip tasks to prepare directories for deployment like delete and mkdir and tasks to deploy applications likecopy and move for local and network deployment as well aS ftp telent sshexec and mail for remote deployment You ll see other deployment related tasks such aStouch to set the deployed files modification dates to a specific value as is done for commercial software deployments fixcrif to fix text file line endings as in readme sh bat html or ini files for different platforms and more Finally you ll learn how to handle build automation se
265. nalparam attribute javadoc task addproperty attribute input task address attribute mail task addsourcefile attribute apply task addTarget method Project class addTaskDefinition method Project class addText method 2nd admin command CVS aiff format algorithm attribute checksum task all set property and element condition task annotate command CVS Ant build files absolute path Ant view and calling tasks in checksums and custom tasks and editing EJB example example importing 2nd projects and properties and 2nd 3rd 4th reformatting downloaded from lib ommolketab ir downloaded from lib eommolketab ir running running in Eclipse scp task example servlet example targets and 2nd 3rd taskdef task example tasks and Tomcat servers and 2nd 3rd 4th war files and 2nd writing in Eclipse XDoclet example XML declaration and Ant build process Anthill and controlling example failure during 2nd scheduling automatic builds stopping testing Ant build tool alternatives to debugger support editions installing 2nd origins process example running testing Ant classpath 2nd Ant editor Eclipse 2nd Ant Home Entries item Eclipse Ant Launcher ant task 2nd Ant view Eclipse ant bat file ant file property 2nd ant java version property ant project name property ant version property ANT ARGS environment variable ANT HOME environment variable example filename length installing An
266. nated by the fail task sant Du uild xml Buildfile build xml iT mkdir Created dir home steven ch0O7 bin compile javac Compiling 1 source file to home steven ch07 bin run java You said OK java Java Result 1 BULLD FAILED nome Stevens cho 7 7bui1 1dZ2 xmi t35 Failed 1 Total time 4 seconds You can set failonerror true In the java task in which case the only possible value for resultproperty IS 0 or the build will terminate That s how the example in the previous topic was written lt target name run failonerror true gt lt java classname Project fork true gt lt Clascpali lt pathelement location output gt lt classpath gt lt arg value OK gt lt java gt lt target gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir If failonerror false and fork false the java task must return a value of 0 or the build will exit because the code was run by the build J VM Making a build fail if there s an error when you run the build s output is a perfect way to test the results of a build if the output doesn t run as it should there s no sense in deploying it Setting failonerror tO true In the java task ensures your build will halt before deployment if the results don t work Here s another example using the java task which forks a JVM and runs a jar file in 512 Megabytes of memory using the entry point indicated by the manifest
267. nd select Run Ant Build this time with an ellipsis three dots This opens the Ant launch configuration dialoc you see in Figure 11 6 The Ant launch configuration is specific to the current project Figure 11 6 Selecting an Ant target downloaded from lib ommolketab ir downloaded from lib ommoltketab ir AntEsample build smil Modify attributes and launch Create a configuration that will run an ant buildfile Mane SrtExarnple build sml Main 4 Refresh zy Buld ve Targets o gt Classpath lt C gt Properties m me B Environment Jal Check targets bo execute O compress Compression target FA man defauit target Main tanget O compie omplation target Apply Revert lt By default the Targets tab is selected in this dialog showing a list of the targets inbuild xmli The default target has been selected you can click the Run button to run that target or you can select other targets to run If you leave the default target selected and click Run you ll see the same result as before in the Console view You can set the execution order of targets shown in the Target execution order box at the bottom of the page the order in which you select the items is the order in which they will run Ant will still run each target s dependencies but you have to be careful in case your changes mess up the overall build order 11 2 1 Selecting the Build File and Passi
268. nds init gt lt webdoclet destdir S app generated src dir excludedtags version author todo force S app xdoclet force verbose false gt lt fileset dir S app java dir gt lt include name Servlet java gt lt fileset gt lt deploymentdescriptor servletspec 2 3 destdir Siaop web int dir gt lt webdoclet gt lt target gt lt target name compile depends webdoclet gt lt javac destdir S app classes dir classpathref app class path debug on deprecation on optimize off gt lt srce path S app java dir gt lt src path S app generated sre dir gt lt javac gt lt target gt lt target name main depends compile gt lt echo gt Using XDoclet lt echo gt lt target gt Sj projoot When you run this build file it ll create a completeweb xml for this servlet here is the crucial part lt servlet gt lt servlet name gt ServletApp lt servlet name gt lt display name gt Servlet App lt display name gt lt servlet class gt app web ServletApp lt servlet class gt lt init param downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt param name gt paraml lt param name gt lt param value gt valuel lt param value gt lt init param gt lt init param gt lt param name gt param2 lt param name gt lt param value gt value2 lt param value gt lt init param gt lt xloa ad on startu
269. ne Cr Converts all EOLs to a Single CR iba Converts all EOLs to a single LF The default is based on platform In Unix the default is 1f For eol No Windows DOS systems the default IS crlf For Mac OS the default Is er Ir Cr downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default Converts all EOLs to the pair CRLF eat Converts all EOLs to a Single CR unix Converts all EOLs to a Single LF dos Converts all EOLs to the pair CRLF Specifies the patterns matching excludes files to exclude aS a comma or No a Space separated list fixlast Specifies the patterns matching includes files to include as a comma or No Space separated list Specifies the name of a file includesfile where each line is a pattern No matching files to include Specifies if the file is a Java javafiles code file Used with thetab No no attribute Set to yes no Specifies where to find the files srcDir Yes you want to fix Specifies how you want to handle tab characters Possible Specifies the name of a file where each line is a pattern No matching files to exclude Specifies whether you want to add an EOL to the last line of a processed file Available since Ant 1 6 1 O true downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required Default values are add Converts sequences of S
270. nested reference elements and nested propertyset elements as with antcall The basedir attribute of the new project s project element is affected by the attributes dir and downloaded from lib ommolketab ir downloaded from lib ommotketab ir inheritall in ant Take a look at Table 3 7 which shows how basedir IS set based on how you set these two attributes Table 3 7 Using dir and inheritAll in ant dir inheritAll basedir in the new project Value assigned true The value of the dir attribute Value assigned false The value of the dir attribute Omitted true The basedir of calling project Omitted false The basedir attribute of the project element of the new project If you need to start breaking your build files up consider thesubant task which executes Ant in various subdirectories downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 3 4 Importing Other Build Files With ant you can execute build files outside the current build file and you caninclude other build files in the current file The old way of doing this was to rely on XML and the Ant XML parser to do th work for you For example if you wanted to include the entire contents of a document named Shared xml at a specific point in a build file you could start by declaring an XML entity named say shared in your build file lt xml version 1 0 gt lt DOCTYPE project lt ENTITY shared SYSTEM file shared xml gt gt
271. ng Arguments to Ant You can get as much use out of Ant in Eclipse as you can from the command line For example to pass arguments to Ant right click build xml in the Package Explorer and select Run Ant Build to open the Ant launch configuration Click the Main tab shown inFigure 11 7 In this page you can set the build file you want to use the base directory for the build and you can pass arguments to Ant Figure 11 7 Setting the build file and arguments to pass to Ant downloaded from lib ommolketab ir downloaded from lib eommolketab ir Aint Eecarrnyole bhailbh srl The Capture output checkbox at the bottom of this dialog indicates whether you want to capture the Ant output to the Eclipse Console view as we ve been doing by default 11 2 2 Modifying the Ant Classpath When using an optional or custom task adding extra libraries to the classpath may be necessary Th Ant classpath can be modified globally or by using an individual project s launch configuration To set the Ant classpath for an individual Eclipse project open the Ant launch configuration for the project and click the Classpath tab You can add external J ARs by clicking the Add External J ARs button You can modify the Ant classpath globally for all projects To do that select Window Preferences Ant Runtime and click the Classpath tab You can add JAR files as needed here and they ll be us
272. ng all files and subdirectories lt delete dir dist gt You can use filesets lt delete includeEmptyDirs true gt lt fileset dir S dist gt lt delete gt You ve seen delete at work in various places throughout the book as in the build file in theinput folder for Chapter 3 s code repeated in Example 4 2 where the user is asked for confirmation before deleting anything Example 4 2 Using the delete task ch03 input build xml lt xml version 1 0 gt lt project default main gt lt property name message value Building the jar file gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt property name sre location source gt lt property name output location bin gt lt target name main depends init compile compress gt lt echo gt message lt echo gt lt target gt lt target name init gt lt 1mnput message Deleting bin directory OK validargs y n addproperty do delete I gt lt condition property do abort gt lt equals argl n arg2 S do delete gt lt coondition gt lt fail at do abort SBuild aborted lt fail gt lt delete dir S output gt lt mkdir dir ou utput gt lt target gt lt target name compile gt javeac srodir 0 s3ro destdir fo tput 7 gt lt target gt lt target name compress gt lt jar destfile S output Project jar basedir S output includes
273. ng files you want to deploy attachments can be sent using the files attribute or nested fileset elements You ll need access to an SMTP Server which you specify in themailhost attribute and need two JAR files in the Antlib directory mail jar which you can get from http java sun com products javamail and activation jar which you can get from http java sun com products javabeans glasgow jaf html Here s an example where the results of a build are deployed as an attachment to an email message This email has the subject New Build the message body Here is the new build and has the build s newly created tar gz files attached lt target name deploy gt lt mail mailhost smtp isp com mailport 1025 subject New Build gt lt from address developer isp com gt lt replyto address developer isp com gt lt to address list xyz com gt lt message gt Here is the new build lt message gt lt fileset dir dist gt lt includes name tar gz gt lt fileset gt lt mail gt lt target gt Now you re deploying via email using Ant You can see the attributes of themail task in Table 4 15 Table 4 15 The mailTask s attributes downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default At least one of tolist cclist bcclist or the equivalent elements to cc Or bcc List of addresses to send a blind copy beclist of the email to
274. ng revision 1 6 downloaded from lib ommolketab ir downloaded from lib ommotketab ir diff rl 6 GreetingClass java AUGU lt oyo emot Princa problems ac all gt DYSUCGM OUL Prine NS probleme here If you want to create a patch file that you can with thepatch utility update code files with use the CVS rdiff command not diff That s how the cvs task works you pass the CVS command along with any command line options ir the command attribute or a commandline element You can extrapolate from the CVS examples given here to other CVS commands easily downloaded from lib ommolketab ir downloaded from lib ommolketab ir 6 4 Getting Version Data The cvsversion task retrieves the version of the CVS client and server For example thiScvsversion element stores the server s version number in the property cvsServerVersion and the client s version IN cvsClientVersion lt cevsversion cvsroot pserver steven STEVE home steven repository password opensesame cvsserverproperty cvsserverVersion cvsclientproperty cvsClientVersion I gt The attributes for this task appear in Table 6 5 Table 6 5 The cvsversion task s attributes Attribute Description Required Default ee ene Specifies the name of the property in which you No PTOPSTEY want the version of the cvsclient to be placed Specifies the CVSROOT No variable you want to use Specifies the CVS_RSH cvsrsh No variable you
275. nit tests inProject java You can see the final version of this file build xml in Example 5 1Example 5 1 Example 5 3 Using J unit chO5 junit build xml lt xml version 1 0 gt lt project default main gt lt property name message value Building the project gt lt property name testsOK value Tested OK gt lt property name srce location source gt lt property name output location gt lt property name results location results gt lt property name Jjars location jars gt lt property name dist location user gt lt property name Jjunit fork value true gt lt target name main depends init compile test compress deploy gt lt echo gt message lt echo gt lt target gt lt target name init gt lt mkdir dir output gt wedi dirs resula gt lt mkdir dir J ars gt lt target gt lt target name compile gt lt javac srcdir S src destdir S output gt lt target gt lt target name test depends testl test2 test3 test4 test5 testo gt lt echo gt S testsOK lt echo gt lt target gt lt target name test1l depends compile gt lt java fork true classname junit textui TestRunner classpath S ant home lib junit jar gt downloaded from lib ommolketab ir downloaded from lib eommolketab ir lt arg value org antbook Project gt lt java gt lt target gt
276. nloaded from lib ommotketab ir launching them Example 7 4 shows how you can do that with the available task where the existence of cc is verified before compiling C code Ifcc is found the build file sets a property named cc ok which is checked by the compile target before the compilation is attempted Example 7 4 Checking for external programs ch0O7 checkfirst build xml lt xml version 1 0 7 gt lt project default main gt lt property name srce location source gt lt target name main depends check compile gt SCI COMPIL e3 lt echo gt lt target gt lt target name check gt lt condition property cc ok gt lt or gt lt available file cc filepath usr gt lt available file cc filepath usr bin gt lt available file cc filepath usr local bin gt lt Or gt lt condition lt target gt lt target name compile depends check if cc ok gt lt exec dir executable cc gt lt arg line S src Project cc gt lt exec gt lt target gt lt project downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 7 3 Performing Batch Execution What if you want to execute a command on multiple files If you want to pass a set of files to an external command use the apply task a version of exec that takes filesets The files in the fileset are passed as arguments to the command or external program This task is a powerful one l
277. nning multiple running test cases targetStarted method Task class 2nd taskdef element taskdef task attributes 2nd creating tasks description ejbdoclet task and target element and webdoclet task and downloaded from lib ommolketab ir downloaded from lib eommolketab ir tasks See also types See also types adding built in calling other creating custom creating DTDs for 2nd declaring outside targets defined dependent DirSet type and failonerror attribute FileSet type and grouping handling attributes implicit file sets life cycle of multithreading 2nd optional property setting setting execution order third party as wrappers tearDown method JUnit 2nd 3rd telnet task 2nd tempdir attribute javac task junit task tempfile task 2nd test cases 2nd 3rd test element test suites test task 2nd TestCase class JUnit 2nd TestCases method JUnit testEquals method JUnit testNotNull method JUnit TestRunner class JUnit tests testing Ant build process criteria formatting results in batches 2nd 3rd 4th junit task and performing running test cases writing TestSuite class JUnit testTrue method JUnit text data as attribute values filtering 2nd downloaded from lib ommolketab ir downloaded from lib eommolketab ir loading nesting os attribute and properties replaceregexp task and threadCount attribute parallel task threadsPerProcessor attribute paralle
278. nt parallel task dao element ejbdoclet task data See types dataobject element ejbdoclet task date attribute cvs task date selector 2nd datetime attribute touch task davidhost attribute jonas element davidport attribute jonas element Davidson James Duncan daysinpast attribute cvschangelog task dbUnit framework JUnit extension ddcreator task EJB 2nd debug attribute javac task weblogic element debug option 2nd 3rd debuglevel attribute javac task default attribute project element defaultexcludes attribute cab task chmod task delete task 2nd ear task FileSet type fixcrif task jar task 2nd javadoc task tar task war task xSlt style task zip task defaultexcludes task 2nd defaultInput method Project class DefaultLogger class defaultvalue attribute input task delete action weblogic tool delete task 2nd 3rd 4th deletecharacters element FilterChain type delimOutput attribute FilterChain type downloaded from lib ommolketab ir downloaded from lib eommolketab ir deltree task depend attribute javac task depend selector depend task 2nd 3rd dependencies antcall task and depend task handling parallel task and recommendations tasks and dependency attribute ejbjar task depends attribute build example fto task target element dependset task deploy action JONAS servers weblogic tool deploy task 2nd deployment by copying to EJB container
279. nt ch12 nestedtext output Jar jar Building jar home steven ant chl2 nestedtext Project jar main project No worries BUILD SUCCESSFUL Total time 7 seconds The supporting code for the custom task recovered the nested text and in this case displayed it during build Want to handle properties in nested text Use replaceProperties java lang String value which replaces style constructions in the given value with the string value of the corresponding datatypes and returns the resulting string 12 2 6 Handling Nested Elements Nested text is one thing but what if you have nestedelements in a custom task For instance assume tli your custom task has nested elements named nested as in Example 12 9 and suppose that these elements have an attribute named language How can you recover the values of the language attributes Example 12 9 Nested elements in a custom task ch12 nestedelement build xml lt xml versi n l J T gt lt project basedir default main gt lt property name src value src gt lt property name output value output gt lt target name main depends jar gt lt taskdef name project classname Project classpath Project jar gt lt project gt lt nested language English gt lt nested language German gt lt project lt target gt lt target name compile gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir l
280. nt displays the names of the various targets but because they re up to date it doesn t execute them Sant B uildfile buatd xml compile compress main echo echo Building the jar file echo BUILD SUCCES OFUL Total time 3 seconds Ant doesn t come with a built in debugger which can make it tough to troubleshoot build files However one of the items under development in the Java Eclipse IDE is an Ant build file debugger Chapter 11 has more on integrating Ant into Eclipse 1 5 5 Verbose Output You can control the amount of output Ant gives you when it runs with the verbose quiet and debug command line options If you ask Ant to be quiet it won t display anything except for build failure or success total build time and any text you specifically output via theecho task Here s an example of a quiet build Sant quiet echo echo Building the jar file echo BUILD SUCCESSFUL Total time 2 seconds On the other side of the coin the verbose option gives you a lot more information than normal including whether Ant is skipping up to date output files what OS or JDK you re using and a lot more Here s what you might see from a verbose build on Unix bash 2 05b ant verbose downloaded from lib ommolketab ir downloaded from lib eommolketab ir Apache Ant version 1 6 1 compiled on February 12 2004 Buildfile build xml Detected Java version 1 4 in opt j2sdk1 4 2_02 jre Detected OS
281. o analyze Since package Ant 1 6 multiple modules can be separated by Yes Spaces ae Specifies the password file you want the task to No cvspass read passwords from n Specifies the port used to communicate with the No port 2401 CVS server ack Specifies that you want to suppress displayed No poise messages Sets the earliest date for differences to still be One of starttag or startdate included in the report startdate ees Sets the earliest tag for differences to still be One of starttag or included in the report startdate Here s something useful to know Ant comes with an XSLT stylesheet ant home etc tagdiff xsl that you can use to generate a HTML report based on this task s XML output Here s an example lt style in datediff xml out datediff html style S ant home etc tagdiff xsl gt lt param name title expression Date Differences gt lt param name module expression GreetingApp gt lt style gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir 6 7 Creating Patches This task applies a patch file to local source code updating the local code You can create a patch file with the CVS rdiff command which lets you compare two files Here s an example which applies patch txt to the module in the current directory lt patch patchfile patch txt gt The attributes for this task appear in Table 6 9 To use this task the patch utility must be in your path Ta
282. o do In Example 9 6 in this servlet s code ServietApp java I m telling Ant how to set up the deployment descriptor web xml Example 9 6 The servliet s code ch0O9 serviet ServietApp java package app web import JaVa lO 7 import javax servlet pOr Javako rV lec P Q web serviet display name Servlet App load on startup 1 name ServletApp Qweb servlet init param name paraml1 value valuel Q web servlet init param name param2 Velie valiez Q web servlet mapping url pattern app author Steve SF SS HF HF FF SF HF SE FF SF SF Bs public class ServletApp extends HttpServlet public void doPost HttpServletRequest request HttpServletResponse response throws IOException ServletException roo once ge WELCer Jerin Lo Na worries TO use webdoclet from Ant you have to use a taskdef task this way to set up the webdoclet task See Chapter 12 downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt taskdef name webdoclet classname xdoclet modules web WebDocletTask classpathref app class path gt To create web xml for this servlet you use a deploymentdescriptor element inside the webdoclet elemen lt deploymentdescriptor servletspec 2 3 destdir app web inf dir gt The complete build file appears in Example 9 7 It compiles the code creates web xml and is designed be used from a directory named bu
283. o gt lt target gt lt target name init gt lt mkdir dir output gt lt target gt lt project Now you can compile the Java source code from the src directory placing the created class file in the output directory and create the Project jar file in the output directory all using properties lt x Verei1cn 1 0 7 gt lt project default main gt lt property name message value Building the jar file gt lt property name srce location source gt lt property name output location bin gt lt target name main depends init compile compress gt lt echo gt message lt echo gt lt target gt lt target name init gt lt mkdir dir S output gt lt target gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt target name compile gt lt javac srcdir src destdir output gt lt target gt lt target name compress gt lt jar destfile output Project jar basedir output includes class gt lt target gt lt project gt The relative paths used will be expanded in a platform specific way something like this in Unix bash 2 05bS ant f properties xml Buildfile properties xml init mkdir Created dir home steye bin compile javac Compiling 1 source file to home steve bin compress jar Building jar home steve bin Project jar main echo echo Building the jar file echo
284. o validate remote hosts downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default Yes if you are Specifies the passphrase for your using key private key based authentication passphrase No if you are using key based authentication or the password has been given in the file or todir attribute Specifies the port you want to connect ie to on the remote host ha 7 Specifies the directory you want to copy to This can be a local path or a remote path of the form Yes user password host directory path Specifies you want to trust all unknown hosts if set to yes true If set TRust to false the default the host you No no connect to must be listed in your knownhosts file You can use fileset elements to select sets of files to copy if you use a fileset you must assign a value to the todir attribute The fileset element works only when you re copying files from the local machin to a remote machine Specifies the password you want to password use for logging in todir downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 8 5 Deploying to Tomcat Tomcat available from http jakarta apache org tomcat the reference Web server for servlets and JSP has become more attractive to Ant developers since it comes with custom Ant tasks for deployment Copy the file server lib catalina ant jar from your Tomcat 5
285. oaded from lib ommotketab ir 9 1 Validating XML Documents You use the xmlvalidate task to validate XML documents with Document Type Definitions DTDs or XML schema Your build process may involve generating XML documents and it can be worthwhile to test those documents for validity before deploying them for example see the section on XDoclet in this chapter You typically use XDoclet to generate XML documents for deploying web applications such as web xml application xml and so on By default this task uses the SAX2 parser implementation provided by Sun s J AXP http java sun com xml jaxp index jsp The attributes of this task appear in Table 9 1 Table 9 1 The xmlvalidate task s attributes ree Attribute aa ooo Description penuos Required petat Default classname Specifies the XML parser you want to use the XML parser you want to use Specifies where to find the XML parser class Note that you can classpelhirer also use a nested classpath element failonerror Specifies you want this task to fail if it encounters an error 7 No true Specifies the file or files you want to validate You can use a file No nested fileset lenient Check only if the XML document is well formed if true K warn Specifies the parser should log warn messages This task can contain nested ata elements which specify locations for DTD resolution The attributes of the ata element appear in Table 9 2 Table 9 2 The dtd element s
286. oat expected float actual float Tests if two floats are equal delta within a value named delta static void assertEquals int expected int actual Tests if two ints are equal static void assertEquals long expected long actual Tests if two longs are equal Static void assertEquals java lang Object expected Tests if two objects are equal java lang Object actual static void assertEquals short expected short actual Tests if two shorts are equal Tests if two booleans are equal Static void assertEquals java lang String message boolean expected boolean actual Static void assertEquals java lang String message byte expected byte actual Tests if two bytes are equal static void assertEquals java lang String message char 7 J 2 Tests if two chars are equal expected char actual Tests if two doubles are equal within a value given by delta Static void assertEquals java lang String message double expected double actual double delta Tests if two floats are equal within a value given by delta Static void assertEquals java lang String message float expected Iloa actual Float delta downloaded from lib ommolketab ir downloaded from lib eommolketab ir Method Does this Static void assertEquals java lang String message int Tests if two ints ar expected int actual ests O Ints are equa static void assertEquals java l
287. ocessed in text mode and the filters applied line by line This means that the copy operations will typically corrupt binary files Table 2 14 The filter set type s attributes Attribute Description Required Default AEE I The string usually a character that specifies the beginning of a No c token e g in AUTHOR PE The string usually a character that specifies the end of a token No c e g IN AUTHOR id The ID you want to use for this filter set No refid The ID of a filter set you want to use while creating this filter set No You specify the filters inside afilter set with the filter task coming up next 2 3 1 Using the filter task downloaded from lib ommolketab ir downloaded from lib ommotketab ir The filter task supports the actual filters in a filter set Here s afilter set example where the build file instructs Ant to copy build java from the s archives directory to the source directory and replace the token epaTze in the files with today s date lt copy file S archives build java toFile source build java gt lt filter set gt lt Trileer Loken DAIE valiwe s1 TODAY gt lt filter set gt lt I Cory Here s the same example where the token to replace is sDATE lt copy file S archives build java toFile source build java gt lt filter set begintoken endtoken gt lt filter Coeen DATEY yalio TOLA gt lt filter set gt lt eo You can define a FilterSe
288. oject When you run this build file every line in the copiedProject java file is commented out when filtered and copied import import import tf Imeort Ti 17 puoli ChainableR jJava 1o Reader java 1o 1OException org apache tools ant filters ChainableReader org apache tools ant filters BaseParamFilterReader final class ProjectFilter extends BaseParamFilterReader implements eader String data mill downloaded from lib ommolketab ir downloaded from lib ommotketab ir 12 6 Creating Custom Selectors Writing custom Ant selectors is possible if you extend a class like org apache tools ant types selectors BaseExtendSelector In code selectors are passed File objects and return true or false depending on whether or not a file is acceptable Say for example that you want to copy files less than a megabyte in length Example 12 20 shows a selector that tests file length and returns true if the file is OK false otherwise Example 12 20 A new selector ch12 selector src ProjectSelector java import java io File import Org dpache Llools ant Buildkxception import org apache tools ant types selectors BaseExtendSelector public class ProjectSelector extends BaseExtendSelector public boolean isSelected File basedir String filename File file throws BuildException if file length lt 1024 1024 return true else return false Example 12 21 is a build file
289. oject jar 664 scp File transfer time 1 32 Average Rate 9502 27 B s scp done downloaded from lib ommolketab ir downloaded from lib ommotketab ir main echo echo Deploying the jar file echo BUILD ULCB GEUL Total time 12 seconds As discussed in Chapter 4 hardcoding passwords and or usernames in a build file is a bad idea It s better to use properties like this lt scp todir username password antmegacorp com home steven source Pass the username and password to Ant like this ant Dusername steven Dpassword opensesame Unix file permissions are not retained when files are copied with thescp task they get uMASK permissions If you want to retain Unix permissions execute the Unixscp command instead 1 lt exec executable scp ea The attributes of this task appear in Table 8 3 Table 8 3 The scp task s attributes Attribute Description Required Default Specifies whether you want to stop the failonerror true build if the task encounters an error Specifies the file you want to transfer Yes unless a You can give a local path or a remote nested file path of the form fileset user password host directory path element is used g Yes if you are pea Specifies the location of a file holding using key the private key you want to use based authentication er ee Specifies the known hosts file which No user home ssh known_ hosts can be used t
290. olketab ir lt target name compile gt lt javac srcdir S sre destdir S output 7 gt lt target gt lt target name compress gt lt jar destfile S output Project jar basedir S output includes class gt lt target gt lt project Here s what you see when you run Ant using this build file Sant B uilafile build xml Ini input Deleting bin directory OK y n y delete Deleting directory home steven input bin mkdir Created dir home steven input bin compile javac Compiling 1 source file to home steven input bin compress jar Building jar home steven input bin Project jar main echo echo Building the jar file echo BUILD SUCCESSFUL Total time 5 seconds The attributes of this task appear in Table 3 3 Table 3 3 The input task s attributes Attribute Description Required addproperty Specifies the name of the property to create using the input from the user No Specifies the default value to use for the created property this default will be used if no input is read message Specifies the prompt you want to display to prompt the user to enter text No defaultvalue TH downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Specifies the input values you consider valid separated by commas If you validargs use this attribute the task will not allow input that doesn t match one of No
291. om lib ommoltketab ir Attribute Description Required Default subject Specifies the email s subject No At least one of tolist Specifies a list of recipients A cclist bcclist or the COLIS i comma separated list equivalent elements to ce Or bcc Specifies the username used to lo PES A ENOTA user p J required on your SMTP into the SMTP server server The mail task can take nested to cc bec from and replyto elements which hold email addresses Here are the attributes of these elements these attributes are common across all these elements address Specifies the email address name Specifies the display name for the email address In addition the nested message element sets the message to include in the email body Here are the attributes of this element all are optional charset Specifies the character set used in the message mimetype Specifies the content type of the message ors Specifies the file to use as the message You can use email to send the results of a build with the mail logger which is useful if you ve set up unattended nightly builds with utilities likeat in Windows or crontab in Unix see Chapter 7 for downloaded from lib ommolketab ir downloaded from lib ommotketab ir coverage of both of these Here s how you use this logger Sant logger org apache tools ant listener MailLogger You set these properties in the build file to set up the email you w
292. omma or space No separated list excludesfile Specifies the name of a file where each line is a pattern matching files to No exclude Specifies the file extension to be used for i ii extension html ma h a Ty a files force Forces creation of the Forces creation of the output files files No fase o Specifies a single XML document to be in transformed This attribute should be used with the out attribute Specifies the patterns matching files to include as a comma or space separated No list Specifies the name of a file where each includesfile i No line is a pattern matching files to include includes downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Attribute Description Required Default Specifies the output name for the out transformed result specified with thein No attribute Specifies the name of the XSLT processor to use Possible values trax for a Trax compliant processor xslp for the XSL P processor note that this value has been ona te deprecated however xalan for the rax processor i E N Apache XML Xalan processor Version lthis value has been deprecated or the name of an arbitrary XSLTLiaison class The first one found in your class path is the one that is used Specifies if the transformer is freshly created for every transformation i l l No false Originally introduced to handle a bug in some Xalan J versions Specifies you want
293. ommand or Specifies the command you want to run executable without any command line arguments executable EE EE EE E E Specifies the build should be stopped if the executable can t start PE T TOE Specifies the build should be stopped if the No EPN encounters errors P Specifies the file where the task should take No i input to run the executable with E EEEE Specifies a string holding the input stream for No the executable to run ee Specifies you want to send error output to No Ant s log Specifies old environment variables should not be passed as new environment variables to a No false forked J VM newenvironment downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Attribute Description N Required Default Specifies the operating systems in which the executable can be run Specifies the name of a file in which to store GULCPUE the output Specifies the name of a property in which you want the output of the task to be placed Specifies the name of the executable should fe resolved using the project s base directory 1 1 tal a then using the execution directory if that ai doesn t work Available since Ant 1 6 Specifies the name of the property that you resultproperty want to hold the return code Use this only if No failonerror IS false and If fork IS TRue Specifies you want to spawn a new process in spawn which to run the command To use this No false att
294. on many different systems in the installation documentation for the J ava J DK To compile Java code you ll need a working JDK on your machine If you only have a Java Runtime Environment JRE Ant won t be able to do many things you need it to do Also note that the Microsoft J VM J DK is not supported In Windows 95 Windows 98 and Windows ME the batch file used to launch Ant will not work if ANT_HoME holds a long filename a filename which Is not in the 8 3 format It s best to install Ant in a short 8 3 path such ax Ant If you re using one of these operating systems you ll need to configure more environment space Update the following line in yourconfig sys file shell c command com c Jp 32768 1 2 2 Testing Ant With Ant in your path you should be able to run it at the command line To test this typeant version which should display the current Ant version Sant version Apache Ant version 1 6 1 compiled on February 12 2004 downloaded from lib ommolketab ir downloaded from lib ommotketab ir If Ant s not working you ll see something along these lines bash 2 05bS ant Sash alt Command nok LTound Here s the Windows version of the same error Ce Sant ant is not recognized as an internal or external command operable program or batch file In that case go back over the installation instructions and look at the Ant documentation for troubleshooting issues downloaded from lib om
295. on of web xml that webinc No details any servlets eee the filename for the generated web xml type No The jspc task is a directory based task so the JSP files to be compiled are located the same way as the javac task locates files which means you can use nested elements such aSincludes and excludes YOU can use nested classpath and classpathref elements as well as nested webapp elements The webapp element unique to the jspc task instructs the J SP compiler to build an entire Web application The one attribute of the webapp element is the basedir attribute which sets the base directory of the application The base directory must have aWEB INF subdirectory beneath it If you use this element the task uses the compiler for all dependency checking Here s an example using downloaded from lib ommolketab ir downloaded from lib ommolketab ir webapp ag 816 package org antbook chO08 gt lt include name jsp gt webapp basediy S1cn05 gt lt 7 Spc gt downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 8 8 Deploying to EJB Containers Fundamentally deploying to Enterprise JavaBean EJB application servers is similar to other Ant deployment projects you ve seen You can use the tasks covered to package and deploy EJB applications For example you can see a build file developed for the J Boss server inExample 8 6 this build file first creates a war file and then pack
296. operty name jJava vm vendor value Sun Microsystems Inc gt lt property gt lt property name Java vendor url value http java sun com gt lt property gt lt property name path separator value gt lt property gt lt property name JjJava vm name value Java HotSpot TM Client VM gt lt property gt lt property name file encoding pkg value sSun io gt lt property gt lt property name user country value US gt lt property gt lt property name sun os patch level value Service Pack 3 gt lt property gt lt properties gt lt testcase name testTrue classname org antbook Project time 0 0 gt lt testcase gt lt testcase name testEKquals classname org antbook Project timeae 0 0 gt lt testcase gt lt testcase name testNotNull classname org antbook Project time 0 0 gt lt testcase gt lt system out gt lt CDATA gt lt system out gt lt system err gt lt CDATA gt lt system err gt lt testsuite gt This kind of output is primarily designed to be used with thejunitreport task 5 2 4 Creating Reports with the junitreport Task You can use the junitreport task to merge XML files generated by the J Unit task s XML formatter and apply a stylesheet on the resulting merged document to create a browseable report of results This is an optional Ant task and you need xalan jar version 2 in the Antlib directory to run it You can get xalan jar from http xml apache org
297. or more of the criteria evaluate to false the property is assigned afalse value You can check that property s value later in the build file In this example the build file checks to see if two files exist using theavailable task covered later in the chapter and sets the property all set to true if the files are found lt condition property all set gt lt and gt lt available file filel java gt lt available file file2 java gt lt and gt lt condit ion gt Here s another example where the build file checks to see if it s running on Mac OS but not Mac OS X which Ant treats as part of the Unix family lt condition property MacOs Not MacOsxk gt lt and gt lt os family mac gt lt not gt spa Tamatly uni 2 gt lt not gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir Aand lt c condition gt Here s how you can set a property in this case calleddo abort if the do delete property value equals yes lt condition property do abort gt lt equals argl yes arg2 S do delete gt lt J gondition You can see the attributes of the condition task in Table 2 1 Table 2 1 The condition task s attributes Attribute Description Required Default property The property you want to set Yes value The value you want to set the property to No true This task depends on nested elements for evaluation you can see the possibilitie
298. paces span a tab stop to tabs tab No asis A515 Leaves tab and space characters alone renove Converts tabs to spaces Specifies the tab character tablength interval Possible values range No 8 from 2 to 80 The output file is only written if it is a new file or if it differs from the existing file The idea is to prevent bogus rebuilds based on unchanged files that have been regenerated by this task 4 1 5 Checking File Contents Using Checksums A checksum is a numerical value corresponding to the contents of a file and it can tell you if the cop of the file you ve deployed is a good copy This task lets you create an MD5 checksum for a file or sel of files Here s an example using this task in this case I m creating an MD5 checksum foProject jar which will be stored in a file named Project jar MD5 lt checksum file Project jar gt You can generate a similar checksum for the file after it s been deployed to check if it s OK Build files can be used to verify checksum values when testing a deployment for example you can generate an MD5 checksum for Project jar compare that value to a value you ve hard coded into a property named checksum and set the property checksumok if the two values match downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt checksum file Project jar property checksum verifyProperty checksumOK gt You can see the attributes of the checksum
299. password S user password gt lt arg value install gt lt jvmarg value mx512m gt lt Generic gt lt serverdeploy gt 8 8 2 2 The weblogic element The weblogic element is designed to run the weblogic deploy deployment tool legal actions for this tool are deploy undeploy list update and delete The attributes for this element appear in Table 8 9 Table 8 9 The weblogic element s attributes Attribute Description Required Default application Specifies the name of the application you want to deploy Yes classpath Specifies the classname of the deployment tool you want to run No Specifies the string for deployment targets of the form lt component gt lt target1l gt lt target2 gt In this case component IS No the archive name without a file extension eee Specifies if you want debug information to be displayed during No deployment password Specifies the password you want to use on the server Yes server Specifies the URL of the server to use a username Specifies the username to log in with No system component Here s an example using this element inside aserverdeploy element to deploy to a WebLogic server lt serverdeploy action deploy source S eardir app ear gt lt weblogic application app server ff19 server 7001 classpath S weblogic home lib weblogic jar username S user name password S user password component appserve
300. per compiler ParserSScriptlet at greeting jsp 7 4 jeasperc 2004 06 s0 U2Zr20709 Compiling wath encoding UlEo main echo echo Compiling the JSP echo BULL SUCCESSFUL Total time 3 seconds And this is what the resulting Java code greeting java looks like package org antbook jsp import javax servilet inpor jeavax Serviler nelp 7 import javax servlet jsp inport Org apacbe Jesper 7 unlime 7 public class greeting extends HttpuJspBase downloaded from lib ommolketab ir downloaded from lib ommolketab ir Sie chee em public greeting private static boolean _jspx_inited false public final void _jspx_init throws org apache jasper runtime JspException public void _jspService HttpServletRequest request HttpServletResponse response throws java 1o0 1OException ServletHException JspFactory _jJjspxFactory null PageContext pageContext null HttpSession session null out println Hello from JSP Display the greeting Here s another example which compiles JSP pages checks the dependencies and uses thejavac task to create the actual bytecode for this J SP Spc destdir temp STreoly 1ero package org antbook ch08 gt lt include name jsp gt Tope lt depend srcdir temp destoir s1 bin classpath lIab apo jar gt Javec srcdir temp destdir ibin classpath lib app jar gt You can
301. piler Forking the Java compiler makes it run in a new process something that s often useful if you want tc use another compiler or want to configure the compiler s runtime environment When the compiler is used in unforked mode in Windows it may lock the files in the classpath of thejavac task That means you won t be able to delete or move those files later in the build If you need to change that fork the compiler using the fork attribute Here s an example that compiles all java files under the src directory stores the class files in the bin directory and forks the javac compiler into its own thread process javae sredir si ere fork yes downloaded from lib ommolketab ir downloaded from lib ommotketab ir de stdir Spin I gt Here s an example showing how you can tell Ant which Java compiler you want to run after forking Javac srcdir S sro destdir S bin fork yes executable opt java jdk1 3 bin javac compiler javacl 3 gt In the early days if you were using Ant on Windows a new DOS window would pop up for every use of an external compiler If you use a JDK after 1 2 this won t be a problem 3 1 2 Setting Command Line Options You can explicitly specify command line arguments for the compiler with nestedcompilerarg elements lt javac srcedir src destdir build classpath xyz Jar debug on gt lt compilerarg value 1 a gt lt javac gt
302. pplication servers wlrun Starts a WebLogic server Wlst A Stops a WebLogic server The Perforce source control tasks are shown in Table 1 8 Table 1 8 Perforce Ant tasks ian Description P4Sync Synchronizes files with the Perforce server P4Change Gets a list of current changes from the Perforce server P4Edit Checks out files for editing pasubmit Checks in files P4Have Lists all client viewable files PaLabel Makes a label based on the files in the current workspace patabelsync Syncs with a label AO Gets or sets a counter value Counters can be used to keep track of build events such as the number of builds that have been executed P4Reopen Reopens a checked out file P4Revert Reverts file s that have been changed to their original content P4Add Adds file s to the list to be submitted to the server downloaded from lib ommolketab ir downloaded from lib ommolketab ir name P4Delete Deletes file s P4Integrate Integrates file s You must specify the source file s and the target file s Resolves file s in case others have made changes to the file s when you were working on it P4Fstat Views differences with the server Many tasks for Microsoft Visual Source Safe are detailed inTable 1 9 P4resolve Table 1 9 Visual Source Safe tasks Task name i SOC scription s s Continuing with source control repository
303. preset as preseLder an enea aae property Sets one or more Sets one or more properties to new values to new values record Runs a listener that records the logging output of the build process to a file replace Replaces a string with another in all files in a directory rmic Invokes the rmic compiler sequential A container task that can contain other Ant tasks and run them in sequence signar Uses the JarSigner to securely sign ZIP and JAR archives sleep Suspends execution for a specified period of time sql Runs SQL statements against a database subant Runs Ant within all subdirectories of the project directory sync Synchronizes two directory trees tar Makes a new TAR archive taskdef Creates a new task definition and adds it to the current project tempfile Sets a temporary filename to an Ant property tstamp Sets time based properties to the current time typedef Creates a new task or data type for use in the current project unjar Unpacks a JAR file untar Unpacks a TAR file pe unwar mesonte ooo Unpacks a WAR file anzi Unpacks a ZIP file a ZIP file eoa Sets a property value to true if a given target file is newer than a set of a SA files waitfor eeoa a build and continues when Hat 2 al nd coe whe spect ents semt conditions are met war Creates WAR archive files an extension of Creates WAR archive files an extension of thejar task 0000 task Locates a class or resource either on the curren
304. private No classes and members Specifies you want to show all protected public classes and members No This is the default enp Specifies you want to show only public No classes and members Specifies you want to be warned about serialwarn No the serial tag if encountered Sets this attribute to 1 4 to document noqualifier packagelist protected source code that compiles using javac source No 1 4 At least one of sourcepath Specifies the source files Use a sourcefriles SCurCeriies comma separated list sourcefiles ora nested sourcepath fileset OF packageset downloaded from lib ommolketab ir downloaded from lib ommolketab ir Description Specifies where to you want to find source files Default Attribute Required At least one of sourcepath sourcefiles sourcepath sourcefiles Ora nested sourcepath fileset OF packageset At least one of sourcepath Specifies where you want to find source files by reference sourcefiles sourcepathref sourcefiles Ora nested sourcepath fileset OF packageset Specifies you want to split the splitindex generated index into one file for each No letter sevieeneser ie Specifies the CSS stylesheet you want No to use Specifies you want to create class and use No package usage pages Specifies whether the source filename s should be written to a No no tempo
305. pserver anthill example cvs2 urbancode com 2401 usr local anthill test downloaded from lib ommolketab ir downloaded from lib ommolketab ir CVS password KKEKKKKKKKKKKKEK In the same command prompt session start Tomcat and navigate tohttp localhost 8080 anthill to ope Anthill console as shown in Figure 4 1 This is the console that lets you schedule and configure your bui Successfully built projects are marked with a green box in the right column of the console Figure 4 1 The Anthill build management server 3 Anthill Adnuanatraton icroasoft Internet Explorer Fie Edt View Favorites Took Hel Sebo gt DD sh avotos Beds SG ot Address E betpey localhost EDEN archi Anthill Build Management Server ers H Not Buli Edit Builg Je ete Not Buil wild Yersigned Build L Not Bui Edit Build We Delete Not Euil Edit Buia Yersioned Guile alata Not Buli Edit Build Edit Build Having logged into the Anthill CVS server click the Buildhyperlink in the top line of the table shown in Fig 1 which will build the cvs_Anthill example This opens the Build Project page shown in Figure 4 2 Click Force Build checkbox enter a build version such as 1 1 and click the Build button Figure 4 2 Forcing a build downloaded from lib ommolketab ir downloaded from lib ommolketab ir Huld Peopect Picrosolt Intemet boplorer se gt ORA Amo ireen Que GIG a G
306. put Project jar basedir output includes class gt lt manifest gt lt section name Credits gt lt attribute name Author value Steve gt lt section gt lt section name Title gt lt attribute name Title value Profits gt lt attribute name Company value YourColInc gt lt section gt lt manifest gt lt jar gt lt target gt For a more substantial example see Example 3 5 coming up in this chapter You can see the attributes of this task in Table 3 11 Table 3 11 The manifest attributes downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required Default file Specifies the name of the manifest file to create Yes Specifies what you want to do with the manifiest file Possible mode No replace values are update OF replace Specifies the encoding you want to use when reading a UTF 8 encoding No manifest to update encoding There s more you can put into JAR manifests as well such as an automatically incremented build number and a time stamp both coming up next Need to un JAR a JAR file Use Ant sunjar task J ust set the src attribute to the JAR file to un jar and set the dest attribute to the directory where you want the output downloaded from lib ommolketab ir downloaded from lib ommotketab ir 3 Setting Build Numbers Anyone who has released software commercially Knows how important it is
307. r S source gt lt include name java gt lt exclude name test gt lt fileset gt Here s an example that lets you include certain files using thefilename selector more on selectors later in this chapter lt fileset dir S source gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt filename name java gt lt filename name test cpp gt lt fileset gt Many Ant tasks support file sets such as the copy task see Chapter 4 here s an example which copies all but java files from the src directory to the dest directory lt copy todir dest gt lt fileset dir src gt lt exclude name Jjava gt lt fileset gt lt COCy You can see the attributes of the fileset type in Table 2 8 FileSets can appear inside tasks that support file sets or at the same level as target as when you want to assign a file set to a property Table 2 8 The fileset type s attributes Attribute Description Required Default ve Specifies whether the include and exclude patterns casesensitive sat No true be treated in a case sensitive way Specifies whether default excludes will be used or defaultexcludes not yes or no Default excludes are used when No TRue omitted Specifies the root of the directory tree used to dir Or file must dir create this FileSet be specified ee Specifies a list comma or space separated o patterns of files that yo
308. r productionserver gt lt serverdeploy gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir 8 8 2 3 The jonas element The jonas element supports deployment to JOnAS Java Open Applicaton Server servers Valid actions for the JOnAS deployment tool org objectweb jonas adm JonasAdmin are deploy undeploy list and update The attributes of this element appear in Table 8 10 Table 8 10 The jonas element s attributes Attribute Description Required Default Specifies the root directory for the jo asroot Yes server Specifies the orb such as RMI JEREMIE DAVID and so on If the orb orb is DAVID RMI IIOP specifies No The ORB present in the classpath the davidhost and davidport attributes a specifies the value for the property No david CosNaming default_host dase disor specifies the value for the property No david CosNaming default port classname Specifies the classname of the No org objectweb jonas adm JonasAdmin deployment tool you want to run Specifies the classpath you want the classpath JVM running the tool to use May be No supplied as a nested element Specifies the URL of the server to server ee Yes If you want to build in delay times to take into account delays in getting responses from a server use the Ant waitfor task You can use the sleep task for this purpose The jonas element supports nested classpath arg and jvmarg elements Here s
309. r and tstamp tasks ch0O3 buildnumber build xml lt xml version 1 0 27 gt lt project default main gt lt property name message value Building the jar file gt lt property name src location source gt lt property name output location bin gt lt target name main depends init compile compress gt lt echo gt message lt Jecho gt lt target gt lt target name init gt lt buildnumber gt lt tstamp gt lt delete dir S output gt lt mkdir dir ou utput gt lt target gt lt target name compile gt lt javac srcdir src destdir S output gt lt target gt lt target name compress gt lt jar destfile S output Project jar basedir output includes class gt lt manifest gt lt attribute name Author value S user name gt lt section name Shared gt lt attribute name Title value Example gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt attribute name Vendor value MegaAntCo gt lt attribute name Build value S build number gt lt attribute name Date value S TODAY gt lgection lt section name Copyright gt lt attribute name Copy value C MegaAntCo 2005 gt sect ion gt lt manifest gt lt jar gt lt target gt lt pro ect gt Here s the resulting manifest file from the JAR file including build number and creation date Manifest
310. r current platform If you need to specify a directory separator here use file separator What mappers can you use with the mapper element You can see the available Ant mappers itn Table 2 18 downloaded from lib ommolketab ir downloaded from lib ommotketab ir Table 2 18 Ant mappers Mapper Does this Flattens the target filename to the source filename but with all directory information flatten i i stripped off from the front To and from attributes are ignored glob Lets you support wildcards in the to and from attributes TR Copies over the filename by making the target filename the same as the source a een To and from attributes are a a eee merge Takes the target filename from the to attribute from will be Takes the target filename from the to attribute rom will be ignored 0 package Helps with Java package names by replacing directory separators with dots regexp Lets you use regular expressions on theto and from values Replaces any dots in the name of a package with legal directory separators available since Ant 1 6 unpackage When you use the identity mapper the target filename is the same as the source filenamein other words this one s transparent to Ant Here s the way you d use this mapper in a file set lt mapper type identity gt The flatten Mapper is more interesting this one strips all leading directory information off allowing you to copy all files in a directory tre
311. r tasks instead of failing immediately in the junit task Here s the output you see when this task runs test2 junit Running org antbook Project junit Tests run 3 Failures 0 Errors 0 Time elapsed 0 011 sec The plain formatter creates the output file TEST org antbook Project txt which holds these contents downloaded from lib ommolketab ir downloaded from lib ommolketab ir Testsuite org antbook Project Tests run 3 Failures 0 Errors 0 Time elapsed 0 01 sec Testcase testTrue took OQ sec Testcase testHgquals took 0 sec Testcase testNotNull took O sec All the tests succeeded and the results look good But what if you changed a test so thereturn4 method is supposed to returns rather than 4 public void testEquals assertEquals assertEquals test 5 return4 In that case you d see this in the build test2 Junit Running org antbook Project Junit Tests run 2 Failures 1 Errors 0 Time elapsed 0 02 sec You could read all about the problems in the output fileTEST org antbook Project txt which indicates the problem Testsuite org antbook Project Tests run 2 Failures 1 Errors 0 Time elapsed 0 02 sec Testcase testTrue took 0 01 sec Testcase testHEgquals took 0 sec FAILED assertEquals test expected lt 5 gt but was lt 4 gt jJunit framework AssertionFailedError assertEquals test expected lt 5 gt but was lt 4 gt at org antbook Project testEquals Unknow
312. rary file Set to yes or no ee Specifies you want this task to display No messages of what it s doing NE Specifies you want to include version No paragraphs Sets the title of the browser window for windowtitle No the documentation For more on how to use the javadoc tool look at the JDK documentation available online at http java sun com j2se 1 4 2 docs index html useexternalfile Here s another example This one passes Java packages starting withgui to javadoc to document them excludes a few specific packages sets the header text for each page groups the packages gui steve api together on the first page under the title Group 1 Packages and includes a link to the Java 1 4 2 docs lt javadoc destdir api version true gt lt packageset dir code gt lt include meame qui17 gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt exclude name gui debug gt lt packageset gt lt header gt lt CDATA Preliminary API Specification gt lt header gt lt Ldoctitle lt IICDATA lt hl Test hl gt gt lt doctitle gt lt group title Group 1 Packages packages gui steve api gt lt link href http java sun com j2se 1 4 2 docs api gt lt javadoc gt downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 3 6 Creating JAR Files The jar task JARs files for you Example 3 4 is a fairly complex example which creat
313. rdir gt lt target gt lt target name ear gt lt copy file S descriptors application xml todir S eardir META INF gt lt jar jarfile S basedir S earfile basedir S eardir gt lt targee gt lt project gt That s all it takes Though this build file gets the job done using standard Ant tasks tasks built into Ant make it easier to work with EJB applications starting with theear task 8 8 1 Creating EAR Files The ear task is handy for creating ear files and makes special provisions for the application xml file needed in most EARs It s not mandatory to use this task to create a ear file but it can make life easier You can see the attributes of this task inTable 8 6 The ear task is an extension of the Jar task with special treatment for application xml You can perform the same operation by using theprefix and fullpath attributes of zipfilesets in a zip or jar task Table 8 6 The ear task s attributes Attribute Description Required Default Yes unless update IS set to TRue er e Specifies the directory from which to get the files conpress Indicates you want to not only store data but P compress PEEN compress it Specifies the deployment descriptor you want to use such as application xml appxml Specifies if you want to use default excludes or eeu defaultexcludes No excludes are not Set to yes no need destfile Specifies the EAR file you want to create
314. re remove Removes an item from a CVS repository rlog Displays CVS history information for a module rtag Adds a tag to a CVS module server Lets you set server modes for access status Displays checked out file information tag Adds a tag to checked out files unedit Undoes an edit command that s been executed update Updates local copies of a file with those in the CVS repository downloaded from lib ommolketab ir downloaded from lib ommolketab ir Does this int barman aon version Shows the CYS version the CVS version watch Watches a file or files watchers Displays which users are watching a file or files The first step in working with CVS is to log into the CVS server typically done with theevspass task downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 6 2 Logging In You use the cvspass task to log into a CVS server to get access to the code stored in the CVS repository This task adds entries to a cvspass file which has the same affect as a CVS login command When a cvspass file has been created subsequent logins will get the needed data from this file and you won t have to supply a password again The values you assign to the attribute named cvsroot use the same format of strings that appear ine CVS cvspass file which specifies the protocol type username server and repository location For example using the pserver protocol with a user named Steve
315. re none or a comma separated list of these keywords lines vars and source This attribute requires debug to be set to true if it s not this attribute is ignored No epera See that you want to use dependency No tracking if your compiler supports it Specifies that you want the compiler to deprecation ne No no display deprecation information eee as Specifies the destination directory for the No generated class files downloaded from lib ommolketab ir downloaded from lib ommolketab ir _ Aes Attribute Description Required Default encoding Specifies the encoding of your Java files No Specifies a list of files that you want to excludes exclude A comma or space separated list No of files eaaeo e Specifies a file containing a list of files you No want to exclude Specifies the path to the javac executable that will be used when fork is used Defaults No to the compiler currently used by Ant Specifies the location of installed extensions extdirs if any Specifies if you want the build to fail if there failonerror true are compilation errors eae Specifies if to execute javac in a forked process ee ee ee Specifies whether you want to make the Ant No e run time libraries accessible to the compiler Specifies whether you want to make the includeJavaRuntime default runtime Java libraries accessible to No no the executing J VM Specifies a list of files that you want to includes include A comma
316. recedence over the target you re importing The import task makes it easier to handle relative paths as defined in the imported build file It does this by creating a new property corresponding to the absolute path of the imported build file so you can resolve relative file references Ant has a property called ant file that contains the absolute path of the build file seeChapter 1 so this task creates a new property based on the name of the file you re importing For example if you import a build file named newbuild the new location property will be namedant file newbuild Now that you ve built your application with the various tasks seen in this chapter it s time for some documentation downloaded from lib ommolketab ir downloaded from lib ommotketab ir 3 5 Documenting Code Creating applications in a commercial environment frequently means creating documentation and Ant i up for that with the javadoc task This task creates documentation using the J ava javadoc tool a process that involves compilation which merits including this task in this chapter This is one of the largest tasks in Ant because of the enormous number of javadoc options Here s an example stored in the javadoc folder in the code for this book Suppose you add a documentation type comment to the Project java file This application prints out No worries public class Project p blig static void Main gt ring argoll SYSUeM OUL
317. reds 1 4 3 1 Built in tasks As you d expect Ant comes with a large number of built in tasks and you can see them all inTable 1 3 many of these tasks may contain subelements downloaded from lib ommolketab ir downloaded from lib ommolketab ir In cases where a task is listed and followed by another task name in brackets as IN apply execon the first task is the current name you should use the second task is an older name that performs similar functionality but is now deprecated Always use the task not in brackets to ensure your code is current Table 1 3 Core Ant tasks Task name Description ant noo a a a a ao Executes Ant fanteall Executes a Executes a target fromthe current build fle from the current build file From a given build file creates a DTD reflecting all of the tasks Ant aAliLeLrUuCLure Say econ eea aaee knows about apply lexecon execon Invokes a native executable a native executable ee E Sets a Boolean value in a property according to the availability of desired Sets a property to the last element of a specified path in an effort to basename ma li a file s name without aae a y structure fbuildnumber Manages build numbers build numbers bunzip2 Expands GZip or BZip2 archives bzip2 Packs GZip or BZip2 archives checksum Creates checksums for one or more files chmod Modifies file permissions on Unix concat Concatenates multiple files condition Checks the
318. remiere Java IDE these days is Eclipse You can see what it looks like inFigure 11 1 Figure 11 1 Eclipse Java AntClassjova Eclipse Plotform Fie Edit Source Restor Navigate Search Project Run Window Hep ro ole O Gae ev 45 aul EEE t TODO To change the template for this t Yindew Preferences Javas Code St Tee Ant Fy E E org_anthonk package ofg antbook E d SnbClnss jav ES AnbClass sal Mel t Ganthor Steven Holzner E TODO To change the template for thia Window FPE at erences MER pir Code st zy Eclipse is free for the downloading like a number of other Java IDEs but Eclipse has a serious advantage behind it which is the power of IBM reportedly spending 40 million developing it It s nc an open source project largely under IBM s development but part of a software consortium named eclipse org downloaded from lib ommolketab ir downloaded from lib ommotketab ir Want to read more on Eclipse See Eclipse by yours truly O Reilly 11 1 1 Getting Eclipse Eclipse is free for the downloading all you have to do is navigate to http www eclipse org downloads Select one of the download mirrors available on that page When you do you ll be presented with a list of the available downloads of these various types Release builds These versions are for general use Stable builds These are comparable to beta versions Integration builds These
319. result of a condition and sets the result to in a property aa Copies files CVS Interacts with a CVS repository cvschangelog Converts a series of CVS change logs into an XML report cvspass Adds entries to a cvspass file evstagdiff Creates an XML report highlighting the differences between tags cvsversion Finds the CVS software version Modifies the list of default exclude patterns affecting which files are defaultexcludes automatically excluded from processing by file related tasks delete deltree Delete files and folders downloaded from lib ommolketab ir downloaded from lib ommolketab ir Task name Description a dependset tes ore es hotare saer ten ren sete es Deletes target files that are older than new source files dirname Assigns a file s Assigns a file s directory path to a property path to a property Extends the jar task to support handling files for an Enterprise Application a ioa PETTO e fecho Echoes text to system out or to a file text to System out or to a file exec Invokes a native executable ____ real aks el ye onime i Halts and exits a build by throwing aBuildException filter Sets a token filter that can be used Sets a token filter that can be used by filter related tasks such ascopy filter related tasks such aScopy Adds or remove tabs carriage returns linefeeds and EOF characters from a Fixcrit caw a i of files genkey Adds a new Adds a new key to a given keystore
320. rg antbook Project FAILED assertEquals test expected lt 5 gt but was lt 4 gt jJunit framework AssertionFailedError assertEquals test expected lt 5 gt but was lt 4 gt at org antbook Project testHEquals Unknown Source at sun reflect NativeMethodAccessorImpl invokeO Native Method at sun reflect NativeMethodAccessorImpl invoke Unknown Source at sun reflect DelegatingMethodAccessorimpl invoke Unknown Source 5 2 3 Using the XML Formatter for Reports The XML formatter gives you the most information of all formatters Here s how you use it in a new task test4 lt target name test4 depends compile gt lt junit printsummary yes fork yes haltonfailure yes gt lt formatter type xml1 gt lt classpath path gt lt test todir results name org antbook Project gt lt in lt target gt This task creates a new file TEST org antbook Project xml which contains a tremendous amount of information including the names and values of all properties as well as the results of the tests downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt xml version 1 0 encoding UTF 8 gt lt testsuite name org antbook Project tests 3 failures 0 errors 0 time 0 04 gt lt properties gt lt property name Java runtime name value Java TM 2 Runtime Environment Standard Edition gt lt property gt lt property name ant java version value 1 4 gt lt property gt lt pr
321. ribute set fork tO true Specifies you want the task to quit if it doesn t timeout finish in the given time Set the time in No milliseconds PE EEE ET specifies you want to run the executable using No eee the JVM s execution facilities If you re running a mixed Unix Windows environment such as Cygwin exec task will not understand paths like bin release for the executable attribute because the JVM in which Ant is running is a Windows executable which means it s unaware of the conventions used in Cygwin CULDULPrOCver YY How you execute general code like this varies by operating system so you can specify the operating system with the os attribute operating system names are strings like Linux Windows 2000 and so on When you specify a target operating system the command or program is only executed when the OS matches one of the operating systems you specify If you want to check the OS name for a target platform use J ava to display the value of the os name system property You can nest arg elements in the exec task to pass command line arguments And you can set the values of environment variables using nested env elements The attributes of this element appear in Table 7 3 downloaded from lib ommolketab ir downloaded from lib ommotketab ir You can send input to a program using theinput and inputstring attributes Table 7 3 The env element s attributes Attribute Description Required Specifies an envi
322. right click a target and select the Run item in the context menu that appears Double clicking a build file in the Ant view opens it in the Ant editor as does right clicking the build file and selecting the Open With Ant Editor item Using Ant with Eclipse is a potent combination Eclipse allows you to develop and debug code and Ant lets you build and deploy it Both of these tools are free for the downloading It s a combination recommend downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Chapter 12 Extending Ant There s more to Ant than what comes out of the box because you can extend Ant in various ways The most common way of extending Ant is by creating your own tasks and this chapter covers how to do that You ll learn how to create new tasks handle task attributes access property values work with nested text and elements make builds fail work with filesets use custom tasks as wrappers for external programs and more Besides creating new tasks you can extend Ant in other ways such as using scripting languages such as JavaScript which I ll explain You can even create listeners that respond to build file events by executing Java code and create loggers that log data as a build progresses And you can create custom filters and selectors which you can use with some Ant tasks such aScopy downloaded from lib ommolketab ir downloaded from lib ommotketab ir 12 1 Creating a Si
323. ring that number in a JAR file s manifest file getting input from the user and acting on that input calling one Ant target from another creating Javadoc with thejavadoc task and more downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 3 1 Compiling Code The javac task compiles Java source code You ve seen javac at work many times in this book but haven t exhausted what this task has to offer by any means You can get an idea how extensive a task it is by its huge number of attributes shown inTable 3 1 Attribute Table 3 1 The javac task s attributes Desc Description Required Default Poore Specifies where to find any bootstrap class files A TE Specifies where to find any bootstrap class aaa Tp OEA un as a reference c1asspatn Specifies the classpath you want to use the classpath you want to use EET T Specifies the classpath you want to use given as a reference to a path compiler debug debuglevel esera Specifies the compiler you want to use If you don t set this attribute this task will use the compiler pointed to by the build compiler property if set If that property is not set the default compiler for the current JVM is used No Specifies whether or not your code should be compiled to include debug data Corresponds No no to the compiler s g option Specifies keywords that will be added to the command line with the g switch Possible values a
324. ronment variable that you want to replace Exactly one of value file with the absolute name of the file path OF file Specifies the name of the environment variable you want to key Yes work with ae Specifies the value for a path like environment variable Use Exactly one of value j or as path separators path OF file value Specifies the value of the environment variable exactly ONE OTga Le path Or file 7 2 1 Handling Return Codes By default the return code of an exec is ignored However if you set failonerror tO TRue then any OS specific return code that indicates failure means the build will fail If you start an external program and the program fails to execute the build halts unlessSfailifexecutionfails IS set to false You can set the resultproperty to the name of a property that will be assigned the return code for testing Any of these attributes can test if the results of your build functions as they should Example 7 2 shows how to execute a C compiler cop exe passing it a command line to execute and watching for errors by setting failonerror tO TRue which means the build will quit if there is an error Example 7 2 Running a J VM ch0O7 exec build xml lt xml version 1 0 gt lt project default main gt lt property name srce location source gt lt property name output location bin gt lt target name main depends init compile gt lt echo gt PuULLQING and Funnind ass
325. rs must not access System out and System err because output on these streams Is redirected by Ant s core to the build event system In other words accessing these streams may cause an infinite loop To implement the listener interface you implement methods such aSbuildStarted buildFinished targetStarted and so on In SoundListener java shown in Example 12 16 the listener code uses the org apache tools ant taskdefs optional sound AntSoundPlayer Class to play a sound when the build is finished TheaddBuildSuccessfulSound java io File file int loops java lang Long duration method is used to add a sound to play for build success and addBuildFailed Sound java io File fileFail int loopsFail java lang Long duration to adda sound indicating build failure In the listener sbuildFinished method the sound player s buildFinished method is called to play the sound downloaded from lib ommolketab ir downloaded from lib ommotketab ir If you run this example substitute your own local filenames forfilel wav and file2 wav in SoundListener java The AntSoundPlayer can play sound files in wav and aiff format Example 12 16 A new listener ch12 listener SoundListener java import java io File import org apache tools ant BuildEvent import org apache tools ant BuildListener import org apache tools ant taskdefs optional sound AntSoundPlayer public class SoundListener implements BuildListener AntSound
326. rth Sebastopol CA 95472 O Reilly books may be purchased for educational business or sales promotional use Online editions are also available for most titles http safari oreilly com For more information contact our corporate institutional sales department 800 998 9938 orcorporate oreilly com Nutshell Handbook the Nutshell Handbook logo and the O Reilly logo are registered trademarks of O Reilly Media Inc Ant The Definitive Guide the image of a horned lizard and related trade dress are trademarks of O Reilly Media Inc Java and all Java based trademarks and logos are trademarks or registered trademarks of Sun Microsystems Inc in the United States and other countries O Reilly Media Inc is independent of Sun Microsystems Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book and O Reilly Media Inc was aware of a trademark claim the designations have been printed in caps or initial caps While every precaution has been taken in the preparation of this book the publisher and author assume no responsibility for errors or omissions or for damages resulting from the use of the information contained herein downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Preface Welcome to Ant today s premiere build tool Ant is an extraordinary tool and it fills a long standing need among
327. rty MailLogger failure subject property MailLogger failure to property MailLogger from property MailLogger mailhost property MailLogger port property MailLogger success notify property MailLogger success subject property MailLogger success toSpecifies property mailport attribute mail task manifest attribute ear task jar task war task manifest element jar task manifest files creating 2nd 3rd default example jar task and plug in manifest task 2nd manifestencoding attribute jar task mapped attribute jspc task mapper element attributes 2nd batch execution and copying files and nesting 2nd 3rd mappers 2nd master targets match attribute replaceregexp task MatchingTask class 2nd 3rd maudit task maxmemory attribute java task javadoc task junit task maxparallel attribute downloaded from lib ommolketab ir downloaded from libeommolketab ir apply task chmod task maybeConfigure method Task class MD5 checksum memorylnitialSize attribute javac task memoryMaximumSize attribute javac task merge mapper 2nd mergeDir attribute ejbdoclet task webdoclet task message attribute fail task input task mail task message element mail task messagefile attribute mail task messagemimetype attribute mail task metainf element jar task and war task and Metamata Metrics WebGain Quality Analyzer methods attributes in custom tasks Project class and Property class Task cla
328. rty attribute apply task batchtest element exec task java task junit task 2nd test task errors brief formatter and build process and Eclipse and external programs and Java code and Java development and responding to validating XML documents escapeunicode element FilterChain type events custom listeners custom loggers 2nd downloaded from lib ommolketab ir downloaded from lib eommolketab ir exclamation point exclude attribute delete task exclude element cab task and depend task and DirSet type and fileset element and FileSet type jar task and javac task PatternSet type and support element and xslt style task and zip task and excludedTags attribute ejbdoclet task webdoclet task excludepackagenames atiribute javadoc task excludes attribute cab task chmod task delete task DirSet type ear task FileSet type fixcrif task jar task 2nd javac task PatternSet type tar task war task xslt style task zip task excludes element ispc task and Matching Task class excludesfile attribute cab task delete task 2nd DirSet type ear task FileSet type fixcrif task jar task 2nd javac task PatternSet type tar task war task xslt style task zip task excludesfile element DirSet type and downloaded from lib eommolketab ir downloaded from lib eommolketab ir fileset element and FileSet type PatternSet type and exdirs element exe
329. rty named message A resource file url Or environment attribute is required when not using the name attribute The prefix to use when retrieving environment variables For example if you specify environment env you will be able to access operating system specific environment variables as property names like env PATH A resource file url Or environment attribute is required when not using the name attribute The name of a property file to load values from Sets the property to the absolute filename of the given file If an absolute path is supplied it s left unchanged with and characters converted for the current platforms A value location Or refid element is required when using the name attribute downloaded from lib ommolketab ir downloaded from lib ommotketab ir lt xml version 1 0 gt lt project default main gt lt property name message value Building the jar file gt lt project gt You declare properties outside your targets As of Ant 1 6 all tasks can be declared outside of targets earlier versions only allowedproperty typedef and taskdef to be used outside of atarget element When you define tasks external to a specific target those tasks are evaluatedbefore any targets are executed You can echo the message to the console like this lt xml version 1 0 gt lt project default main gt lt property name messag
330. rvers such aSdeploy reload and undeploy And there s more to come Chapter 9 covers the many optional Enterprise JavaBeans EJB tasks Ant supports downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 8 1 Creating WAR Archives The war task is an extension of the jar task and it compresses Web applications into war files with Special handling for files that should end up in theWEB INF lib WEB INF classes or WEB INF directories on the server For example say you have this directory layout after you build your project war CULE DUuL login class logout Class source iRerepeeee lt iil html welcome xml The build file in Example 8 1 will create the war file you need to deploy this application placing the class files in the WEB INF classes directory renaming login xml web xml and placing it in WEB INF and so on Example 8 1 Creating a war file chO8 war build xml lt xml version 1 0 encoding UTF 8 gt lt project default main basedir gt lt property name bin value output gt lt property name srce value Source gt lt target name main gt lt war destfile login war webxml S src login xml gt Tilese dir sro 7 irri 7S Classes cir Sibint 7 gt lt war gt lt target gt lt project Here s what this build file looks like at work Sant downloaded from lib ommolketab ir downloaded from lib ommotket
331. s Attribute Description Description O Required Default Specifies the name of a property you want set in errorprope rty case there is an error No ee Specifies the name of a property in case the task No fails Removes Junit and Ant stack frames from error filtertrace m Species you want orn tens anew yy traces fork Specifies you want to run tests inanewJVM you want to run tests in a new JVM ol ee you want to stop the build if there are a o haltonfailure Specifies you want to stop the build if the test fails Specifies you want to stop the build if the test fails No Specifies this test should run only if a specified li No property Is set Specifies the directory where you want reports The current todir No written to directory aie Specifies this test should run only if a specified No property Is not set Other nested elements are available since Ant 1 6 You can specify a set of properties to be used as system properties with syspropertysets If you re forking a new JVM you can specify the location of bootstrap class files using the bootclasspath path like structure inside the junit task You can revoke or grant security permissions during the execution of a class with a nestedpermissions element And you can even control Java 1 4 assertions with anassertions subelement downloaded from lib ommolketab ir downloaded from lib ommoltketab ir downloaded from lib ommolketab ir downloaded from li
332. s The source code for an EJB Appbean java appears in Example 9 8 and shows how the ejbdoclet task works The embedded XDoclet tags hold data for theejbdoclet task which will create a deployment descriptor and write code Example 9 8 The EJB bean ch09 ejb Appbean java package app web Import Javax e jb x x x ejb bean name App description App example bean jndi name ejb App type Stateless downloaded from lib ommolketab ir downloaded from lib ommolketab ir ejb security role ref role link Administrator role name admin ejb permission role name App ejb permission role name Administrator ejb transaction type Regquired ejb transaction type type Container author Steven y public abstract class AppBean implements SessionBean Add and return values ejb interface method view type remote ay public double adder int x int y recur A a y public void ejbActivate public void ejbPassivate public void setSessionContext SessionContext ctx x Remove ejb transaction a type Mandatory ay public void ejbRemove In the build file you USetaskdeg to tell Ant about the ejbdoclet task lt taskdef downloaded from lib ommolketab ir downloaded from lib ommotketab ir name ejbdoclet classname xdoclet modules ejb EJbDocletTask classpathref app class pa
333. s hot by moving files 2nd packaging applications for preparing for scheduling automatic builds scp task setting file protections 2nd Tomcat web servers and using email using FTP using SSH 2nd using telnet war files web 2nd deploymentdescriptor element ejbdoclet task 2nd webdoclet task 2nd deprecation attribute javac task depth selector description attribute target element 2nd Description type descriptordir attribute ejbjar task dest attribute apply task 2nd cvs task cvsversion task get task unjar task downloaded from lib eommolketab ir downloaded from lib eommolketab ir destdir attribute depend task ejbdoclet task ejbjar task fixcrif task javac task javadoc task ispc task webdoclet task weblogic element xslt style task desttile attribute cvschangelog task cvstagdiff task ear task gzip bzip2 tasks jar task patch task tar task war task zip task diagnostics option diff command CVS 2nd 3rd different selector dir attribute ant task 2nd apply task build xml file and chmod task custom tasks and cvschangelog task delete task DirSet type exec task FileList type FileSet type 2nd fto task java task junit task mkdir task patch task dir command Windows directories copying to new locations creating default excludes deleting dependencies and 2nd ejbjar task and fto task and ispc task and manipulating remotely downloaded from lib ommolketab ir
334. s and filter chains e Working with mappers e Creating conditional targets e Packaging applications e Moving copying and deleting files e Building documentation e Creating JAR files e Deploying applications e Using FTP e Handling remote deployment e Getting and installing J Unit e Using J Unit assertions e Creating a test case downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Running a test case Using CVS and Ant Accessing CVS Initializing CVS Running external programs and continuous integration Running code in a new JVM Calling other programs Setting environment variables Scheduling Ant builds automatically Scheduling builds in Unix and Windows Using scripting Using AntHill Creating email notifications Working with XDoclet and XML Creating XML build logs Handling web development Compiling JSP pages Using Ant s EJB tasks Using XDoclet for EJB development Connecting Ant to Eclipse Configuring Ant in Eclipse Writing Ant tasks Handling errors Writing custom filters and selectors Writing custom Ant loggers and listeners Here s an overview chapter by chapter downloaded from lib ommolketab ir downloaded from lib ommotketab ir Chapter 1 This chapter is all about the basics including all the details on how to create Ant build files and how to run them Chapter 2 Using Properties and Types This chapter is about two central Ant topics properties and
335. s handling cookies and so on e JavaBean Tester is a tool to automate the testing of JavaBeans e Jemmy is a Java library that is used to create automated tests for Java GUI applications e jenerator generates Unit Tests for all types of EJB for J Unit and Cactus e FCUnit enables you to execute unit tests against Swing based code e JUnit JNDI DataSource helper package can simulate J NDI lookups for database connections e UnitDoclet generates TestSuites TestCase skeletons and default tests from Java sources e UnitPerf is a collection of J Unit test decorators to test scalability e UnitX provides access to private and protected classes methods and variables between different packages for testing purposes e jWebUnit provides a high level API for navigating a web application combined with a set of assertions to verify the application s correctness e Log4Unit is a JUnit extension combining J Unit with Log4J e Schema Unit Test SUT is a framework for testing XML Schema e SQLUnit is a regression and unit testing harness for testing procedures stored in a database downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Chapter 6 Getting Source Code from CVS Repositories Up to this point you ve been working solo with Ant butas with any major build toolAnt can be used in team environments There s a lot of support built in for the Concurrent Version System CVS in Ant and this chapter is all abou
336. s ant types FileList public class ProjectType extends FileList public void setFiles String files super setFiles files The build file for the custom task appears inExample 12 23 the nested multiFile element s files attribute takes the list of files that will be stored in internal filelist of the object of the custom data type Example 12 23 Build file for the datatype example ch12 type build xml en vwersion 1 0 FS lt project basedir default main gt lt property name sre value src gt lt property name output value output gt downloaded from lib ommolketab ir downloaded from lib ommoltketab ir lt target name main depends jar gt lt taskdef name projectTask classname ProjectTask classpath Project jar gt lt projectTask gt lt multiFile dir srce files ed txt george txt gt lt projectTask gt lt target gt lt target name compile gt lt mkdir dir S output gt Javac Sredizv Siere cdestdir s output gt lt target gt lt target name jJar depends compile gt lt jar destfile Project jar basedir Sf output gt lt target gt lt oro 7 Set gt ProjectTask java which implements the projectTask task and uses the new datatype appears in Example 12 24 Example 12 24 Task that uses the new type ch12 type src ProjectTask java import data ProjectType import org apache tools ant Task import org apache
337. s inTable 2 2 Table 2 2 Elements that can be nested within the condition task Nested Functionality element land True if all of its contained conditions are true available Identical to the available task which checks for the availabilty of files Identical to the Ant checksum task which generates a checksum for files If you checksum compare two files that you think are the same but their checksums are different the files are different as well Checks if one string string contains another substring Optionally you can Contains make the test case sensitive with the casesensitive attribute The default is to make comparisons case insensitive Checks whether two strings are identical The strings are given using the required equals i attributes arg1 and arg2 The optional attributes are casesensitive and TRim Checks to see whether two files have identical contents The required attributes are filesmatch filel and file2 downloaded from lib ommolketab ir downloaded from lib ommolketab ir Nested Functionality element ii Checks for a valid response from a web server at the specified URL The required http attribute iS url and the optional attribute Is errorsBeginat the lowest HTTP response code that is an error isfalse Behaves the same aS istrue but returns the logically opposite value Checks if a particular reference has been defined The required attribute iSrefid isreference t
338. s mapper was designed to be useful to flatten directory structures where files have the fully qualified classname as part of their name this mapper was designed for use with the uptodate and junit tasks Here s an example lt mapper type package from Beta java to Beta Beta xml gt For example if you used this mapper element onorg steve tools ant util AntTaskBeta java it will create Beta org steve tools ant util AntTaskBeta xml flattening the directory structure but still letting you see where files come from The unpackage Mapper new since Ant 1 6 is the reverse of thepackage mapper that is it replaces dots in a package name with directory separators Here s an example lt mapper type package from Beta Beta xml to Beta java gt This is a useful one if you want to restore the original directory structure after flattening it with the package Mapper This example will take files such as Beta org steve tools ant util AntTaskBeta xml back to org steve tools ant util AntTaskBeta java downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Chapter 3 Building Java Code Ant is the premiere build tool for Java developers and this chapter focuses on the J ava build process from compiling Java code with the javac task through compressing and packaging the results with tasks such aS jar and tar Along the way I ll discuss several central build issues such as keeping track of the build number sto
339. s servlet is manager so this is something like http localhost 83080 manager The app path property holds the context path at which this application should be deployed usually plus the name of the application as you want to use it in the URL to access the application online Th amp uila property downloaded from lib ommolketab ir downloaded from lib ommotketab ir holds the location at which you build the Web application as it should be installed in the Tomcat webapps directory If you have installed an application and want Tomcat to recognize you have updated J ava classes use the reload task instead lt target name reload gt lt reload url manager url username S manager username password S manager password pathi app bath lt target gt To remove a Web application use theundeploy task lt target name remove gt lt undeploy url S manager url username manager username password S manager password path Sf app path gt lt target gt downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 8 6 Deploying to Tomcat More often than not you won t be developing your applications on the same server you want to deploy 1 You can deploy to a Tomcat installation running on a remote server by contacting the Tomcat manager servlet via URL in a browser To do that in Ant you use theget task which gets a file when you pass it a If you re using Java 1 4 or l
340. see the attributes of the jspc task in Table 8 5 downloaded from lib ommolketab ir downloaded from lib ommolketab ir Table 8 5 The jspc task s attributes Attribute Description Required Default Specifies the classpath to use when you re running the classpath JSP compiler You can specify this by nestedclasspath No elements PEE Specifies the classpath to use when you re running the No JSP compiler by reference PEE TE specifies the classname of a JSP compiler such aS jasper No E Or jasper42 DEE T EE EEE T Specifies the classpath that should be used to find the a n REE specified by the compiler attribute fdestdir Specifies where you want to place the compiled files where you want to place the compiled files failonerror Specifies if the task to fail if it encounters an error s ieplugin Specifies the Java Plugin class ID for Internet Explorer N No MeS Specifies you want to generate separate write statements No a for each HTML line in the JSP Set to true false Specifies the name of the destination package for the package No generated compiled classes Specifies where you want the task to look for source JSP srodir Yes files Specifies the base URI for relative URI references in JSP uribase No saa Sets the root directory from which URIs should be Uriroot resolved Specifies you want full verbose output Set to an Integer y verbose value 0 9 Specifies the filename for the secti
341. setUp Lets you perform initialization operations Lets you clean up after your tests such as closing a network connection protected void tearDown jJaveslang ocring toString Returns a string representation of a case 5 1 1 Writing the Tests To add J Unit test cases to your code you import junit framework TestCase base your application s class on it and write test cases Test cases are methods whose name begins with test which means J Unit will call them automatically In this example there are three test caseS testTrue to test the return value of the returnTrue method testEquals to test the results of the return4 method and testNotNull to test the results of the returnobject method All three of these test cases will be called automatically by the J Unit framework Inside test cases you can use the J Unit methods like assertTrue assertEquals and so on to make sure the build didn t break your application To make this work import junit framework TestCase extend that class and add three test cases to test the three methods in your codehe J Unit framework will call all three test cases automatically because their names start with test package org antbook import junit framework TestCase public class Project extends TestCase public Project String name downloaded from lib ommolketab ir downloaded from lib ommolketab ir public void testTrue pu
342. sredizy Siere d estdir s outpue gt lt target gt lt project gt The results show that the build file reports the name of the project as set by theproject element s name attribute and the line location in the build file Sant Bulldfile build xml compile mkdir Created dir home steven ant chl2 projecttask output javac Compiling 1 source file to home steven ant chl2 projecttask output Jar jar Building jar home steven ant ch12 projecttask project jar main project Welcome to project TheTask at home steven ant ch12 projecttask build xml1 9 BUILD SUCCESSEUL Total time 3 seconds 12 2 3 Handling Attributes in Custom Tasks If your custom task supports attributes Ant will pass the value of the attribute to your code if you have setter method much as you d use in a JavaBean For example if you have an attribute namedianguage define a method e g public void setLanguage String language Ant will pass this method the string value after performing any needed property expansion of thelanguage attribute Strings are the most common attribute values but you can ask Ant to perform conversions of attribute values to other data types based on the type of the argument in your setter method Here are the possi data types and how they re handled downloaded from lib ommolketab ir downloaded from lib ommotketab ir boolean Your method will be passed the value true if the value specified in the
343. ss Microsoft 2nd 3rd 4th millis attribute touch task mimemail task mimetype attribute message element mkdir task 2nd 3rd 4th mmetrics task mockdoclet task XDoclet mode attribute manifest task tarfileset element modification dates files 2nd modification sets modificationset task modified selector modules checking out 2nd defined updating shared code 2nd move task deployment and 2nd 3rd description filterchain element mappers and renamextension task and MParse compiler Metamata mparse task downloaded from lib eommolketab ir downloaded from lib ommotketab ir multithreading tasks 2nd mvcsoft element ejbdoclet task downloaded from lib ommolketab ir downloaded from libeommolketab ir Index A B C D E F G H H J K L M N O P Q R S O U V W RX 2 name attribute attribute element 2nd elements supporting 2nd factory element outproperty element param element project element 2nd 3rd property element section element target element taskdef task test task name property input task name value format naming attribute ejbjar task native2ascii task nesting arg elements batchtest element catalogpath element and checksum task and chmod task and classpath element dependencies and DirSet type and ejbdoclet task and 2nd ejbjar task and elements 2nd 3rd 4th fileset elements 2nd 3rd 4th 5th FilterChain type generic element
344. stance of classname aS a listener which ts alerted when build events occur e g starting and stopping of the build process 1 l i Ba esa Nuy rae Specifies the class to handle logging of Ant s output NOLnpuL l baa Turns off interactive input projecthelp p l l l file Til Tedi propertyriie faze Loads properties from the specified file _ iet o Ca Reduces Ant messages to the minimum possible verbose v an loam Specifies verbose output version ma Prints the version of Ant being used listener classname downloaded from lib ommolketab ir downloaded from lib ommotketab ir Ant Is Just Java Ultimately Ant is just Java code and can be run with java like any other J ava class java Dant home home steven ant org apache tools ant Main options target target2 target3 You can use the Ant Launcher which first appeared in Ant 1 6 java Dant home home steven ant org apache tools ant launch Launcher options target target2 target3 1 5 2 Executing Ant If you want to use a build file named build xml and want to run the default target enter ant in the directory containing the build file Sant For example if you ran the build file fromExample 1 2 that command gives this result bash 2 05bS ant Buildfile build xml compile javac Compiling 1 source file compress jar Building jar home httpd vhosts builder Project jar main echo
345. summary yes haltonfailure yes gt lt formatter type brief usefile true gt downloaded from lib eommolketab ir downloaded from lib ommolketab ir lt classpath path gt lt batchtest todir S results gt lt fil set dir includes Project class gt lt batchtest gt lt Junit lt target gt lt target name compress gt lt jar destfile jars Project jar basedir S output gt lt include name class gt lt jar gt lt target gt lt Larget Tame deploy gt lt delete dir S dist gt lt mkdir O1Fr Sicdistel gt lt copy todir Si dist gt lt fileset dir S jars gt lt include name jar gt lt fileset gt lt copy gt lt target gt lt project gt Here s what you see when you run the build file Sant Buildfile build xml cl a Ree mkdir Created dir home ant ch05 junit results mkdir Created dir home ant ch05 junit jars compile javac Compiling 1 source file to home ant ch05 junit testi java java Time 0 java OK 3 tests test2 junit Running org antbook Project LJ nic Tests tun 3 Failures O Errors 0 Time elapsed v 01 downloaded from lib ommolketab ir eC downloaded from lib ommolketab ir Cerco Junie Running grg antbook Projec junit Tests run 3 Failures 0 Errors 0 Time elapsed 0 01 sec test4 Janit Running ord anlboook Pro ject junit Tests run 3 Failures 0 Errors 0
346. t library files and ANT OPTS environment variable antcall task 2nd 3rd antfile attribute ant task Anthill build tool Antidote IDE antlr task downloaded from lib ommolketab ir downloaded from lib eommolketab ir antrc_post bat file AntSoundPlayer class 2nd antstructure task 2nd 3rd 4th apachesoap element ejbdoclet task append attribute apply task cvs task exec task java task sshexec task application attribute weblogic element applications deploying by copying moving files 2nd packaging for deployment remote deployment using FTP remote deployment using SSH 2nd remote deployment using telnet remote deployment via email setting file protections with chmod 2nd apply task 2nd 3rd appxml attribute ear task 2nd arg element arguments and 2nd example exec task and generic element and jonas element and args attribute java task weblogic element argument element ASCII characters Assert class JUnit assertEquals method JUnit 2nd 3rd 4th 5th assertFalse method JUnit 2nd assertions element 2nd Assertions type assertNotNull method JUnit 2nd 3rd assertNotSame method JUnit 2nd assertNull method JUnit 2nd assertsSame method JUnit 2nd assertI rue method JUnit 2nd 3rd 4th 5th asterisk 2nd 3rd 4th at command Windows 2nd at sign attrib task attribute element manifest task xmlvalidate element and xslt style task and attributes downloaded from lib ommolketab ir
347. t hpas element ejbdoclet task HTML reports HtmlUnit framework JUnit extension htto element condition task 2nd http schema https schema HttpUnit framework JUnit extension hyphen downloaded from lib eommolketab ir downloaded from libeommolketab ir Index A B C D E F G H H J K L M N O P Q R S M U V W RX Z IBM Eclipse and icontract task id attribute FilterSet type patterns and xmicatalog element identity mapper 2nd ieplugin attribute jspc task if attribute batchtest element elements and elements supporting fail task and 2nd formatter task param element target element test task if statement See conditions ignoreerrors attribute get task ignoreNoncriticalErrors attribute ftp task ignoresystemclasses attribute available task ignorewhitespace attribute patch task ilasm task ildasm task image task imageurl attribute splash task import command CVS import task 2nd 3rd ImportTypelib task in attribute xslt style task include element cab task and depend task and DirSet type and fileset element and FileSet type filesets and jar task and javac task PatternSet type and support element and xslt style task and zip task and downloaded from lib eommolketab ir downloaded from lib eommolketab ir includeantruntime attribute javac task junit task includeEmptyDirs attribute copy task delete
348. t and reference it later lt filter set id today filter begintoken endtoken gt lt filter token DATE value S TODAY gt lt filter set gt lt copy file S archives build java toFile source build java gt lt filter set refid today filter gt lt l copy If you just want to replace text in a file you can use the Antreplace task Here s an example lt replace file S src index html token author value Ted gt You can use the concat task designed to concatenate files together to concatenate text to the end of a file like this COncac destfile readme txt gt Copyright C 2005 lt concat gt You can see the attributes of this task inTable 2 15 Table 2 15 The filter task s attributes downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required The file from which you want filters to be Token and value attributes must be filtersfile read you format this file like a property provided or only the filtersfile file attribute po os 2 3 8 Filtering and Modifying Text with FilterChains and FilterReaders Token and value attributes must be provided or only the filtersfile attribute The token string to match omit the beginning and end tokens Token and value attributes must be provided or only the filtersfile attribute The string to replace the token with A FilterReader fi
349. t class path or the system whichresource n le peee xmiproperty Loads Ant Loads Ant properties from an XML property file from an XML property file xslt style Transforms a set of documents via XSLT zip Creates and packs a new ZIP archive 1 4 3 2 Optional tasks downloaded from lib ommolketab ir downloaded from lib ommotketab ir Besides these built in tasks called thecore tasks Ant supports many optional tasks which you can see in Table 1 4 These tasks may require the support of additional J AR files which you load into the Ant lib directory For example ftp uploads files to remote servers you need to place the JAR files jakarta oro jar and commons net jar in your Ant lib directory to use the task Another optional task IS csc which compiles Microsoft C code lt csc optimize true debug false warnhevel 4 unsafe false targetType exe incremental false mainClass Main destFile app exe gt lt erce dir sro inclvdes cs gt lt reference file S testCSC dll gt lt define name RELEASE gt lt o20 gt To determine which additional J AR files an optional task needs see http ant apache org docs manual index html librarydependencies which lists the needed libraries for each optional taskand where to get them Table 1 4 Optional Ant tasks Task name Description antie Runs the ANTLR Translator Generator Language Tool attrib Changes the permissions and or attr
350. t from the User Section 3 3 Calling Other Ant Tasks Section 3 4 Importing Other Build Files section 3 5 Documenting Code Section 3 6 Creating JAR Files Section 3 7 Setting Build Numbers Section 3 8 Setting Timestamps Chapter 4 Deploying Builds Section 4 1 Packaging Applications for Deployment Section 4 2 Preparing to Deploy Section 4 3 Deploying Applications Section 4 4 Scheduling Automatic Builds Chapter 5 Testing Builds with JUnit Section 5 1 Using JUnit lt downloaded from lib eommolketab ir downloaded from lib eommotketab ir Section 5 2 Running Test Cases Section 5 3 Testing in Batches Section 5 4 Running the Build File Section 5 5 Extending JUnit Chapter 6 Getting Source Code from CVS Repositories Section 6 1 Source Control and Ant Section 6 2 Logging In Section 6 3 Working with the Server Section 6 4 Getting Version Data Section 6 5 Creating Change Logs Section 6 6 Finding Changes Between Versions Section 6 7 Creating Patches Chapter 7 Executing External Programs Section 7 1 Executing Java Code Section 7 2 Executing External Programs Section 7 3 Performing Batch Execution Section 7 4 Multithreading Tasks Section 7 5 Setting Execution Order Chapter 8 Developing for the Web Section 8 1 Creating WAR Archives Section 8 2 Creating CAB Files Section 8 3 Creating Simple Web Deployment Section 8 4 Deploying with SCP Sectio
351. t making code sharing in teams with CVS happen downloaded from lib ommolketab ir downloaded from lib ommolketab ir 6 1 Source Control and Ant When you work in teams you have to coordinate your efforts That means discussing and planning but even with the best of intentions you can still end up with unintentional conflicts You may have made some brilliant changes to the code only to find them wiped out by mistake when another programmer uploads his own version of the same file Source control helps prevent these problems by controlling access to code and by maintaining a history of the changes made so things aren t destroyed unintentionally Storing a history of your code IS powerful you can compare a new buggy file against an older one and you can revert to a previous version in case things have gone bad Ant has several source control tasks shown inTable 6 1 Table 6 1 Source control tasks Task name Description Tasks for ClearCase cleartool checkin checkout uncheckout update clearcase lock unlock mklbtype rmtype mklabel mkattr mkdir mkelem and mkbl Commands Tasks for Continuus cemcheckin cemcheckout cemcheckintask ccmreconfigure and cemcreateTask commands Continuus Synergy tasks Specifies how to work with packages and modules retrieved from a CVS repository cvschangelog Creates change reports from a CVS repository cvspass Adds entries to a cvspass file Creates an XML forma
352. t mkdir dir S output gt lt javac srcdir src destdir S output gt lt target gt lt target name Jar depends compile gt lt jar destfile Project jar basedir output gt lt target gt sJ project In the code supporting this custom task shown in Example 12 10 you need a class Nested representir the nested element and you can use a method named createNested to handle calls from Ant for eact nested element Each time createNested IS called the code adds the new nestea element to a vector named nesteds The language attribute of each nestea element is passed to the setLanguage method and can be recovered with the getLanguage method After the vector is filled the execute method i called and the code iterates over thevector displaying the language attribute value for each nested element Example 12 10 Handling nested elements ch12 nestedelement src Project java import Java util Vector import java util Iterator import org apache tools ant Task import OoOrg dpache Lools antl Bu1ldkxcept ion public class Project extends Task public void execute for Iterator iterator nesteds iterator iterator hasNext Nested element Nested iterator next System out printin The language is element getLanguage Vector nesteds new Vector public Nested createNested Nested nested new Nested nesteds add nested return nested
353. t you need from http www cvshome org Many CVS servers are available for Windows such as CVSNT available for free from http www cvsnt org To install CVSNT download the executable file and run it The idea behind CVS as with any repository software is to manage and record changes to source code What corresponds to a project for Ant is amodule in CVS Modules are represented by directories in CVS the files you share are stored in the CVSrepository When you retrieve a file from the repository you check the file out After you ve modified the file you commit the file checking it back in and sending those changes to the repository If you want to refresh your own copy of a file you update it from the repository Because each file must be independently tracked CVS gives the individual files a version number automatically Each time a file is committed its version number is incremented When you commit files to the repository they ll get a new version number as well Using the cvs task you communicate with the CVS server using CVS commands which appear in Table 6 2 Read more about these commands in the CVS guide at https www cvshome org docs manual cvs 1 11 7 cvs 16 html Table 6 2 CVS commands ie Does this add Specifies you want to add a new file or directory to the CVS repository admin Lets you work with administrative commands annotate Specifies the revision where each line was modifi
354. tProperty method Project class 2nd 3rd getReference method Project class getReferences method Project class getRuntimeConfigurableWrapper method Task class getTarget method BuildEvent getlargets method Project class getl ask method BuildEvent getTaskDefinitions method Project class getlaskName method Task class getlaskT ype method Task class getUserProperties method Project class getUserProperty method Project class getWrapper method Task class glob mapper 2nd 3rd group attribute javadoc task tarfileset element Gump build tool 2nd gunzip task 2nd downloaded from lib ommolketab ir downloaded from lib ommotketab ir gzip task 2nd 3rd 4th downloaded from lib ommolketab ir downloaded from lib eommolketab ir Index A B C D E F G H 1 J K L M N O P Q R S O U V W RX 2 h option haltonerror attribute batchtest element junit task test task haltonfailure attribute batchtest element junit task 2nd test task handleErrorFlush method Task class handleErrorOutput method Task class handleFlush method Task class handleInput method Task class handleOutput method Task class header attribute javadoc task headfilter element FilterChain type 2nd help option helpfile attribute javadoc task hibernatedoclet task XDoclet history command CVS homeinterface element ejbdoclet task host attribute sshexec task hot deploymen
355. tains a Containsagroupofdirectories of directories FileList Contains a named list of files FileSet Contains a groups of files File mappers Maps original filenames to a new set of names FilterChains Contains a group of ordered FilterReaderS ines FilterSet er ee a o ao Contains a group of filters PatternSet Contains a group of filename Contains a group of filename matching patterns patterns Path like ires Includes a wide variety of support for specifying file paths Contains the security permissions given to the code as executed in the JVM Permissions where Ant is Pe a m r running PropertySet Groups a set of properties Groups a set of properties together Groups files in a fileset selected using criteria other than filename as provided Selectors by the include and exclude tags XMLCatalog Contains a catalog of public XML resources such as DTDs or entities ZipFileSet Contains a special form of afileset using ZIP files downloaded from lib ommolketab ir downloaded from lib ommotketab ir Many Ant tasks in the upcoming chapters depend on the types you see inTable 2 7 so it s worth going through them in detail especially the ones that handle files Understanding Ant types is centra to using Ant if you don t understand paths andFrilesets for example you ll be severely hampered by what you can do with Ant 2 3 1 Path Like Structures In Ant paths are often handled by the path type called apath li
356. task and webdoclet task xslt style task and FileSet type attributes batch testing and cab task and chmod task and defaultexcludes delete task and depend task and description fixcrlf task and jar task and javac task and pathconvert task and PatternSet type and purpose tar task and tarfileset elements and zip task and filesetmanifest attribute jar task filesets 2nd filesmatch element condition task filesonly attribute ear task jar task war task zip task filter task 2nd FilterChain type 2nd 3rd filtering attribute copy task filterreader element FilterChain type 2nd FilterReaders filters copy task and custom files and 2nd FileSets as text and FilterSet type 2nd filtersfile attribute filter task filtertrace attribute batchtest element junit task test task find option 2nd firewalls fixcrif task 2nd downloaded from lib ommolketab ir downloaded from lib eommolketab ir fixlast attribute fixcrlf task flags attribute replaceregexp task flatdestdir attribute ejbjar task flatten attribute copy task flatten mapper 2nd 3rd followsymlinks attribute DirSet type FileSet type footer attribute javadoc task force attribute ejbdoclet task webdoclet task xslt style task forceoverwrite attribute checksum task fork attribute batchtest element java task javac task junit task test task forking based on true false properties compiler java task and
357. task in Table 4 7 Table 4 7 The checksum task s attributes Attribute Description Required Default staan enn Specifies the algorithm you want to use to No aie compute the checksum One of file or Specifies the file you want to generate the at least one Pad checksum for nested fileset element Specifies the extension of the file for the ORAUS ORE fileext No algorithm name generated checksum being used Specifies whether you want to overwrite forceoverwrite se No no existing files If verifyproperty IS not set property specifies the name of the property to hold property the checksum value If verifyproperty is No set property specifies the actual checksum value you expect provider Specifies the algorithm provider No ee Specifies the size of the buffer the task No oe Should use when reading files in bytes Checksum files are written to the same directory as the source files Specifies the directory where you want codir checksums to be written Available since No Ant 1 6 Specifies the name of the property that eE you want to hold a checksum of all the No generated checksums and file paths Available since Ant 1 6 Specifies the name of the property to be ET E OR set true Or false depending upon whether No the generated checksum matches the existing checksum downloaded from lib ommolketab ir downloaded from lib ommotketab ir The checksum task can cont
358. tat task P4Have task P4Integrate task P4Labeltask P4Labelsync task P4Reopen task P4resolve task P4Revert task P4Submittask P4Sync task Pack class package attribute cvs task cvschangelog task cvstagdiff task cvsversion task javadoc task ispc task Package Explorer Eclipse build xml file and 2nd creating build files creating projects package mapper 2nd packagelist attribute javadoc task packagenames attribute javadoc task packageSubstitution element ejbdoclet task webdoclet task packaging applications deployment parallel attribute apply task chmod task parallel task 2nd 3rd param element nesting xslt style task and parentheses downloaded from lib eommolketab ir downloaded from lib eommolketab ir parser attribute xmlvalidate task passfile attribute cvs task cvschangelog task cvspass task cvstagdiff task cvsversion task passive attribute ftp task passphrase attribute scp task sshexec task passwd command CVS password attribute cvspass task fto task generic element get task mail task scp task 2nd sshexec task telnet task weblogic element assword property input task passwords 2nd 3rd patch task 2nd 3rd patchfile attribute patch task path attribute compilearg element env element PATH environment variable path type 2nd 3rd path like structures core Ant types javac task and junit task and overview pathconvert task 2nd path
359. tdescriptor Specifies you want to generate a web xml deployment descriptor fileset Specifies a fileset to indicate the files to parse jbosswebxml Specifies you want to generate ajboss web xml deployment descriptor E E Specifies you want to generate a web application deployment descriptor for JOnAS jrunwebxml Specifies you want to generate ajrun web xml deployment descriptor oe Specifies you want to generate ataglib tld deployment descriptor for JSP taglibs packageSubstitution Substitutes a new package for the package in generated files resin web xml Specifies you want to generate web xml with Resin extensions strutsconfigxml Specifies you want to generate a struts config xml deployment descriptor Sn nen ete ae want to generate a Struts Validator validation xml deployment subTask Specifies a subtask for this task ioa Specifies you want to generate a weblogic xml deployment descriptor for We applications webspherewebxml Specifies you want to generate WebSphere specific deployment descriptors wevorkectLondoes n i you want to generate HTML files containing descriptions of WebWo downloaded from lib ommolketab ir downloaded from lib ommotketab ir Element Description webworkactionsxml Specifies you want to generate an actions xml file webworkconfigproperties Specifies you want to generate a views properties file You use tags prefixed with ane to tell XDoclet what you want it t
360. te JavaCC compiler 2nd javacc task JAVACMD environment variable javadoc task 2nd Javadoc wizard Eclipse javadoc2 task javafiles attribute fixcrlf task javah task JavaServer Pages JSPs 2nd JAXP Sun jboss element ejbdoclet task 2nd jbosswebxml element webdoclet task JcovMerge task JcovReport task JDBCTask class idepend task JDK Java Development Kit 2nd 3rd idodoclet task XDoclet Jemmy Java library Jenerator JFCUnit JJDoc documentation generator jjdoc task JJTree preprocessor jjtree task link task imxdoclet task XDoclet JNDI DataSource helper package JNI Java Native Interface JONAS deployment tool jonas element ejbdoclet task nesting downloaded from lib ommolketab ir downloaded from lib eommolketab ir serverdeploy task 2nd JONAS servers ejbdoclet task and EJBs and hot deployment and jonas element and 2nd jonasroot attribute jonas element jonaswebxml element webdoclet task JPCoverage task jorobe task jrun element ejbdoclet task jrunwebxml element webdoclet task isharpc task ispc task 2nd JSPs JavaServer Pages 2nd isptaglib element webdoclet task JUnit framework Ant tasks and 2nd batch testing 2nd extending overview performing tests running build file running test cases writing tests junit task description example 2nd overview packager mapper and performing tests with testing with JUnitDoclet JUnitPerf junitreport task 2nd JUnitX
361. te DataHandler class return suite When you re using J Unit from Ant it s easier to usebatch testing with the nested batchtest task This task lets you specify whole filesets to test using thefileset type and the results will be merged into a report Here s how to uS batchtest lt target name test6 depends compile gt lt junit printsummary yes haltonfailure yes gt lt formatter type brief usefile true gt lt classpath path gt lt batchtest todir results gt lt fileset dir includes Project class gt lt batchtest gt lt 7 Vn gt lt target gt In this case the fileset only contains a single file there s only one file to test in this chapter s example but you can include as multiple files in your nestedfileset element lt target name test6 depends compile gt lt junit printsummary yes haltonfailure yes gt lt formatter type brief usefile true gt lt classpath path gt lt batchtest todir results gt lt fileset dir build gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt include name Test class gt lt include name Gold class gt lt exclude name Beta class gt lt fileset gt lt batchtest gt lt 7nit gt lt target gt downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 5 4 Running the Build File That completes the build file that runs the J U
362. te xmlproperty task colon command attribute cvs task 2nd 3rd 4th exec task sshexec task command line environment variables and options for 2nd 3rd 4th commandline element 2nd Commandline object commit command CVS committers compilearg element compiler attribute compilearg element javac task 2nd ispc task weblogic element compilerclasspath attribute jspc task compiling documentation and JSPs source code source files component attribute weblogic element compress attribute cab task ear task jar task war task zip task compression attribute cvs task cvstagdiff task tar task 2nd compressionlevel attribute cvs task concat task 2nd 3rd concattilter element FilterChain type downloaded from lib eommolketab ir downloaded from lib eommolketab ir Concurrent Version System See CVS condition task 2nd 3rd 4th conditions configParam element ejbdoclet task webdoclet task Console view Eclipse 2nd constants 2nd containers EJB and 2nd contains element condition task linecontains filter and contains selector 2nd containsregexp selector 2nd content assist Eclipse Continuous source control servers Continuus commands copy task deployment and description file filtering file sets and filterchain element mappers and copydir task copyfile task cr attribute fixcrlf task createDatal ype method createResult method JUnit create ask method Project class 2nd cr
363. th gt Include the jar file containing Sun s javax ejb classes on the taskdef task s classpath when creating the ejbdoclet task in a build file You can create a deployment descriptor ejb jar xml with the deploymentdescriptor element lt deploymentdescriptor destdir S app meta inf dir description ejbbean gt The entire build file appears in Example 9 9 This file is designed to be run from a directory named ejbbuild right under the XDoclet unzip directory with the servlet s code in the directory butld src java app web Example 9 9 The EJB bean build file chO9 ejb build xml lt 7 Vereicn 1 0 7 gt lt path id app class lt fileset dir Lib dir lt include name jar gt lt fileset gt lt fileset dir S app lib dir gt lt include name jar gt lt fileset gt lt path gt lt target name init gt Lo amo lt format property TODAY pattern d MM yy gt downloaded from lib ommolketab ir lt project default main basedir gt lt property name lib dir value lib gt lt property name app dist dir value output gt lt property name app srce dir value src gt lt property name app java dir value S f app src dir java gt lt property name app generated srec dir value S app dist dir generated src gt lt property name app web inf dir value S app dist dir web inft gt lt property name app classes dir value S app dist dir classes
364. th of the command line arguments is working over 4 K Available since Ant 1 6 directory Specifies that you want the compiler to verbose No no generate verbose output This is where the meat is for most Java authors This taskwhich should be one of your staplesmakes sure the source directory will be recursively scanned for J ava source files to compile and compiles them Only Java files that have no corresponding class file or where the class file is older than the java file will be compiled The javac task forms an implicit FileSet and supports all attributes offileset note that dir becomes srcdir as well as the nested include exclude and patternset elements And because the javac task S srcdir classpath sourcepath bootclasspath and extdirs attributes are path like structures they can be set via nested src classpath sourcepath bootclasspath and extdirs elements 3 1 1 Compiling Source Files Here are a few javac examples starting with a standard example that compiles all java files in and under the src directory and stores the class files in the bin directory In this case the classpath includes common jar and we re compiling with debug information turned on lt Tavac Srcedir sicrc debug on destdir IDin classpath common jar gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir This next example compiles java files in and under the src and src2 directories s
365. the jar file lt echo gt lt target gt lt target name compile gt lt javac srcdir gt lt target gt lt target name compress gt lt jar jarfile Project jar basedir includes class lt target gt lt project gt When you run Ant it ll look for build xml and execute the default target which the project element indicates iS main The main target s depends attribute tells Ant to run the compile target and then run the compress target before running the body of the main target downloaded from lib ommolketab ir downloaded from lib ommotketab ir Though you use this attribute to indicate the order targets should run in targets can still fail which means you re not guaranteed that they will all behave as expected Generally a failed target will stop the Ant build process but that s not always the case Bear in mind that dependencies can be nested inadvertently For example take a look at this build file fragment lt target name find gt lt target name inspect depends find gt lt target name test depends inspect gt lt target name purchase depends test inspect find gt If target purchase was the default target you might think that targets test inspect find and purchase were executed in that order However targettest depends on target inspect which depends on find and so on An Ant target gets executed once even when multiple targets depend on it Bec
366. ther the task should display verbose what it s doing as it does it Available in An No false 1 6 or later This task holds an implicit FileSet and supports all of FileSet s attributes and nested elements directly Since Ant 1 6 you can specify nestedfileset Or dirset elements and you can use nested filelists downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 4 4 Scheduling Automatic Builds It s time to add some automation to the build process When you re working alone you probably won t r automate nightly builds but as part of a team it s a good idea Larger projects typically have nightly bu posted to a web site and using various automation tools and tasks likeftp that s no problem I ll take i at various options here 4 4 1 Unix You can schedule recurring builds with Unix utilies likecrontab which you use to configure the cron dael For example say you have a Shell script that runs your nightly build dobuild sh something like this export ANT_HOME usr local ant export JAVA_HOME usr local jdk1 4 export PATH S PATH S5 ANT_HOME bin cd home work ant i naghttlybuild aml You can schedule that build to happen at various times witNhcrontab by starting its editing mode bash 2 05bS crontab e Edit the crontab file to include this line run at 00 01 every day 30 0 SHOME work dobuild sh That makes your build run every night at 12 01 A M Easy enough 4 4 2 Windows The
367. they will propagate throughout the build file You can see the attributes of theproperty element in Table 1 13 downloaded from lib ommolketab ir downloaded from lib ommolketab ir Table 1 13 The property element s attributes Attribute Description Required classpath The classpath to use when looking for a resource No The classpath to use when looking for a resource which classpathref can then be given as a reference to a path element later in No the build file environment file Otherwise the supplied filename is taken as a path relative location to the project s base directory and then expanded name The name of the property to set No n The prefix to add to properties loaded from a file or a No af resource A is appended to the prefix if none is specified A value location Or refid A reference to a previously defined object Bose Clement required when using the name attribute A resource file url EOE The resource name of the property file used for searching or environment attribute the classpath is required when not using the name attribute A resource file url url The URL from which to read properties Oca aorta autre is required when not using the name attribute A value location Or refid element is 1 value The value of this property required when using the name attribute As an example you can store a message that displays Building the jar file in a prope
368. thin a build file is a bad habit to get into and almost impossible to maintain Using property files means that you can quickly tailor a build file to different sets of circumstances by Swapping property files And you can store property values though we ve been using mostly true false properties to make conditional processing easier they can hold all kinds of textual data such as copyright notices and legal information in a central repository everyone can share You can specify a property file to use on the command line with the propertyfile option Take a look at Example 2 2 which uses a property file to hold a property namedmessage This example points to the property file with the property task s file attribute which can hold the fully qualified name of the file You can use the property tasSk s url attribute to point to a property file Example 2 2 Using a property file chO2 properties build xml lt xml version 1 0 gt lt project default main gt lt property file build properties gt lt property name src location source gt lt property name output location bin gt lt target name main depends init compile compress gt lt echo gt message lt echo gt lt target gt lt target name init gt lt mkdir dir outpu t 7S lt target gt lt target name compile gt lt javac srcdir S sre destdir S output gt lt target gt lt target name compress gt lt
369. tiln files loopIndex downloaded from lib ommolketab ir downloaded from lib ommotketab ir Project java is the only java file in the project and that s the file the custoM project task picks up Cs ant ichl2 rileset ant P ildfile build xml compile javac Compiling 1 source file to home steven ant ch12 fileset output jar jar Building jar home steven ant chi2 fileset Project jar main project src Project java BUILD SUCCESSFUL Total time 4 seconds Extending MatchingTask to Support includes and excludes nested elements you can make your task support filesets 12 2 8 Running External Programs Custom Ant tasks are often wrappers for existing programs You can launch an external program from tl Support code for a custom task if you use theorg apache tools ant taskdefs Execute Class Example 1 13 shows how this works and launches Windows WordPad and opens the project s build file in it Example 12 13 Executing external programs ch12 executetask src Project java import java io 1OException import org apache tools ant Task import org apache tools ant taskdefs Execute import org apache tools ant types Commandline public class Project extends Task public void execute Commandline commandline new Commandline commandline setExecutable C Program Files Windows NT Accessories wordpad exe commandline createArgument setValue C ant ch12 executetask build x
370. to keep track of build numbers The first version of your software might be 1 0 0 an update might be 1 0 1 a major update might be 2 0 0 and so on Thebuildnumber task is a basic task that can be used to track these kinds of build numbers This task will first attempt to read a build number from a file by default build number in the current directory and set the property build number to the value that was read in or to O if no value was read It will increment the number by one and write the new value back to the file This task has only one attribute file which holds the name in which you want to store the build number This attribute is not required I ll take a look at an example usingbuildnumber after discussing time stamps the next topic downloaded from lib ommolketab ir downloaded from lib ommotketab ir 3 8 Setting Timestamps The tstamp task sets properties holding the current time so you can time stamp your builds This task creates the pstamp day stamp TSTAmp time stamp and Topay properties in the current project By default the psTamp property is in the format yyyyMMdad TstTamp is in the format hhmm and TODAY is in the format MMMM dd yyyy If you use this task it s almost invariably run in an initialization target You can see how this works tn Example 3 5 which stores the build number and creation date in the project s jar file USING buildnumber and tstamp Example 3 5 Using the build numbe
371. to transform files scanincludeddirectories found in any directories specified by the No TRue include patterns Specifies the name of the stylesheet to style Yes use for the transformation This task forms an implicit fileset and so supports all attributes offileset dir becomes basedir as well as the nested include exclude and patternset elements You can use nested classpath elements to load the XSLT processor nested xmicatalog elements see Table 9 3 for entity and URI resolution and attribute elements see Table 9 4 to specify settings of the processor factory the attribute names and values are processor specific Thexsit style task Supports the use of nested param elements whose attributes appear in Table 9 7 to pass values to xsl1 param declarations in stylesheets then xslp in that order reloadstylesheet o Table 9 7 The param element s attributes Attribute Description Required name Specifies the name of an XSLT parameter you want set Yes expression Specifies the text value to be stored in the parameter Yes No N if Specifies you want to pass the parameter only if this property is set unless Specifies you want to pass the parameter only if this property is not set O downloaded from lib ommolketab ir downloaded from lib ommotketab ir You can use outputproperty elements whose attributes appear in Table 9 8 with a TraX processor to specify how the result tree
372. tools ant BuildException public class ProjectTask extends Task ProjectType multiFile null public void execute throws BuildException String files multiFile getFiles getProject for int Looplndex U loopind ex lt Tiles dength loocpindext SVeCeiwouc princi files Loopindex public ProjectType createMultiFile multiFile new ProjectType return multiFile downloaded from lib ommolketab ir downloaded from lib ommotketab ir Here s how it works ProjectTask java handles the nested multiFile element with a createMultiFile method which creates a new object of the ProjectType class our custom data type based on the FileList class ProjectType multiFile null public ProjectType createMultiFile multiFile new ProjectType return multiFile The setFiles method in the custom data type s support code creates a filelist from the list of files in the multiFile element s files attribute public void setFiles String files super setFiles files The files are now stored in the new datatype object namedmultiFile When the task executes it will display their names using that object public void execute throws BuildException String files multiFile getFiles getProject for int loopIndex 0 loopIndex lt files length loopIndex System out printin files loopIndex When this build file executes the custom task creates
373. toring class files IN bin Including common jar in the classpath and turns debug information on In this case only files in packages archive and packages backup will be includedand those in packages archive betapackage will be excluded javec Srecdiv sSisre 22 src7 destdir S build includes packages archive packages backup excludes packages archive betapackage classpath common yjar debug on gt Ant only uses the names of the source and class files to find the classes that need a rebuild It doesn t read the source codes and so has no knowledge about nested classes f you want to specify dependencies that Ant is having trouble with use the Antdepend task covered in Chapter 6 for advanced dependency checking One of the new aspects of Ant 1 6 is that it s OK to use 1 5 the newest version of Java as the Java version In javac attributes as source 3 1 1 1 Selecting which files to compile You can make javac compile only files that you explicitly specify as opposed to all files under the specified source directory You do that by disabling thejavac task s default searching mechanism by unsetting the sourcepath attribute and specifying the files you want to include and exclude explicitly as here where I m including only java files in the src directory lt javac sourcepath srcdir S src destdir S bin gt lt include name java gt lt javac gt 3 1 1 2 Forking the com
374. tribute Description Required Default Specifies you want to process the file s one line byline at a time executing the replacement on one line No false at a time eer Specifies the encoding of the file you re using No The default 7 Available since Ant 1 6 JVM encoding ee Specifies the file in which text matching the Yes if no nested regular expression should be replaced fileset IS used Specifies flags to use when matching the regular expression For example g means global flags iai l at No replacement I means case insensitive and so on Specifies the regular expression pattern you want Yes if no nested Male n to use to match text in the source file s regexp IS used Yes if no nested replace Specifies the text to replace matched text with substitution IS used This task Supports a nested fileset element You can use a nested regexp element to specify the regular expression this way lt regexp id id pattern st gt lt regexp refid id gt The replaceregexp task Supports a nested substitution element to specify the substitution pattern here are some examples lt substitution id id expression beta lalpha gt SUS Ubon Ferro 1 4 downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 10 4 Handling Dependencies The javac task does a good job of handling dependencies but it s limited because it only compiles java files if the corresponding class
375. tted report of the changes between two tags or dates recorded in a CVS repository CY a cvstagdiri Microsoft Visual Tasks for Visual SourceSafe vssget vsslabel vsshistory vsscheckin pOuUrcesale Tasks vsscheckout vssadd vsscp and vsscreate Commands Tasks for Perforce p4sync p4change p4edit p4submit p4have p4label p4counter p4reopen p4revert and p4add commands pves Retrieves and handles source code from a PVCS repository perforce Tasks for SourceOffSite sosget soslabel soscheckin and soscheckout commands SHurcCeort Isite Tasks for StarTeam stcheckout stcheckin stlabel and stlist commands starteam downloaded from lib ommolketab ir downloaded from lib ommotketab ir Though Ant lets you work with various source control systems most of its support revolves around CVS which is used throughout this chapter CVS is an open source project that started as a set of Unix shell scripts in 1986 and came into its own with dedicated software in 1989 Support for CVS is available on many operating systems Unix Linux Windows Mac and others For the full CVS story look at http www cvshome org To work with CVS using Ant you need access to a CVS server Most Linux and Unix installations come with a built in CVS server To test if you have a working CVS installation type cvs help at the prompt you should see a list of help items If you can t find a CVS server you can download wha
376. tting up builds to run on their own at a schedule of your choosing There s more on deployment coming up in this book Ant has a lot of support for deploying web applications so much so that it ll take more than just this chapter to cover Chapter 8 covers how to package and deploy web applications including using get used to send administrative commands to web servers remotely serverdeploy war and other Ant tasks designed to load web applications to various servers Chapter 8 and part of Chapter 9 also Specifically discuss how to deploy to Enterprise JavaBean EJB application servers downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 4 1 Packaging Applications for Deployment We re going to start with deployment tasks designed to package applications for deployment tar gzip and zip These are not the only way to package applications thejar task was covered in Chapter 3 on Java Development and the war task a special form of the jar task for Web applications that makes allowances for files like the deployment descriptorweb xml will be covered in Chapter 8 4 1 1 Creating TAR Files The tar task creates a TAR archive handy for archiving files for distribution This task is directory based and like other such tasks forms an implicit FileSet that defines which filesrelative to the basedir attribute settingwill be included in the archive If you set the compression attribute to gzip Or bzip2
377. ty attribute batchtest element junit task test task file attribute available task buildnumber task checksum task chmod task compilearg element copy task delete task echo task env element downloaded from lib ommolketab ir downloaded from lib eommolketab ir FileSet type import task manifest task property element property task 2nd replaceregexp task scp task taskdef task touch task xmlproperty task xmlivalidate task file mappers 2nd file option 2nd fileext attribute checksum task filelist element apply task FileList type 2nd 3rd 4th filemode attribute zipfileset element filename selector 2nd 3rd filepath attribute available task files checking contents of 2nd checking modification dates 2nd comparing 2nd compressing 2nd copying to local machines copying to new locations copying using filesets creating empty default excludes deleting filters and 2nd lists of mappers and 2nd moving 2nd property retrieving using ftp task selecting to compile setting creation time date 2nd setting protections with chmod 2nd working with groups of XML files attribute FileList type mail task fileset element cab task and catalogpath element and delete task and 2nd depend task and ejbdoclet task junitreport task and nesting 2nd 3rd 4th 5th downloaded from lib eommolketab ir downloaded from lib eommolketab ir overview replaceregexp task and scp task and war
378. ty tasks available for free athttp ant contrib sf net which includes a set of tasks for use with Ant and C Creating Ant tasks is easier than you might think and you re going to create your own inChapter 11 1 4 4 Dependent Tasks Typically you create an Ant build file with a default target named something likenain this target then acts as a master target handling program flow for the entire build process It tells Ant to run other targets and specifies their ordering This is accomplished through thetarget element s depends attribute For example you might want to add a target named compile to compile your code and add another downloaded from lib ommolketab ir downloaded from lib ommolketab ir target called compress to put the compiled code into a JAR file feml version 1 0 7 gt lt project default main gt lt target name main gt lt echo gt Building the jar file lt echo gt lt target gt lt target name compile gt lt javac srcdir gt lt target gt lt target name compress gt lt jar jarfile Project jar basedir includes class gt lt target gt lt project gt Ensure that the compile and compress targets runin that orderby assigning the string compile compress to the default target s depends attribute lt xml version 1 0 7 gt lt project default main gt lt target name main depends compile compress gt lt echo gt Building
379. types Properties let you configure Ant tasks and types hold data used by tasks Chapter 3 Building Java Code This chapter focuses on the Java build process from compiling Java code with thejavac task through compressing and packaging the results with tasks such aS jar Chapter 4 Deploying Builds This chapter covers tasks to package applications for deployments such aStar gzip and zip tasks to prepare directories for deployment such aSdelete and mkdir and tasks to deploy applications such aS copy and move for local and network deployment as well aS ftp telent sshexec and mail for remote deployment Chapter 5 Testing Builds With J Unit It doesn t make much sense to deploy code that has been broken by a new build This chapter using the J Unit framework with Ant during which you can run tests on your code and deploy it if it satisfies those tests Chapter 6 Getting Source Code from CVS Repositories There s a lot of Support built in for Concurrent Version System CVS in Ant and this chapter is all about making code sharing in teams with CVS happen Chapter 7 Executing External Programs Part of the build process involves testing what you ve built and an obvious way of doing that is to run the results of a build Doing so from Ant involves using the major tasks in this chapter java exec and apply Chapter 8 Developing for the Web downloaded from lib ommolketab ir downloaded from lib ommotketab ir This
380. u an overview of the targets in build files To open this view select Window Ant the Ant view appears at right in Figure 11 12 Show View Figure 11 12 The Ant view Ha ills Eclipse Plailormn E taml version 1 0 7 gt oject neme TEc lipse Example defau target nane nain depend comp ec hos Building the jar file lt ec hoe 17 Larget gt target mame compile descript io jerar sredic org antbook gt lt targets lt Larget name compress description jae jeartile Projece jar ba lt target gt lt project gt The toolbar in this view contains these buttons from left to right e Add Build Files e Add Build Files with Search e Hide Internal Targets e Run the Default Target e Remove Selected Build File downloaded from lib ommotketab ir e Buana L man defaut downloaded from lib ommotketab ir e Remove All Build Files To add a build file to the Ant view click the Add Build Files button opening the Choose Location dialog In the left box select the Eclipse project you want to use and in the right box select the buil file you want to add to the Ant view Click OK adding the build file to the Ant view In Windows you can add build files to the Ant View with drag and drop Besides giving you an overview of a build file the Ant view lets you run build files Select a build file in the Ant view and click the Run the Default Target button Or
381. u can use nested file sets for more flexibility and specify multiple ones to merge together different trees of files into one JAR No satse index whenempty The update parameter controls what happens if the jar file exists When set to yes downloaded from lib ommolketab ir downloaded from lib ommotketab ir the jar file is updated with the files specified When set to gee the default the jar file is overwritten Besides nested include exclude and patternset elements you can nest metainf and manifest elements in the jar task 3 6 1 Working with the META INF Directory The nested metainf element specifies a FileSet All files included in this fileset will end up in the META INF directory of the JAR file If this fileset includes a file namedMANIFEST MF the file is ignored but you ll get a warning telling you what s going on 3 6 2 Creating Manifest Files You use this task to write data into aJAR manifest file Themanifest task Supports two nested elements attribute which you can use to set attributes in a manifest file andsection which can create a section in a manifest file The attribute element has two attributes name the name of the attribute and value the value of the attribute The section element has one attribute name the name of the new section Here s an example which creates a manifest with attributes and sections lt target name compress gt lt jar destfile S out
382. u need to respond to error conditions and let the user know what has happened when errors do occur You often need to deal with groups of files copy them over en masse and more These kinds of tasks involve using properties and types downloaded from lib ommolketab ir downloaded from lib ommotketab ir 2 1 Using Properties to Control Tasks Ant provides extensive support for controlling the build process though Ant is not a programming language it has a number of control structures and those control structures rely on properties Asif and TRy catch allow you to handle several logic paths in Java Ant s control tasks allow you the same flexibility within the context of a build process 2 1 1 Setting Conditions The foundation to any type of control processing is some form of theif statement This typically involves two steps 1 Check or determine if a certain condition is true 2 If the condition is true perform one action if it is false perform another In Java this all happens in a single line of code in Ant the condition must be set in one step and the evaluation of that condition occurs in another step First you need to set a condition based on some criteria not surprisingly condition is the name of the task Ant provides condition allows you to specify one or more true false tests Sometimes calledcriteria If all the criteria evaluate to true a property supplied to the condition task is set to TRue If one
383. u want to exclude oo ee n Specifies a file each line of this file is used as an a NO exclude pattern file A shortcut for creating a A shortcut for creating a single filefiteset file fileset Specifies whether you want symbolic links to be foll link A am Defaults to true Specifies a list of patterns for files that you want includes No included Comma or space separated Specifies the name of a file each line in the file will includesfile No be used as an include pattern downloaded from lib ommolketab ir downloaded from lib ommotketab ir As mentioned the fileset element can contain include includesfile exclude and excludesfile elements and you can see the allowed attributes of these elements inTable 2 9 The fileset element can contain patternset and selector elements which you ll see later in this chapter Table 2 9 The include includesfile exclude and excludesfile type s attributes Attribute Description Required Default If If the corresponding property is true use this pattern No Pattern to include exclude for include and exclude types or the Name name of the file holding the patterns to include exclude for Yes includesfile and excludesfile types unless If the corresponding property is not set use this pattern No Some tasks form implicit file sets such as the javac task This means that a task supports all attributes of fileset see Table 2 8 You don t have to use a n
384. ublic class Project public void execute system out printin No worries Here s the build file lt ra Vere onH 1 0 eS lt project basedir default main gt lt property name sre value src gt lt property name output value output gt lt target name main depends jar gt downloaded from lib ommolketab ir getTaskName downloaded from lib ommolketab ir lt taskdef name project classname Project classpath Project jar gt lt project gt lt target gt lt target name compile gt Weis dir 0utput y gt lt javac srcdir src destdir S output gt lt target gt lt target name jJar depends compile gt lt jar destfile Project jar basedir output gt lt target gt lt pra ect When you execute this build file with the custom logger each task will be displayed as it s executed To attach the logger to the build use this command line sant logger ProjectLogger When the build runs you ll see each task logged like this sant logger ProjectLogger Buildfile build xml Running task property Running task property compile Running task mkdir mkdir Created dir C ant chl12 logger output Running task javac javac Compiling 1 source file to C ant ch12 logger output yeu Running task jar jar Building jar C ant ch12 logger Project jar main Running task taskdef Running task project project No worries
385. udes 7 bat J gt This example converts all txt files according to the convention of the host operating system and replaces tabs with spaces aTiseri sredir o erc tab remove Inc lucdes 7 CAG i gt As demonstrated by the previous example fixcrlf is good for removing or inserting tabs That s useful because some software e g Make is finicky about tabs The attributes of this task appear in Table 4 6 Table 4 6 The fixcrif task s attributes E Attribute Description nem Default Deprecated Use eol Specifies if you want to use defaultexcludes default excludes or not Set to No Default excludes are used yes no destDir Specifies where Jan want the No The value of srcDir modified files encoding pecities aye roang BENE No The default JVM encoding files you re working on Specifies how you want to handle DOS end of file Z characters Possible values are downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default add Makes sure an EOF character is at the end of the Tile The default is based on platform In aoe No Unix the default iS remove For Windows DOS systems the default ace IS asis Leaves EOF characters alone remove Removes any EOF character found at the end Specifies how you want to handle end of line EOL characters Possible values are asis Leaves EOL characters alo
386. ump are two other Ant automated build tools for use with Ant You can get Cruise C at http cruisecontrol sourceforge net It s an extensive build management tool but it takes some effc install To configure a build you work with amodification set Cruise Control supports an Ant task name modificationset that contains nested tasks you can use to configure your build After setting up the build as you want it you start the Cruise Control runner using sh and bat scripts depending on your operating system and Cruise Control takes it from there An alternative automated build tool is Gump You can get Gump from the J akarta CVS repository using password anoncvs Scevs d pserver anoncvs cvs apache org home cvspublic login Logging in to pserver anoncvs cvs apache org home cvspublic CVS Password Yrrere cvs d pserver anoncvs cvs apache org home cvspublic checkuot jakarta alexandria You can read all about Gump and how it works at http gump apache org Using Gump project definit are converted from XML to scripts native to the platform on which you are running These scripts execut or SVN update commands for every module which contains a project being built and then builds each o projects downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Chapter 5 Testing Builds with JUnit This chapter is about a crucial aspect of the build processtesting build results before deploying them It doesn t make s
387. upports a nested classpath element to set the classpath It Supports the vendor specific generic jonas and weblogic nested elements 8 8 2 1 The generic element This is the element you use for generic Java based deployment if you ve got deployment codea Java classsupplied by the server s vendor If there s a vendor specific element forserverdeploy use that of course but if not try the generic element The attributes of this element appear in Table 8 8 Table 8 8 The generic element s attributes Attribute Description Required classname Specifies the classname of the deployment tool you want to run Yes Specifies the classpath you want the JVM running the tool to use Depends on the classpath i May be supplied as a nested element server Depends on the password Specifies the password you want to use on the server Eaei Depends on the server Specifies the URL of the server to use server Depends on the username Specifies the username to log in with server The generic element supports nested arg and jvmarg elements Here s an example using the generic element for deployment that assumes the deployment tool for the target Web server is org steven jZee config Deploy downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt serverdeploy action deploy source S eardir app ear gt lt generic classname org steven j 2ee config Deploy classpath S classpath username S user name
388. urns a value returnTrue returns a boolean value of TRue return4 returns an integer value of 4 returnObject _ returns an Integer object containing a value of1 When you compile Project java and run it each of these methods are executed Now you can use the junit task to make sure that alterations to this application s code doesn t break the expected operation of these methods You can see the original build file that builds and deploys theProject java application in Example 5 2 Note the section where the J Unit tests will be added Break the build if those tests don t pass Example 5 2 Using J unit ch0O5 junit build xml lt xml version 1 0 gt lt project default main gt lt property name message value Building the lt property name testsOK value Tested OK lt property name srce location source gt lt property name output location gt lt property name results location results lt property name Jjars location jars gt lt property name dist location user gt lt property name junit fork value true gt lt target name main depends init compile lt echo gt message downloaded from lib ommolketab ir project gt m gt J gt test COMpress deploy gt downloaded from lib eommolketab ir lt echo gt lt target gt lt target name init gt lt mkdir dir output gt lt mkdir di rosults gt
389. use env elements see Table 7 3 to specify environment variables to pass to the forked JVM and nested permissions elements As with the javac taSk permissions represents a set of security permissions granted to the code in the JVM where Ant is running Since Ant 1 6 you can use nestedassertions elements to support Java 1 4 assertions 7 1 1 Handling Errors and Return Codes By default the return code of the java task is ignored If you want to check the return code you can set the resultproperty attribute to the name of a property and have the result code assigned to it For example say your code returned a non zero value public class Project i p nlic static void main String args SVySeem OCUuUL pErInLini you saidi T args 0 System exit 1 You can test the return code from a forked JVM and explicitly fail unless it so this way lt target name run gt lt java classname Project fork true resultproperty return code gt Cleasepeci gt lt pathelement location output gt lt classpath gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt arg value 0OK gt lt Jjava gt lt condition property problem gt lt not gt lt equals argl return code arg2 0 gt lt not gt lt condition gt lt fail if problem message Failed return code gt lt target gt Here s the result The java task indicates a nonzero return code and the build was termi
390. utes of this task appear in Table 7 5 Table 7 5 The parallel task s attributes Attribute Description Required Default onsen you want the task to fail if any nested task No pollinterval Polls tasks not implemented at this point No 1000 TOE ET Specifies the maximum numbers of threads you want 7 No use ieee ees eee Specifies the maximum number of threads you want to No use for each processor Requires JDK 1 4 or later Specifies a timeout in miiliseconds before the task timeout fails No Be careful when using this task as you would with any parallel task For example if you re compiling and two files have the same dependency you could have file access conflicts The parallel task supports a daemons nested element which is a list of tasks which are to be run in parallel daemon threads The parallel task will not wait for these tasks to complete Because they are daemon threads however they will not prevent Ant from completing the task The parallel task may be combined with the sequential task to define sequences of tasks to be executed on each thread inside the parallel task for an example usingparallel and sequential see the next topic downloaded from lib ommolketab ir downloaded from lib ommotketab ir 7 5 Setting Execution Order Like parallel sequential IS a container task which can contain other Ant tasks In this task the nested tasks are executed in sequence You use this tas
391. ved data TERE Specifies you want to only log errors instead of treating them as eia fatal n Specifies the password to use when connecting eme Pani sre Specifies the URL where the data you want is the URL where the data you want is username Specifies the username for BASIC http authentication al aam Specifies you want to download a file only after checking the usetimestamp timestamp of the local copy to ensure you don t overwrite a more No fals recent version Specifies you want to see full information as this task executes Set verbose No fals tO true false When the verbose option is on this task will display a dot for every 100 KB received downloaded from lib ommolketab ir downloaded from lib ommoltketab ir 8 7 Compiling JSPs When deploying to servers the jspc task can be useful This task runs the JavaServer Pages compiler and turns JSP pages into Java source which you can compile with thejavac task Compiling JSP pages supports fast invocation of JSP pages deployment on servers without the complete J DK o lets you check the syntax of pages without deploying them By default this task uses the Jasper J SP compiler which comes with Tomcat Copy Tomcat sjasper compiler jar and jasper runtime jar files into the Ant lib directory to use this task You ll needserviet jar which comes with Tomcat in the Ant lib directory For example say you have this JSP page greeting jsp lt HT
392. version option Visual Source Safe Microsoft 2nd vmiauncher attribute apply task downloaded from lib eommolketab ir downloaded from lib eommolketab ir exec task Vssadd task Vsscheckin task Vsscheckout task Vsscp task Vsscreate task vssget task Vsshistory task Vsslabel task downloaded from lib ommolketab ir downloaded from libeommolketab ir Index A B C D E F G H 1 Y K L M N O P Q R S CO U V W X Z waitfor task 2nd 3rd war task 2nd warfile attribute war task warn attribute xmlvalidate task watch command CVS watchers command CVS wav format web applications compiling JSPs creating CAB files 2nd creating WAR archives EJB containers and scp task and simple web deployment 2nd Tomcat servers and XDoclet and webdoclet task XDoclet 2nd webinc attribute jspc task webinf element war task weblogic element 2nd 3rd 4th Weblogic servers 2nd 3rd 4th 5th weblogic deploy deployment tool weblogicwebxml element webdoclet task websphere element 2nd webspherewebxml element webdoclet task webworkactiondocs element webdoclet task webworkactionsxml element webdoclet task webworkconfigproperties element webdoclet task webxml attribute ispc task war task whenempty attribute jar task zip task whichresource task wildcards 2nd Windows environment atcommand 2nd build process 2nd CVS servers end of line characters
393. ves Junit and Ant stack frames from error filtertrace No on stack traces Tork Specifies that you want to run tests in a new JVM No off ee Specifies you want to stop the build if there are No a errors downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default ee ee Specifies you want to stop the build if the test No pe fails E E E E ee Specifies you want to add the Ant classes and PE J Unit to the classpath in a forked J VM E Specifies the command used to start the Java Virtual Machine Ignored if fork is disabled see een Specifies the maximum amount of memory to give to the forked J VM Ignored if fork is Kea Specifies you don t want to copy the old newenvironment environment when new environment variables are No raise specified Ignored if fork is disabled Specifies you want statistics for each test case Possible values on off ANd withOutAndErr printsummary which is the same as on but also writes output of No the test as lial to System out and gt olen err Pa ere Specifies whether you want a neWclassloader to eae a be started for each test case Since Ant 1 6 Only the a Sends any output to Ant s logging system and to No formatters the formatters you specify receive the output ee Specifies where you want this task to place No The project s i temporary files Since Ant 1 6 base directory Specifies you want to stop a test if it
394. w Ant tasks handle task attributes access property values work with nested text and elements make builds fail work with filesets use custom tasks as wrappers for external programs and more downloaded from lib ommolketab ir downloaded from lib ommotketab ir Conventions Used in This Book There are some conventions I ll use that you should know about When there s a new piece of code under discussion it will appear highlighted when there s more code to come you ll see three dots Here s what that looks like import org apache tools ant Task import org apache tools ant BuildException public class Project extends Task private String language public void execute throws BuildException System out printin The language is language public void setLanguage String language this language language Note that I ll use the standard convention for selecting menu items in this book when menu items come into play as when we use Ant in the Eclipse IDE For instance to create a new project in Eclipse you use the File New Project menu item The following typographical conventions are used in this book Plain text Indicates menu titles menu options menu buttons and keyboard accelerators Italic Indicates new terms URLs email addresses filenames file extensions pathnames directories and Unix utilities downloaded from lib ommolketab ir downloaded from lib ommotketab ir
395. wo directories are scanneQNT_HoME lib and ant libin the Java user home directory You can place additional library files in this directory if you don t have access to ANT_HoME Ilib The location of the Java user home directory depends on your JVM settings In Unix it s usually your home directory so you d store additional Ant libraries in for example home username ant lib In Windows it s usually C Documents and Settings username SO you d store additional Ant libraries inC Documents and Settings username ant lib To determine where your J ava user home is use this element in a build file lt echo gt S user home lt echo gt downloaded from lib ommolketab ir downloaded from lib ommotketab ir Chapter 2 Using Properties and Types In Chapter 1 you learned about properties and tasks in Ant However long tables with short descriptions do not an Ant expert make In this chapter you begin to get the details on using Ant s extensive feature set which relies on two conerstones properties and types You received an introduction to them in the previous chapter but here s where to get a real working knowledge In the examples from last chapter building was a linear process you compiled some files you J ARred them up and then you were done In the real world things are almost never so straightforward You need to be able to check for specific files and perform different tasks depending on the existence of those files Yo
396. word let_me_in The build file is shown in Example 4 5 Before running the file supply the IP address of the server by changing the value of the server attribute from 000 000 000 000 to the IP address of your server or use the name of the server like ftp apache org Though you usually supply anaction attribute telling tp what to do the default action is to send files ction send SO you can omit action here Example 4 5 Using ftp ch04 ftp build xml lt xml version 1 0 gt lt project default main gt lt property name message value Deploying the jar file gt lt property name sre location source gt lt property name output location bin gt lt target name main depends init compile compress deploy gt lt echo gt S message lt echo gt lt target gt lt target name init gt lt mkdir diz Si outcpurc gt lt target gt lt target name compile gt lt javac srcdir S src destdir S output gt lt target gt lt target name compress gt downloaded from lib ommolketab ir downloaded from lib ommolketab ir lt jar destfile S output Project jar basedir output gt lt include name class gt include nane t2L 7 gt lt are lt target gt lt target name deploy gt lt ftp server 000 000 000 000 binary true verbose true userid S name password S password remotedir cgi bin gt lt fileset dir S output
397. x system lt chmod dir S dist perm ugotrx includes sh gt You can see the attributes for this task inTable 4 16 At present the chmod task only works in Unix and the NonStop Kernel Tandem Table 4 16 The chmod task s attributes Attribute Description Required Default eek Default Bese snide ieee Specifies if you want to use default No lades are excludes Set to yes no seed Specifies the directory holding the files to One of file dir or dir nested fileset list work on elements Specifies the patterns matching files to excludes exclude aS a comma or space separated No list downloaded from lib ommolketab ir downloaded from lib ommolketab ir Attribute Description Required Default One of file dir or Specifies the file or single directory where file DE nested fileset list you want permissions to be changed elements Specifies the patterns matching files to includes include as a comma or space separated No list Specifies limits on how many files to pass at once Set this attribute to 0 or negative _ maxparallel o i No unlimited values for unlimited parallelism Available in Ant 1 6 or later see Specifies the task should process multiple _ mT dpe using a single chmod command perm Specifies the new permissions you want measa oa ees ren j n specifies the target type Possible values No T file dir OF both Specifies whe
398. xecuted Specifies the file where standard error output LL POL Should be stored E Specifies the name of a property where you No want to store errors Specifies the command to execute without executable Yes any command line arguments ee ER Specifies the build should be stopped if the No n program doesn t start P E Specifies the build should be stopped if the No task encounters errors PE ack Specifies you want filenames to be passed with No esas forward slashes as directory separators Specifies the file where the task should take LNpUuL No input to run the class with E ceeinG Specifies a string holding the input stream for No the class to run ingen Specifies you want to send error output to No Ant s log Specifies the maximum number of source files to use at once Set to a value less than or maxparallel e f l No unlimited equal to O for unlimited parallelism Available since Ant 1 6 Specifies the directory in which files will be stored by the task dest Indicates you do not want to pass to the old newenvironment environment when new environment variables are specified No Specifies the operating systems in which the No executable can be run false Specifies the name of a file in which to store output N the output Specifies the name of a property in which you a want the output of the task to be placed g HEL downloaded from lib ommolketab ir downloaded from lib
399. y passed as a void setBasedir jJava lang String baseD a string for the project Specifies the default target of the project void setDefault java lang String defaultTarget l passed as a string void setDefaultInputStream java io InputStream Specifies the default System input stream defaultInputStream an InputStream object Specifies the project description in string void setDescription java lang String description format vO Oe See Oe E eee Bony Specifies a user property by name and valu java lang String value Specifies keep going mode In this mode void setKeepGoingMode boolean keepGoingMode all targets that don t depend on failed targets will be executed downloaded from lib ommolketab ir downloaded from lib ommotketab ir Method Does this void setName java lang String name Specifies the name of the project as a strin void setNewProperty java lang String name Specifies the new value of a property if no java lang String value value exists ifi reference to thi void setProjectReference java lang Object obj pec a a 7 erence to this Project end tt specified object void setProperty java lang String name i aa ee ne aS Specifies a property by name and value void setUserProperty java lang String name Specifies a user property by name and java lang String value value static 7ave lang String Translates a general path into its OS specif translatePath java
400. y project and its home page is athttp ant apache org Because it s an open source project it s always developing There are multiple authors called committers which can write to Ant s source code repositories However officially sanctioned Ant versions don t appear too rapidly and when they do they re usually backward compatible enough to make sure your build files aren t broken One notable exception to this practice is Ant 2 0 which may be out sometime in the next year or so When it does come out the Apache Ant team plans on releasing an automated migration tool that will translate 1 x build files to Ant 2 0 downloaded from lib ommolketab ir downloaded from lib ommoltketab ir Team LiB 1 2 Getting Ant Ant comes in two editions binary and source The binary release is ready to use just download uncompress and go The source release allows you to see what makes Ant run and to make modifications of your own if you choose To download either go tohttp ant apache org and click a link under the Download title either Binary Distributions or Source Distributions Downloading a binary edition is easiest J ust click the Binary Distributions link and download the tar gz or zip compressed file If you want bleeding edge Ant you can get the nightly builds from http cvs apache org builds ant nightly 1 2 1 Installing Ant To install the binary distribution of Ant expand it Here s the resulting dir
401. yes no used destfile Specifies the name of the TAR file you want to Yes create No Specifies the patterns matching files to excludes exclude as a comma or space separated list No files except default excludes are excluded Specifies the name of a file where each line is excludesfile No a pattern matching files to exclude Specifies the patterns matching files to All files are includes No include as a comma or space separated list included No a Specifies the name of a file where each line is a pattern matching files to include includesfile Specifies how you want to handle long file longfile paths more than 100 characters Possible No warn values are truncate fail warn omit and gnu Here s another example that uses the Ant gzip task after thetar task to create Project tar gz lt tar tarfile S dist Project tar basedir S output gt OZ10 ipiile fdisti Projectetar g2 sro gt 1cist pro jecl tar 7s This next example does the same thing except that it excludes files from thebeta directory and any todo html files lt tar tarfile S dist Project tar basedir S output downloaded from lib ommolketab ir downloaded from lib ommotketab ir excludes beta todo html gt G7p Ziptile S Gist l Proj ect tar g2 src sidist project tar gt The tar task Supports nested tarfileset elements These are specially extended FileSet types that Support all th
402. you can compress the output tar file to the Specified format For instance Example 4 1 compiles code and places the resulting Project class file in a tar gz file Project tar gz by setting the compression attribute to gzip Example 4 1 Tarring a file ch0O4 tar build xml lt xml version 1 0 gt lt project default main gt lt property name message value Building the tar gz file gt lt property name src location source gt lt property name output location bin gt lt target name main depends init compile compress gt lt echo gt message lt echo gt lt target gt lt target name init gt lt mkdir dir S output gt lt target gt lt target name compile gt lt javac srcdir S sre destdir S output gt lt targer gt lt target name compress gt lt Lar destfile S output Project tar gz basedir S output downloaded from lib ommolketab ir downloaded from lib ommotketab ir includes class compression gzip gt lt target gt lt pro ect gt The attributes of this task appear in Table 4 1 Table 4 1 The tar task s attributes Attribute Description Required Default bacedir Specifies the directory from which to get the No files to TAR l Sets the compression method if any Legal compression No values are none gzip and bzip2 detauitexciudes Specifies if you want to use default excludes No Default excludes are Set to
403. you want to allow the task to ignoreNoncriticalErrors continue despite some non fatal error false codes Required for the list action but eanan te otherwise depends Specifies a file to write output from the listin i 3 list action Bewer The same as the depends attribute same as the depends attribute sed es Specifies you want to use passive transfers oond Specifies the login password for the FTP 7 a ea port Specifies the port of the FTP server the port of the FTP server Specifies whether you want to give downloaded files the same modified time No false as the original files preservelastmodified downloaded from lib ommolketab ir downloaded from lib ommotketab ir Attribute Description Required Default ne Specifies a directory on the FTP server No you want to use Specifies the directory separator used on eee the target FTP server ne d server Specifies the address of the FTP server Yes skipFailedTransfers Specifies unsuccessful transfers Should No eee be skipped with a warning Specifies if to make this task calculate timediffauto the time difference between you and No server Available in Ant 1 6 or later Specifies the number of milliseconds eee between times on the target machine No compared to the local machine Available since Ant 1 6 em Specifies the default file permission a No only yee Specifies the login you want to use on yes th
Download Pdf Manuals
Related Search
Related Contents
USER MANUAL Plasma User Manual Construcción - Construnario.com 伊保処理場沈砂池電気設備工事 [273KB pdfファイル] KOHLER K-T16239-3-SN Installation Guide Untitled - Klarstein 安全データシート Apparatus for treating a stain in clothing 回 参 考文献 Samsung SV-DVD20 Керівництво користувача Copyright © All rights reserved.
Failed to retrieve file