Ant Step by Step
Ant Step by Step
Ant Step by Step
Page 1 of 22
Table of Contents
About the Author 1.0 2.0 Introduction Download, Install and Configure ANT 3 4 5
5
3.0
Build.xml a glance
6
6
9 11 18 20
20 20 21 21
7.1 Step 1: Create the java program as below 7.2 Step 2: Create build.xml 7.3 Step 3: System Verification 7.4 Step 4: Run the build.xml files
8.0
Appendices A: References
22
Page 2 of 22
Page 3 of 22
1.0 Introduction
This document guides you Step/Step to learn and create Ant scripts using Jakarta Ant technology. Ant script is the robust and most frequent used build technology in the real world. This guide will give you Step/Step process to learn Ant Scripts. The Ant script needs an xml file (default file name is build.xml) to execute. The xml files has all the information with specific formats which can be understand by the ANT system
Page 4 of 22
The latest Ant jar and files can be downloaded from http://ant.apache.org/bindownload.cgi site. You can download the binary format in .zip etc or you can also download the source code. For the new users it is highly recommended to download the binary files.
6. Click the OK button. 7. Set the PATH as below in your system (If you have a PATH variable exists in your system then append the ANT_HOME to it) set PATH=%PATH%;%ANT_HOME%\bin
Page 5 of 22
The build configuration file build.xml has the following main tags. A. Project a. Target i. Tasks
Page 6 of 22
System Properties Key java.version java.vendor java.vendor.url java.home java.vm.specification.version java.vm.specification.vendor java.vm.specification.name java.vm.version java.vm.vendor java.vm.name java.specification.version java.specification.vendor java.specification.name java.class.version java.class.path java.ext.dirs os.name os.arch os.version file.separator path.separator line.separator user.name user.home user.dir
Description Java Runtime Environment version Java Runtime Environment vendor Java vendor URL Java installation directory Java Virtual Machine specification version Java Virtual Machine specification vendor Java Virtual Machine specification name Java Virtual Machine implementation version Java Virtual Machine implementation vendor Java Virtual Machine implementation name Java Runtime Environment specification version Java Runtime Environment specification vendor Java Runtime Environment specification name Java class format version number Java class path Path of extension directory or directories Operating system name Operating system architecture Operating system version File separator ("/" on UNIX) Path separator (":" on UNIX) Line separator ("\n" on UNIX) User's account name User's home directory User's current working directory
Description the absolute path of the project's basedir (as set with the basedir attribute of <project>). the absolute path of the buildfile. the version of Ant the name of the project that is currently executing; it is set in the name attribute of <project>. the JVM version Ant detected; currently it can hold the values "1.2", "1.3", "1.4" and "1.5". home directory of Ant
ant.home
Page 7 of 22
Ant Build process Token Filters This is a very good functionality provided in Ant. When copying files to a destination folder, this filter will replace the token in the files with a specified value. For example we can set the filter as <filter token="version" value="5.0"/> <copy todir="${dest.dir}" filtering="true"> <fileset dir="src"/> </copy> The above code will copy all the files from the src.dir directory to the dest.dir directory replacing all the occurrences of the string @version@ with 5.0 in each file. Very cool feature hah. Path-like Structures The Ant has provision to set PATH and CLASSPATH type variables in the configuration file. We have different option like fileset, dirset, files, include and exclude options. We have to use : or ; to separate the arguments. Command-line Arguments We can pass variables from one task to another process or task. We have to use any one of the following attributes to pass command line arguments. We can give more than one command line arguments which have to be separated by ; or : Attribute value file path pathref line Description Single command line argument To specify a file as argument To specify a file as a normal string This is the reference to the a pathref somewhere in the build file space limited list of command line arguments.
The format is <arg value=-ls -lat/> References Any project element can be assigned an identifier using its id attribute. We can use reuse the element in any place by just referring the id. This will help to remove duplicate code in the configuration xml files. CLASSPATH or PATH is the best example for this <project ... > <path id="project.class.path"> <pathelement location="lib/"/> <pathelement path="/lib/tools.jar/"/> </path> <target ... > <compile ...> <classpath refid="project.class.path"/> </compile> </target> </project>
Page 8 of 22
If everything is set as per the installation process then running an Ant command is very simple. We have two options to run the ant script 1. Command line execution ant <options> <target1 target 2 target n> Options -help, -h -projecthelp, -p -version -diagnostics -quiet, -q -verbose, -v -debug, -d -emacs, -e -lib <path> -logfile <file> -l <file> -logger <classname> -listener <classname> -noinput -buildfile <file> -file <file> -f <file> -D<property>=<value> -keep-going, -k -propertyfile <name> -inputhandler <class> -find <file> -s <file> -noinput -nouserlib -noclasspath -noclasspath -main <class> Few examples ant this will look for a build.xml in the current folder and execute it. If there is no file as build.xml then it will fail.
Page 9 of 22
Descriptions print this message print project help information print the version information and exit Print information that might be helpful to diagnose or report problems. be extra quiet be extra verbose print debugging information produce logging information without adornments specifies a path to search for jars and classes use given file for log use given file for log the class which is to perform logging add an instance of class as a project listener do not allow interactive input use given buildfile use given buildfile use given buildfile use value for given property execute all targets that do not depend on failed target(s) load all properties from file with -D properties taking precedence the class which will handle input requests search for buildfile towards the root of the file system and use it A niceness value for the main thread: 1 (lowest) to 10 (highest); 5 is the default Run ant without using the jar files from /home/kev/.ant/lib Run ant without using CLASSPATH Java 1.5+ : use the OS proxies override Ant's normal entry point
Ant Build process ant buildfile config.xml This will execute the ant scripts on config.xml
2. Java execution java -Dant.home=<ant home physical folder> org.apache.tools.ant.launch.Launcher [options] [target]
Page 10 of 22
This is the important section to know for a better configuration management. We have tags associated to different tasks to use in our build file. Each task has its own functionality. Here I have mentioned most of the important tasks. You can see the complete list of tasks inside your installable. 1. Ant: This task is used to call an ant script inside an ant script. We can invoke another build process from the current process. We can <ant antfile="subproject/subbuild.xml" target="compile" inheritrefs="false" inheritAll="true"> <property name="file" value="data.properties"/> </ant> 2. AntCall: This task is used to call another target in the same build file. In the below example the targets compile and deploy are called form the main tags. Its not mandatory that these tags has to be called using antcall. It can be also controlled by depends attributes. <target name="main"> <antcall target="compile"> <param name="file" value="java"/> </antcall> <antcall target="deploy"> <param name="file" value="jar"/> </antcall> </target> 3. AntStructure: This task is used to create a DTD for your build file. <antstructure output=mydtd.dtd> 4. Apply: This task is used to execute system commands. We can execute any UNIX commands with parameters etc. The following task will list all the files excluding .txt files from /com/aots/learnant folder. <apply executable="ls"> <arg value="-lat"/> <fileset dir="/com/aots/learnant"> <patternset> <exclude name="**/*.txt"/> </patternset> </fileset> </apply> 5. BuildNumber: This task is to track the build number. This task will read the number from the given file and increment and write it back. The default file name is build.number. We can specific any file name using the property file. <buildnumber/> <buildnumber file="aotsbuild.number"/>
Page 11 of 22
Ant Build process 6. GUnzip/BUnzip2: This task is used to unzip and expand the tar files with gz and bz2 extensions. These files are expanded in the current folder. <gunzip src="com.aots.tar.gz" dest="test2.tar"/> <bunzip src="com.aots.tar.gbz2" dest="subdir"/> <gunzip dest="."> <url url="http://alphaomegatechsolutions.com/test.tar.gz"/> </gunzip> 7. BZip2: This task is used to zip the source files using GZip or BZAip2 algorithms. The source(src) and the destination (destfile or zipfiles) attributes are mandatory <gzip src="com.aots.test.tar" destfile="com.aots.test.tar.gz"/> <bzip2 src="com.aots.test.tar" destfile="com.aots.test.tar.bz2"/> <gzip destfile="com.aots.archive.tar.gz"> <url url="ttp://alphaomegatechsolutions.com/test.tar"/> </gzip> 8. Checksum: This task will generate checksum files using MD5 or SHA-1 algorithm. The same task can be used to verify the files checksum value. <checksum file="test.java" forceOverwrite="yes"/> <checksum file="test.java" verifyProperty="isMD5ok"/> 9. Chmod: This task is used to change the mode of any file. <chmod file="build.sh" perm="755"/> 10. Condition: This task is used to setup properties based on conditions. <condition property="isSunOSonSparc"> <os name="SunOS" arch="sparc"/> </condition> 11. Copy: Copy a file to a new file or to a new folder. <copy file="myfile.txt" tofile="mycopy.txt"/> 12. Copydir: Copy the whole directory tree from the source to the destination. <copydir src="${src}/resources" dest="${dist}" includes="**/*.java" excludes="**/Test.java" /> 13. Cvs: This tag is used to checkout files from CVS repository. We can get all the latest files in a specific folder before starting the build process. <cvs cvsRoot=":pserver:[email protected]:/home/cvspublic" package="aots" dest="${dest.dir}" /> 14. CvsChangeLog: This tag is used to get all the logs in the CVS repository in am xml format. <cvschangelog dir="dev/network" destfile="changelog.xml" daysinpast="10" />
Page 12 of 22
Ant Build process <cvschangelog dir="dve/network" destfile="changelog.xml" start="01 Jan 2007" end="01 Jan 2008" /> 15. CvsVersion: This task is used to get the CVS client and server version. <cvsversion cvsRoot=":pserver:[email protected]:/home/cvspublic" passfile="/home/myself/.cvspass" serverversionproperty="apachecvsversion" clientversionproperty="localcvsversion" /> 16. CVSPass: This task will add a new password entry in the CVS password file. <cvspass cvsRoot=":pserver:[email protected]:/home/cvspublic" password="aotspass" /> 17. Defaultexcludes: This task will update the default excludes for all the process below. We can both add and remove excludes <defaultexcludes echo="true" add="*.java" remove="*.txt"/> 18. Delete: This task is used to delete a file, folder and its entire sub directories. We can use these properties includes, includesfile, excludes, excludesfile or defaultexcludes to add or remove files from deleting. But all these tasks are depreciated and its recommended to use resource collections. <delete> <fileset dir="." includes="**/*.bak"/> </delete> 19. Diagnostics: This task used to run ant script in diagnostic mode <target name="diagnostics" description="diagnostics"> <diagnostics/> </target> 20. Dirname: This task is used to identify the directory of a specified file and store in a property variable. <dirname property="foo.dirname" file="foo.txt"/> 21. Ear: This task is used to create ear file for Enterprise Deployment. <ear destfile="build/myapp.ear" appxml="src/metadata/application.xml"> <fileset dir="build" includes="*.jar,*.war"/> </ear> 22. Echo: This task is used to echo message during the build process. We can write the message in the console or to a specified file. We have options to setup the level of logging as error, warning, info, verbose and debug. <echo file="aots.lgo" level="error"> build filed!!!!!!!!!!!!!!!! </echo> <echo message="Hello AOTS"/> 23. Exec: This task it used to execute a system command like exec or cmd etc The following example set the PATH variable <property environment="env"/> <exec ... >
Page 13 of 22
Ant Build process <env key="PATH" path="/user/bin"/> </exec> The following example will open the index.html in IE <property name="browser" location="C:/Program Files/Internet Explorer/iexplore.exe"/> <property name="file" location="aots/main/index.html"/> <exec executable="${browser}" spawn="true"> <arg value="${file}"/> </exec> 24. Fail: This task will exit the current build with an error message. We can also add in or unless properties in the fail task. <fail message="Build filed"/> 25. GenKey: This task is used to create a keystore for the encryption process. <genkey alias="aots" storepass="AOTSPASS" dname="CN=AOTS, O=alphaomegatechsolutions.com, C=IN"/> 26. Get: This task is used to get a file from a specified URL <get src="http://www.alphaomegatechsolutions.com/" dest="temp/index.htm"/> 27. Import: This task is used to import another build file into the current file. The optional will decide whether to stop the build if the file is not available. <import file="../build-common.xml" optional=true/> 28. Input: This task is used to create user interaction during the build process. <input message="Do you want to delete all class and recompile your Java files (Y/N)?" validargs="Y,N" addproperty="delete.classes" /> <condition property="deleteclasses"> <equals arg1="N" arg2="${delete.classes}"/> </condition> <delete if="deleteclasses" file="lib/class/*.class"/> 29. Jar: This task is used to create jar file from a specific folder. The includes or excludes properties can be used to add or prevent few files adding in the jar file <jar destfile="${dist}/lib/aots.jar" basedir="${build}/classes" includes="com/aots/**" excludes="**/Demo.class" /> 30. Java: This task is used to execute a java class during the execution of the ant script. We can use all the properties used in the java command. <java classname=com.aots.test> <java jar=aots.jar> 31. Javac: This task is used to compile java files in the build process <javac srcdir="${src}" destdir="${build}" classpath="aots.jar" includes="com/aots/**" excludes="**/Demo.class" debug="on" source="1.4" />
Page 14 of 22
OU=Training,
Ant Build process 32. Javadoc/Javadoc2: This task is used to create java documentation for the java classes. 33. Length: This task is used to find the length of a file or a string. <length string="alphaomegatechsolutions" property="length" /> <length file="aots.txt" property="length" /> 34. LoadFile: This task is used to load a file in the build process. <loadfile property="message" srcFile="message.txt"/> 35. LoadProperties: This task is used to load the contents of the properties file as ant properties. The properties should be as key=value format <loadproperties srcFile="file.properties"/> 36. LoadResource: This task will load a text resource to a single property. <loadresource property="homepage"> <url url="http://alphaomegatechsolutions.com/index.htm"/> </loadresource> 37. MakeURL: This task is used to convert a file name to a URL. <makeurl file="*.java" property="java.url"/> 38. Mail: This task is used to send mail using SMTP. <mail mailhost="smtp.alphaomegatechsolutions.com" mailport="1076" subject="Test Mail.."> <from address="[email protected]"/> <replyto address="[email protected]"/> <to address="[email protected]"/> <message>The is the current build. Test the application once you get this mail.</message> <attachments> <fileset dir="dist"> <include name="**/*.jar"/> </fileset> </attachments> </mail> 39. Manifest: This task is used to create a manifest file. <manifest file="MANIFEST.MF"> <attribute name="Built-By" value="kev"/> <section name="common"> <attribute name="Specification-Title" value="Example"/> <attribute name="Specification-Version" value="1.1"/> <attribute name="Specification-Vendor" value="AOTS"/> <attribute name="Implementation-Title" value="common"/> <attribute name="Implementation-Version" value="1.1 January 01 2009"/> <attribute name="Implementation-Vendor" value="AOTS CORP"/> </section> <section name="com/aots/Demo.class"> <attribute name="Sealed" value="false"/> </section> </manifest> 40. ManifestClassPath: This task will convert the path to a value for Manifest file. 41. Mkdir: This task is used to create a new folder <mkdir dir="build"/> 42. Move: This task is used to move a file to a new file or to a folder <move file="a.txt" tofile="b.txt"/> - this can be also used for renaming the file.
Page 15 of 22
<move file="a.txt" todir="new/dir"/> 43. Nice: This task is used to set the thread priority to the current process. <nice newpriority="10"/> 44. Parallel: This task is used to execute parallel process. 45. PreSetDef: This task is used to create preset definitions and can be used later by calling the name. This can be used like a function in java. <presetref name=createjar> <jar destfile="${dist}/lib/aots.jar" basedir="${build}/classes" includes="com/aots/**" excludes="**/Demo.class" /> </presetdef> Later it can use just by calling the name </createjar> 46. Replace: This task is same as the filter task which replaces a token with a specified value. 47. ResourceCount: This task is used to find the number of files in a file list. <resourcecount property="counter"> <filelist dir="." files="*.java" /> </resourcecount> 48. Retry: This task is used to repeat a step few time if it fails. <retry retrycount="3"> <get src="aots.jar" dest="/com/build/aots.jar" /> </retry> 49. Rmic: This task is used to execute the rmic task in ant build. We can use includes or excludes properties. The property base is the destination folder for the class files. <rmic classname="com.xyz.FooBar" base="${build}/classes"/> 50. SignJar: This task is used to sign the jar file. <signjar jar="aots.jar" alias="aots" storepass="aotspass"/> 51. Sleep: This task is used to sleep the build process for a while. We can use milliseconds, seconds and hours also. <sleep milliseconds="10"/> 52. Sql: This task is used to execute SQL commands using Java JDBC connectivity. <sql driver="jdbc driver name" url="jdbc url" userid="ui" password="pass" > insert insert into aots_users values (1, "aots1"); </sql>
Page 16 of 22
Ant Build process 53. Sync: This task is used to synchronize two folders. This file will overwrite the data and also it will remove the files from the todir folder. <sync todir="Server"> <fileset dir="local"/> </sync> 54. Tar: This task is used to create a tar file from the basedir folder <tar destfile="${dist}/manual.tar" basedir="htdocs/manual"/> 55. Tempfile: This task is used to create a temp file in the build process. <tempfile property="temp.file" suffix=".xml"/> 56. Touch: This task is used to update the last modified date of a file. <touch file="test.txt" datetime="01/01/2008 12:00 am"/> 57. Truncate: This task is used to set the maximum length or size of a file. We can set from 0 byte, KB, MB, GB, TB(TerraBytes) and PB (Petabytes) <truncate file="foo" length="1K" /> 58. Unjar: This task is to un-jar the given tar file. <unzip src="aots.zip" dest="com/aots/"/> 59. Untar: This task is to un-tar the given tar file. 60. Unwar: This task is to un-war the given tar file. 61. Unzip: This task is to unzip the given tar file. 62. War: This task is used to create a war file. 63. Zip: This task is used to create a zip file. A zipfileset property is used to create a zip with multiple zip files.
Page 17 of 22
Ant Build process 12. Scp: This task is used to copy a file to or from a remote server. <scp file="myfile.txt" todir="userid:password@hostname:/home/data"/> 13. Sound: This task is used to create sound during the build process for specific tasks. <sound> <success source="sound.wav"/> </sound> 14. Splash: This task is used to create a splash image during the build process <splash imageurl="aotslogo.gif" useproxy="true" showduration="5000"/> 15. Sshexec: This task is used to run a command in the remote server. <sshexec host="hostname" username="uid" password="pass" command="ls -lat"/> 16. Telnet: This task is used to get a telnet session in the build process. <telnet userid="uid" password="pass" server="aots"> <read>/home/test</read> <write>ls</write> <read string="/home/test"/> </telnet> 17. WebLogic JSP Compiler: This task is used to compile a JSP with WebLogic JSP compiler <wljspc src="source" dest="dest" package="aots.jsp"> <classpath> <pathelement location="${weblogic.classpath}"/> <pathelement path="${compile.dest}"/> </classpath> </wljspc>
Page 19 of 22
7.0 An example
The first step is to create the application code. For this sample process we can write the famous Hello World program. In the following example we are going to do the following process using Ant script a) Verify whether the java file is available to proceed. b) Compile the java file and convert it to class file c) Bundle it to a jar file.
Ant Build process </echo> </target> <!-- File Verification Task --> <target name="file.check"> <condition property="file.run"> <and> <available file="src/com/aots/learn/HelloWorld.java"/> </and> </condition> </target> <!-- Java Compilation Task--> <target name="compile" description="Compilation target" depends="file.check" if="file.run"> <echo>Java File is available. Start the process...</echo> <javac srcdir="src/com/aots/learn"/> </target> <!-- Jar Bundling Task--> <target name="compress" description="Compression target" depends="compile"> <jar jarfile="Project.jar" basedir="src/com/aots/learn" includes="*.class" /> </target> </project>
Page 21 of 22
Page 22 of 22