You are on page 1of 25

Apache Ant - Building Simple Java Projects

Build and Test tools Java Build Tools These tools help the programmer to build their project efficiently. Build process is repetitive process where programmer builds the project again and again to test the changes in the project code. While developing a project code changes needs to be test and the testing requires the build of the code and finally deploying on the server for testing. Build tools automate the repetitive process and allows the programmer to concentrate on the project development. It also reduces the overall build time. Build tools makes the build process just a single click work. List of build Java build and Test Tools DBUNIT,ANT,Maven,JUNIT,JMeter Apache Ant - Building Simple Java Projects About the Tutorial Apache's Ant technology, which is a mean to build java projects. Ant is an open source tool that is easy to use and platform independent. Ant Definition Apache Ant is an open source, cross-platform based build tool that is used to describe a build process and its dependencies and implemented in XML scripts using Java classes that ensures its extensibility to any development environment (based on Java) and its integrity with other build tools. Why Ant? Ant is developed by Apache Foundation specifically to build projects based on java platform. But why to use Ant if there already exists other build tools like make, jam and many. Tool like MAKE uses shell commands that facilitates integration of other tools to extend its functionality on the operating system where it runs. The use of shell commands in make brings about the integrity with other languages too .But this limits the functionality of the build tool specific to that OS only, e.g., MAKE is specific to the UNIX platform. Ant has overcome this shortcoming as it uses java classes with XML scripting that makes it portable through cross-platform behavior. Ant is applicable to any integrated development environment based on java technology and therefore easy to use in building java projects across any platform. Ant enables automatic generation of build processes that is more reliable than manual procedures. Ant can also compile source code from version controls and package the compiled code and other resources (JAR, EAR, TAR etc.). History of Ant The development of Ant technology originated as an integral component of Tomcat application server based on Java Servlet and Java Server Faces. Its first independent release as a Jakarta subproject was made in the year 2000. Since then, Ant has been used as a major tool in building java projects and now it has become a top-level Apache project for server-side solutions. The latest release of Ant is version apache-ant-1.8.2. Introduction to Apache Ant (Another Neat Tool) Ant is an open source build technology developed by Apache intended to build processes in Java environment. Ant is based on XML and uses java classes in automatic generation of build processes that makes it platform independent. It is applicable to any integrated development environment (IDE) that uses java. A build file is generally named as build.xml. The best features of the Ant technology can be summarized as below Easy to Use: It is not a programming language, it is an XML based scripting tool, therefore easy to understand and implement. Portable and Cross-platform based: Uses of Java classes makes it portable, i.e., it can be run on any operating system. Extended Functionality: Ant is based on java its functionality can be extended to any development environment based on java. It is easier to implement than any specific IDE because it is automated and ubiquitous. Build Automation: Ant provides automated build processes that is faster and more efficient than manual procedures and other build tools can also be integrated with it. Compilation of Source Code: Ant can use and compile source code from a variety of version controls and packaging of the compiled code and resources can also be done.

Handling Dependencies between Targets: An Ant Project describes the target and tasks associated with it and also handles dependencies between various targets and tasks.

Installation In this section, you will learn how to install Ant into your system. The current version 1.8.2 of Ant was released on 27 June, 2008. It is available for download at http://ant.apache.org/bindownload.cgi. Here, you have to click on the link apache-ant-1.8.2-bin.zip in the .zip archive to download the zip file. Under Environment variables, Set the path value I:\apache-ant-1.8.2 to ANT_HOME variable and the path value I:\apache-ant-1.8.2\lib; to CLASS_PATH variable. Again in the System Variables, we have to set the value C:\jdk to JAVA_HOME variable and the value I:\apache-ant-1.8.2\bin; to Path variable. checking the installation process: To do this, open the Command Prompt and run the command C:\>ant. If the following message

appears, then it indicates that your installation is successful; Ant is properly installed in your system..

How to generate build.xml file This example shows how to generate the build.xml file. build.xml file is the backbone of ANT (Another Neat Tool) technology. Each build.xml file contains only one project name and at least one target. T HE PROJECT TAG HAS ONLY THREE ATTRIBUTES : <project name="My Project" default="compile" basedir="."> Attribute Description name project name default target name which called by default basedir the base directory having all path, it contain absolute path

Requirement not necessary not necessary not necessary

The project tag is used to create our project and its attributes are used to handle further processing of the project. The name attribute is used to specify the project name and the default attribute is used to specify which target will be called as default when the program will run. The basedir attribute is used to calculate the absolute path of the parent directory. T ARGET TAG HAS ONLY FIVE ATTRIBUTES: <target name="buildWar" depends="init" description="build a war file"/> <target name="init" if="build"/> <target name="init" unless="build"/> Attribute name depends if unless description Description target name depends on another target the name of the property that must be set in order for this target to execute. the name of the property that must not be set in order for this target to execute. short description about target Requirement necessary not necessary not necessary not necessary not necessary

In the target tag, name attribute is used for target name. The depends attribute is used to give sequence of target, i.e., which target will execute first, one target may depend on one or more other targets. The if attribute is used in case of condition, whether property exists or not; then this target will be executed. The Unless attribute is used as like else condition whether property does not exist, the target will not be executed. The description attribute is used for only giving details about target. P ROPERTY TAG HAS ONLY FOUR ATTRIBUTES: <property name="build" value="${build}"/> <property name="src" location="src"/> <property file="build.properties"/> Attribute Description

Requirement

name value location file

name of the property, which is case-sensitive name of task attribute, this is done by placing the property name between "${"name }" in the attribute value it contain property name name of the property file

not necessary necessary not necessary not necessary

In the property tag, name attribute is used for property name; it is case sensitive. The value tag is used to give the task which will be the name of property in this format "${name}", and the location tag is used to specify the location of task where it performs and the file tag is used to import all properties of ant file. The complete build.xml file structure is as follows: <project name="My Project" default="jar" basedir="."> <property name="dir.src" value="src"/> <property name="dir.build" value="build"/> <property name="dir.dest" value="dest"/> <target name="clean" description="Removing the all generated files."> <delete dir="${dir.build}"/> <delete dir="${dir.dest}"/> </target> <target name="prepare" depends="clean"> <mkdir dir="${dir.build}"/> <mkdir dir="${dir.dest}"/> <mkdir dir="${dir.src}"/> </target> <target name="compile" depends="prepare" description="Compilation of all source code."> <javac srcdir="${dir.src}" destdir="${dir.build}"/> </target> <target name="jar" depends="compile" description="Generates Roseindia.jar file in to the 'dest' directory."> <jar jarfile="${dir.dest}/roseindia.jar" basedir="${dir.build}"/> </target> </project> The above build.xml file is used to create directory, compile source code, create jar file and clean the directory if already exists. To check the program, simply copy and paste the above code and give appropriate path; then run with ant command on the command prompt. The output is as follows:

The output shows that a jar file named roseindia.jar is created but in this jar file only manifest file is created. When you make a java file in the src folder and run with ant command, the jar file is created completely. class Hello { public static void main(String args[]) { System.out.println("sandeep kumar suman"); } } To check your program, compile it with ant command on the console; then the following output will be displayed:

`````` Ant built-in Properties: This is a simple example that illustrates how to find the basedir name, file name, project name, ant version, java version, operating system name, ant home directory name, java home directory name, user home directory name and user name. Ant provides you with certain built-in properties that you may find useful during your build process. Ant's built-in properties: Property ant.file ant.project.name ant.home ant.version ant.java.version basedir os.name java.home user.home user.name Source code of build.xml: <?xml version="1.0"?> <project name="AntProperties" default="echo" basedir="."> <target name="echo"> <echo message="The operating system is: ${os.name}"/> <!-- absolute path of the project. --> <echo message="The home path is: ${basedir}"/> <!-- absolute path of the build file. --> <echo message="The file name is: ${ant.file}"/> <!-- root directory of ant. --> <echo message="The Project name is: ${ant.project.name}"/> <echo message="The Ant home directory is: ${ant.home}"/> <echo message="The Ant version is: ${ant.version}"/> <echo message="The Java version is: ${ant.java.version}"/> <!-- System properties. --> <echo message="The Java home directory is: ${java.home}"/> <echo message="The User home directory is: ${user.home}"/> <echo message="The User name is: ${user.name}"/> </target>

Description The absolute path of the build file The name of the project as set in the <project> element's name attribute. The root directory of ant The version of this ant installation. This is not just the version number and includes information such as the compilation date. The version of the java that ant uses The absolute path of the project Operating system name Java home directory name User directory name User name

</project> Run this program - the following output will be displayed:

Using Ant to execute class file : This build.xml file is used to compile and run the java file and print the value on command prompt. Here we are using five targets: The "clean" target deletes any previous "build", "classes" and "jar" directory; second one is used to create all necessary directories and it depends on <target name="clean">; third one is used to compile the java file from "src" directory to transform source files in to object files in the appropriate location in the build directory and it depends on <target name="prepare">; fourth one is used to create the jar file and it depends on <target name="compile">, it means that after completion of compile target, it will be executed; fifth one is used to run the jar file and it depends on <target name="jar"> and finally <target name="main"> is used to specify the default project name, it means that when the program will be run, it will be called first and it depends on <target name="run">. <?xml version="1.0"?> <project name="Roseindia" default="main" basedir="."> <property name="src.dir" value="src"/> <property name="build.dir" value="build"/> <property name="classes.dir" value="${build.dir}/classes"/> <property name="jar.dir" value="${build.dir}/jar"/> <property name="main-class" value="Roseindia"/> <target name="clean"> <delete dir="${classes.dir}"/> <delete dir="${jar.dir}"/> <delete dir="${build.dir}"/> </target> <target name="prepare" depends="clean"> <mkdir dir="${build.dir}"/> <mkdir dir="${classes.dir}"/> <mkdir dir="${jar.dir}"/> <mkdir dir="${src.dir}"/> </target> <target name="compile" depends="prepare"> <javac srcdir="${src.dir}" destdir="${classes.dir}"/> </target> <target name="jar" depends="compile"> <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}"> <manifest> <attribute name="Main-Class" value="${main-class}"/> </manifest> </jar> </target>

<target name="run" depends="jar"> <java jar="${jar.dir}/${ant.project.name}.jar" fork="true"/> </target> <target name="main" depends="run"> <echo message="main target completed.." /> </target> </project> If you run this build.xml file using ant command, then the following output will be displayed.

In this output display, the class name Roseindia is not found by the compiler. Create a java file as shown below and put it in the src directory, and again run it with ant command. The following output will be displayed. class Roseindia { public static void main(String args[]) { System.out.println("Roseindia Technology Pvt. Ltd."); } }

Executes a Java class within the Ant VM: This example illustrates how to call class file through build.xml file. The build.xml file is used to compile and run the java file and print the calculated value on command prompt. Here we are using only four targets: "clean" target deletes any previous "build" directory; second one is used to create "build" and "src" directories which depend on <target name="clean">, after execution of the clean target, this target will be executed; third one is used to compile the java file from "src" directory, it transforms source files in to object files in the appropriate location in the build directory and it depends on <target name="prepare">; forth one is used to run the class file and it depends on <target name="compile">.

The debug keyword is used to find the error and optimize is used to find resources of source and destination directory. In the target run, fork="true" is used to display output and failonerror is used to display error report. <?xml version="1.0"?> <project name="add" default="run" basedir="."> <target name="clean"> <delete dir="build"/> </target> <target name="prepare" depends="clean"> <mkdir dir="src"/> <mkdir dir="build"/> </target> <target name="compile" depends="prepare"> <javac srcdir="src" destdir="build" debug="on" optimize="on"/> </target> <target name="run" depends="compile"> <java fork="true" failonerror="yes" classname="Addition" classpath="build"> <arg line=""/> </java> </target> </project> Simply copy and paste the following source code in the src directory and then run with ant command. The following output will be displayed: class Addition{ public static void main(String[] args) { int a=5; int b=10; int add = a + b; System.out.println("Addition = " + add); } }

Ant Script to Create Mysql Table : This example illustrates how to create table through the build.xml file by simply running the ant command. In this build.xml file, we are using 4 property elements for connectivity of database. The first property <property name="sql.driver"> is used to connect the sql driver. The second property <property name="sql.url"> is used to define the database url and database name. The third property <property name="sql.user"> is used to define user name of the database. The fourth property <property name="sql.pass"> is used to define the password name of the database.

In this build.xml file, only one target <target name="createTables"> is used to execute the query which is in the client.sql and project.sql file. The source code of the build.xml file is as follows: <project name="MysqlCreateTable" basedir="." default="createTables"> <property name="sql.driver" value="org.gjt.mm.mysql.Driver"/> <property name="sql.url" value="jdbc:mysql://192.168.10.211/test"/> <property name="sql.user" value="sandeep"/> <property name="sql.pass" value="sandeep"/> <target name="createTables"> <sql driver="${sql.driver}" url="${sql.url}" userid="${sql.user}" password="${sql.pass}" > <transaction src="client.sql"/> <transaction src="project.sql"/> </sql> </target> </project> client.sql create table client ( client_id int not null auto_increment primary key, client_name text not null ); project.sql create table project ( project_id int not null auto_increment primary key, project_name text not null ); Create the both client.sql and project.sql files with the build.xml file and simply run the build.xml file with ant command in the appropriate path on command prompt. If the program executes successfully, then the following output will be displayed.

Ant Script to Insert Data in Mysql Table This example illustrates how to insert data in table through the build.xml file by simply running the ant command. In this build.xml file, we are using 4 property elements for connectivity from database. The first element <property name="sql.driver"> is used to connect from the sql driver. The second element <property name="sql.url"> is used to define the database url and database name. The third element <property name="sql.user"> is used to define user name of the database. The fourth element <property name="sql.pass"> is used to define the password name of the database. In this build.xml file, <target name="createTables"> is used to execute the query which is in the client.sql and project.sql file and <target name"insertData"> is used to execute the query which is in the insertclient.sql and insertproject.sql file. The source code of the build.xml file is as follows: <project name="MysqlCreateTableAndInsertData" basedir="." default="insertData"> <property name="sql.driver" value="org.gjt.mm.mysql.Driver"/> <property name="sql.url" value="jdbc:mysql://192.168.10.211/test"/> <property name="sql.user" value="sandeep"/>

<property name="sql.pass" value="sandeep"/> <target name="createTables" > <sql driver="${sql.driver}" url="${sql.url}" userid="${sql.user}" password="${sql.pass}" > <transaction src="client.sql"/> <transaction src="project.sql"/> </sql> </target> <target name="insertData" depends="createTables"> <sql driver="${sql.driver}" url="${sql.url}" userid="${sql.user}" password="${sql.pass}" > <transaction src="insertclient.sql"/> <transaction src="insertproject.sql"/> </sql> </target> </project> client.sql create table client ( client_id int not null auto_increment primary key, client_name text not null ); project.sql create table project ( project_id int not null auto_increment primary key, project_name text not null ); insertclient.sql INSERT INTO client (client_name) VALUES ("Galanthus nivalis"); INSERT INTO client (client_name) VALUES ("Narcissus pseudonarcissus"); INSERT INTO client (client_name) VALUES ("Narcissus poeticus var. recurvus"); INSERT INTO client (client_name) VALUES ("Leucojum vernum"); INSERT INTO client (client_name) VALUES ("Iris pseudacorus"); INSERT INTO client (client_name) VALUES ("Crocus tommasinianus"); INSERT INTO client (client_name) VALUES ("Colchicum autumnale"); INSERT INTO client (client_name) VALUES ("Hyacinthoides non-scripta"); INSERT INTO client (client_name) VALUES ("Erythronium dens-canis"); INSERT INTO client (client_name) VALUES ("Fritillaria meleagris"); INSERT INTO client (client_name) VALUES ("Cyclamen coum"); INSERT INTO client (client_name) VALUES ("Tulipa turkestanica"); INSERT INTO client (client_name) VALUES ("Ranunculus ficaria"); insertproject.sql INSERT INTO project (project_name) VALUES ("codingdiary.com"); INSERT INTO project (project_name) VALUES ("roseindia.net"); INSERT INTO project (project_name) VALUES ("allcooljobs.com"); INSERT INTO project (project_name) VALUES ("huntarticles.com"); INSERT INTO project (project_name) VALUES ("onlinefreetrading.com"); INSERT INTO project (project_name) VALUES ("allcoolloans.com"); INSERT INTO project (project_name) VALUES ("newstrackindia.com"); INSERT INTO project (project_name) VALUES ("artsandlitreture.com"); INSERT INTO project (project_name) VALUES ("javajazzup.com"); INSERT INTO project (project_name) VALUES ("whitecollers.com"); INSERT INTO project (project_name) VALUES ("singlepane.com"); INSERT INTO project (project_name) VALUES ("ilikeyoutube.com"); INSERT INTO project (project_name) VALUES ("fake.com");

Create the all client.sql, project.sql, insertclient.sql, insertproject.sql files parallel of the build.xml file and simply run the build.xml file with ant command in the appropriate path on command prompt. If the program executes successfully, then the following output will be displayed.

Ant Script to Update Mysql Table:This example illustrates how to insert and update data in table through the build.xml file by simply running the ant command. In this build.xml file, we are using 4 property elements for connectivity from database. The first property <property name="sql.driver"> is used to connect from the sql driver. The second property <property name="sql.url"> is used to define the database url and database name. The third property <property name="sql.user"> is used to define user name of the database. The fourth property <property name="sql.pass"> is used to define the password name of the database.

In this build.xml file, <target name="createTables"> is used to execute the query which is in the client.sql and project.sql file and <target name"insertData"> is used to execute the query which is in the insertclient.sql and insertproject.sql file and <target name="updateTable"> is used to execute the query of updateclient.sql and updateproject.sql file. The source code of the build.xml file is as follows: <project name="MysqlCreateTableAndInsertData" basedir="." default="updateTable"> <property name="sql.driver" value="org.gjt.mm.mysql.Driver"/> <property name="sql.url" value="jdbc:mysql://192.168.10.211/test"/> <property name="sql.user" value="sandeep"/> <property name="sql.pass" value="sandeep"/> <target name="createTables" > <sql driver="${sql.driver}" url="${sql.url}" userid="${sql.user}" password="${sql.pass}" > <transaction src="client.sql"/> <transaction src="project.sql"/> </sql> </target> <target name="insertData" depends="createTables"> <sql driver="${sql.driver}" url="${sql.url}" userid="${sql.user}" password="${sql.pass}" > <transaction src="insertclient.sql"/> <transaction src="insertproject.sql"/> </sql> </target> <target name="updateTable" depends="insertData"> <sql driver="${sql.driver}" url="${sql.url}" userid="${sql.user}" password="${sql.pass}" > <transaction src="updateclient.sql"/> <transaction src="updateproject.sql"/> </sql> </target> </project>

client.sql create table client ( client_id int not null auto_increment primary key, client_name text not null ); project.sql create table project ( project_id int not null auto_increment primary key, project_name text not null ); insertclient.sql INSERT INTO client (client_name) VALUES ("Galanthus nivalis"); INSERT INTO client (client_name) VALUES ("Narcissus pseudonarcissus"); INSERT INTO client (client_name) VALUES ("Narcissus poeticus var. recurvus"); INSERT INTO client (client_name) VALUES ("Leucojum vernum"); INSERT INTO client (client_name) VALUES ("Iris pseudacorus"); INSERT INTO client (client_name) VALUES ("Crocus tommasinianus"); INSERT INTO client (client_name) VALUES ("Colchicum autumnale"); INSERT INTO client (client_name) VALUES ("Hyacinthoides non-scripta"); INSERT INTO client (client_name) VALUES ("Erythronium dens-canis"); INSERT INTO client (client_name) VALUES ("Fritillaria meleagris"); INSERT INTO client (client_name) VALUES ("Cyclamen coum"); INSERT INTO client (client_name) VALUES ("Tulipa turkestanica"); INSERT INTO client (client_name) VALUES ("Ranunculus ficaria"); insertproject.sql INSERT INTO project (project_name) VALUES ("codingdiary.com"); INSERT INTO project (project_name) VALUES ("roseindia.net"); INSERT INTO project (project_name) VALUES ("allcooljobs.com"); INSERT INTO project (project_name) VALUES ("huntarticles.com"); INSERT INTO project (project_name) VALUES ("onlinefreetrading.com"); INSERT INTO project (project_name) VALUES ("allcoolloans.com"); INSERT INTO project (project_name) VALUES ("newstrackindia.com"); INSERT INTO project (project_name) VALUES ("artsandlitreture.com"); INSERT INTO project (project_name) VALUES ("javajazzup.com"); INSERT INTO project (project_name) VALUES ("whitecollers.com"); INSERT INTO project (project_name) VALUES ("singlepane.com"); INSERT INTO project (project_name) VALUES ("ilikeyoutube.com"); INSERT INTO project (project_name) VALUES ("fake.com"); updateclient.sql UPDATE client SET client_name = "Mr. Dormet" WHERE client_id = "13"; updateproject.sql UPDATE project SET project_name = "onedatingtips.com" WHERE project_id = "13"; Create the all client.sql, project.sql, insertclient.sql, insertproject.sql, updateclient.sql, updateproject.sql files parallel of the build.xml file and simply run the build.xml file with ant command in the appropriate path on command prompt. If the program executes successfully, then the following output will be displayed.

Using Ant Build Scripts to Drop Mysql Table:This example illustrates how to drop table through the build.xml file by simply running the ant command. In this build.xml file, we are using 4 property elements for connectivity of database. The first property <property name="sql.driver"> is used to connect the sql driver. The second property <property name="sql.url"> is used to define the database url and database name. The third property <property name="sql.user"> is used to define user name of the database. The fourth property <property name="sql.pass"> is used to define the password name of the database.

In this build.xml file, <target name="createTables"> is used to execute the query which is in the client.sql and project.sql file and <target name"dropTables"> is used to execute the query which is in the deleteclient.sql and deleteproject.sql file. In the target <target name="dropTable">, a condition is used - whether the user wants to delete the file or not. If the user gives input 'n', then the table can't be deleted but if the user give input 'y', then the table will be completely deleted. The source code of the build.xml file is as follows: <project name="MysqlCreateTable" basedir="." default="dropTables"> <property name="sql.driver" value="org.gjt.mm.mysql.Driver"/> <property name="sql.url" value="jdbc:mysql://192.168.10.211/test"/> <property name="sql.user" value="sandeep"/> <property name="sql.pass" value="sandeep"/> <target name="createTables" > <sql driver="${sql.driver}" url="${sql.url}" userid="${sql.user}" password="${sql.pass}" > <transaction src="client.sql"/> <transaction src="project.sql"/> </sql> </target> <target name="dropTables" depends="createTables"> <input message="Are you sure to delete the table?" validargs="y,n" addproperty="do.delete" /> <condition property="do.abort"> <equals arg1="n" arg2="${do.delete}"/> </condition> <fail if="do.abort">Build aborted by user.</fail> <sql driver="${sql.driver}" url="${sql.url}" userid="${sql.user}" password="${sql.pass}" > <transaction src="deleteclient.sql"/> <transaction src="deleteproject.sql"/> </sql> </target> </project> client.sql create table client ( client_id int not null auto_increment primary key,

client_name text not null ); project.sql create table project ( project_id int not null auto_increment primary key, project_name text not null ); deleteclient.sql drop table client; deleteproject.sql drop table project; Create the all client.sql, project.sql, deleteclient.sql, deleteproject.sql files parallel of the build.xml file and simply run the build.xml file with ant command in the appropriate path on command prompt. If the program executes successfully, then the following output will be displayed.

Ant and JUnit This example illustrates how to implement junit test case with ant script. This is a basic tutorial to implement JUnit framework with ANT technology. Before creating any test case you will need Java compiler, Ant and JUnit. You will also need junit.jar in your Ant's library folder. Download the junit.jar file from the given link http://junit.org/ and paste this jar file in ANT_HOME/lib folder. Then create a build.xml file as shown below. <property name="testdir" location="test" /> <property name="srcdir" location="src" /> <property name="full-compile" value="true" /> <path id="classpath.base"/> <path id="classpath.test"> <pathelement location="/apache-ant-1.7.1/lib/junit-3.8.1.jar" /> <pathelement location="/apache-ant-1.7.1/lib/junit-3.8.jar" /> <pathelement location="${testdir}" /> <pathelement location="${srcdir}" /> <path refid="classpath.base" /> </path> <target name="clean" > <delete verbose="${full-compile}"> <fileset dir="${testdir}" includes="**/*.class" /> </delete> </target> <target name="compile" depends="clean"> <javac srcdir="${srcdir}" destdir="${testdir}" verbose="${full-compile}" > <classpath refid="classpath.test"/> </javac> </target>

<target name="test" depends="compile"> <junit> <classpath refid="classpath.test" /> <formatter type="brief" usefile="false" /> <test name="JUnitTestExample" /> </junit> </target> </project> Create a JUnitTestExample.java file in the src directory as given below. import junit.framework.*; public class JUnitTestExample extends TestCase{ public void testCase1(){ assertTrue( "TestExample", true ); } } If you run the source code with ant command, then the following output will be displayed.

If you compile with ant -verbose test command, then the following output will be displayed.

Value in the properties file overwrite the value in the build.xml:This example illustrates how to create a build.properties file in the C:\apache-tomcat-6.0.16\webapp\antBuild\build.properties and overwrite it's properties in the build.xml file. In this example, <property name="build.path"> is used to map the path of build.xml and build.properties file, <property url="http://localhost:8080/antBuild/build.properties"> is used to root url of properties file, <property file="build.properties" prefix="imported"> is used to define the property of the build.properties file and <property environment="env"> is used to create an environment variable that is 'env'. Now the target <target name="builtin-properties"> is used to find base directory name, ant file name, version of ant, project name and version of java. The target <target name="build.path"> is used to print the file name and path of file and finally <target name="environment"> is used to print the processor architecture name and operating system name and print the ant home directory name. Source code of build.xml: <project name="Properties" basedir="." default="environment"> <property name="build.path" value="${basedir}/build.xml:${basedir}/build.properties"/> <property url="http://localhost:8080/antBuild/build.properties"/> <property file="build.properties" prefix="imported"/> <property environment="env"/> <target name="built-in properties">

<echo message="The base directory is: ${basedir}"/> <echo message="The ant file is: ${ant.file}"/> <echo message="The Ant version is: ${ant.version}"/> <echo message="The Project name is: ${ant.project.name}"/> <echo message="The Java version is: ${ant.java.version}"/> </target> <target name="build.path" depends="built-in properties"> <echo message="The File name is: ${basedir}${file.separator}build.xml"/> <echo message="Path structure: ${basedir}${file.separator}build.xml${path.separator} ${basedir}${file.separator}build.properties"/> </target> <target name="environment" depends="build.path"> <echo message="Built on: ${env.OS} ${env.PROCESSOR_ARCHITECTURE}"/> <echo message="ANT_HOME Directory name: ${env.ANT_HOME}"/> </target> </project> source code of build.properties: property.example=Local property.file.example=build.properties Run this program on command prompt - the following output will be displayed.

File

Built In Properties:This example illustrates how to access various system properties using Ant. Ant provides access to all system properties as if they had been defined using a <property> task. Here is a list of the properties with descriptions. Property basedir ant.file ant.version ant.project.name ant.java.version ant.home java.version java.vendor java.vendor.url java.home java.vm.specification.version 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 JRE version JRE vendor Java vendor URL Java installation directory JVM 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

JVM specification vendor JVM specification name JVM implementation version JVM implementation vendor JVM implementation name JRE specification version JRE specification vendor JRE 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

T HE SOURCE CODE OF BUILD. XML FILE <project name="Built-In-Properties" default="echo" basedir="."> <property environment="env"/> <target name="echo"> <echo message="basedir : ${basedir}"/> <echo message="ant.file : ${ant.file}"/> <echo message="ant.project.name : ${ant.project.name}"/> <echo message="ant.home : ${ant.home}"/> <echo message="ant.version : ${ant.version}"/> <echo message="ant.java.version : ${ant.java.version}"/> <echo message="java.version : ${java.version}"/> <echo message="java.vendor : ${java.vendor}"/> <echo message="java.vendor.url : ${java.vendor.url}"/> <echo message="java.home : ${java.home}"/> <echo message="java.vm.specification.version : ${java.vm.specification.version}"/> <echo message="java.vm.specification.vendor : ${java.vm.specification.vendor}"/> <echo message="java.vm.specification.name : ${java.vm.specification.name}"/> <echo message="java.vm.version : ${java.vm.version}"/> <echo message="java.vm.vendor : ${java.vm.vendor}"/> <echo message="java.vm.name : ${java.vm.name}"/> <echo message="java.specification.version : ${java.specification.version}"/> <echo message="java.specification.vendor : ${java.specification.vendor}"/> <echo message="java.specification.name : ${java.specification.name}"/> <echo message="java.class.version : ${java.class.version}"/> <echo message="java.class.path : ${java.class.path}"/> <echo message="java.ext.dirs : ${java.ext.dirs}"/> <echo message="os.name : ${os.name}"/> <echo message="os.arch : ${os.arch}"/> <echo message="os.version : ${os.version}"/>

<echo message="file.separator : ${file.separator}"/> <echo message="path.separator : ${path.separator}"/> <echo message="line.separator : ${line.separator}"/> <echo message="user.home : ${user.home}"/> <echo message="user.name : ${user.name}"/> <echo message="user.dir : ${user.dir}"/> <echo message="Path: ${env.Path}"/> <echo message="Hostname: ${env.COMPUTERNAME}"/> </target> </project> RUN THIS CODE THE FOLLOWING OUTPUT WILL BE DISPLAYED .

CHECK PROPERTIES This example illustrates how to check properties using environment variable whether it is set or not. In this code, there are three properties; the first two are used to define source directory and destination directory. The source directory is 'src' and the destination directory is 'build'. The element <property environment="env"> is a path of jar file dependent on environment variables, and these are available only if you use <property environment="env"> before you import the property file. The following example shows how to check whether TOMCAT_HOME environment variable is set or not. If TOMCAT_HOME environment variable is set, then the output will display build successful... as given below.
BUILD . XML

<project name="Check Properties" default="compile" basedir="."> <property name="dir.src" value="src"/> <property name="dir.build" value="build"/> <property environment="env"/> <target name="check"> <fail unless="env.TOMCAT_HOME">TOMCAT_HOME class path must be set</fail> </target> <target name="clean" depends="check"> <delete dir="${dir.build}"/> </target>

<target name="prepare" depends="clean"> <mkdir dir="${dir.build}"/> </target> <target name="compile" depends="prepare" > <echo>Compile code...</echo> </target> </project>

Output:

But if TOMCAT_HOME environment variable is not set, then the following error message will be displayed.

Ant make directory with relative path:This example illustrates how to make directory, how to compile java file and how to create jar file. This is a simple program that uses <classpath refid="test.classpath"> to map with the jar file. In this example five targets are used, the first target <target name="clean"> is used to delete the build and the dist directory. The second target <target name="prepare"> is used to create the build and the dist directory. The third target <target name="compile"> is used to compile the java file and copy the class file in build directory. The fourth target <target name="jar"> is used to create the jar file in the dist directory from the name of test.jar. The fifth target <target name="test"> is used to map with the class path by the reference id. T HE SOURCE CODE OF BUILD. XML FILE IS AS FOLLOWS: <project name="AntPath" default="test" basedir="."> <property name="class" value="Test"/> <path id="test.classpath"> <pathelement location="dist/test.jar"/> </path> <target name="clean"> <delete dir="build"/> <delete dir="dist"/> </target> <target name="prepare" depends="clean"> <mkdir dir="build"/>

<mkdir dir="dist"/> </target> <target name="compile" depends="prepare"> <javac destdir="build" debug="on" optimize="on"> <src path="src"/> </javac> </target> <target name="jar" depends="compile"> <jar jarfile="dist/test.jar"> <fileset dir="build"> <include name="test/*.class"/> </fileset> </jar> </target> <target name="test" depends="jar"> <java fork="true" failonerror="no" classname="${class}"> <classpath refid="test.classpath"/> <arg line=""/> </java> </target> </project> SOURCE CODE OF T EST.JAVA : class Test { public static void main(String args[]){ System.out.println("RoseIndia Technology Pvt. Ltd."); } } Run this program on the appropriate path with ant command. The following output will be displayed.

Ant Custom Properties Setting properties in the build file is the first method of providing custom properties with <property> element in an ant build file. Unlike the <project> and <target> elements, the <property> element is defined as a task. This means that you can include <property> elements inside a target depending on certain conditions or depending on which target has been selected. You can also set properties at the beginning of a build file so that they apply to the entire build file. This means that you can set important constant values in a central location so that they are easy to find and change. You should remember that properties set inside a target override any properties set at the project level. Naming again comes into this and you should consider whether your target level properties should be identified as such by using a prefix to avoid confusion and possible namespaces clashes. The simplest and most obvious use of the <property> task is to set a property using a name value pair, as shown below. You can set the value of a property to the value of another property. This can be useful if you will be referencing a verbose builtin property multiple times. This is as simple as placing a property marker in the value attribute of a <property> task as shown below in source code:

build.xml: <project name="Properties" default="custom.echo" basedir="."> <property name="custom.value" value="1.0"/> <property name="fileseperator" value="${file.separator}"/> <property name="pathseperator" value="${path.separator}"/> <target name="custom"> <echo message="custom.value = ${custom.value}"/> </target> <target name="custom.echo" depends="custom"> <echo message="File: ${basedir}${fileseperator}build.xml"/> <echo message="Path: ${basedir}${fileseperator}build.xml${pathseperator}${basedir} ${fileseperator}build.properties"/> </target> </project> Run this program on the appropriate path, then the following output will be displayed.

How to set memory used by JVM in Ant This example illustrates how to set memory size of JVM (java virtual machine), when ANT (another neat tool) is used outside of java virtual machine. In this example, <property name="sourcedir"> is used to specify the location of source directory and <property name="targetdir"> is used to specify the location of target directory and <property name="librarydir"> is used to define the location of library directory. In this build.xml file, <path id="libraries"> is used to put any jar file in the lib directory. The target <target name="clean"> is used to delete the target directory and library directory from base directory. The target <target name="prepare"> is used to create the source directory, target directory and library directory and <target name="compile"> is used to compile the source code. The fork="true" is used if you don't run Java code in a separate JVM to the ant script, you can get some pretty strange errors that are difficult to diagnose. For NoClassDefFoundError, the problem was fixed by setting fork=true in the java target. The memoryMaximumSize="1024m" for the underlying VM, if using fork mode; ignored otherwise. Defaults to the standard VM memory setting. (Examples: 83886080, 81920k, or 80m) and memoryInitialSize="256m" is used for the underlying VM, if using fork mode; ignored otherwise. Defaults to the standard VM memory setting. (Examples: 83886080, 81920k, or 80m). The source code of build.xml file is as follows: <project name="MemoryMap" default="compile" basedir="."> <property name="sourcedir" value="${basedir}/src"/> <property name="targetdir" value="${basedir}/build"/> <property name="librarydir" value="${basedir}/lib"/> <path id="libraries"> <fileset dir="${librarydir}"> <include name="*.jar"/> </fileset> </path> <target name="clean"> <delete dir="${targetdir}"/> <delete dir="${librarydir}"/> </target>

<target name="prepare" depends="clean"> <mkdir dir="${sourcedir}"/> <mkdir dir="${targetdir}"/> <mkdir dir="${librarydir}"/> </target> <target name="compile" depends="prepare"> <javac srcdir="${sourcedir}" destdir="${targetdir}" debug="true" fork="true" memoryMaximumSize="1024m" memoryInitialSize="256m"> </javac> </target> </project> Hello.java class Hello{ public static void main(String args[]) { System.out.println("Sandeep kumar suman"); } } Create a class file in the 'src' folder and compile it on the console with ant command. The following output will be displayed.

Redefine property in the children Target This example illustrates how to define the property file whether it is local or global. When you create build.properties on local target, then the echo message prints that this file is Local but when the file is not created on local target, then it shows the message Global file. The <property name="build.property" value="Global"/> element is used to define global build.properties file and <property name="build.property" value="Target"/> is used to define local build.properties file. The target <target name="global-file"> is used to print the global value of build.properties file and <target name="local-file"> is used to print local value of build.properties file. Source code of build.xml: <project name="Properties" default="local-file" basedir="."> <property file="build.properties"/> <property name="build.property" value="Global"/> <property name="build.property" value="Target"/> <target name="global-file"> <echo message="The value of build.property is: ${build.property}"/> </target> <target name="local-file" depends="global-file"> <echo message="The value of build.property is: ${build.property}"/> </target> </project> Run this program - the following output will be displayed.

If any given property file which is not available on local target (code is given below). <project name="Properties" default="local-file" basedir="."> <property file="build.properties"/> <property name="property.example" value="Global"/> <property name="property.example" value="Target"/> <target name="global-file"> <echo message="The value of property.example is: ${property.example}"/> </target> <target name="local-file" depends="global-file"> <echo message="The value of property.example is: ${property.example}"/> </target> </project> When you run this program, then the following output will be displayed.

Path Separator In this example, path.separator is used to separate the path and file by semicolon (;). When it is run, Ant checks for the path separator and directory separator characters provided by the underlying JVM and uses those values. It successfully interprets either the ";" or the ":" inside the build file. For example, when run on Unix machine, ant interprets the path dir;dir\\subdir correctly as the dir;dir\\subdir. Separator must be used consistently with in the same value type; the string dir;dir\\subdir, combining a windows path separator (;) and a Unix directory separator (/) is not a good form. <project name="PathSeperator" default="echo" basedir="."> <target name="echo"> <echo message="File: ${basedir}${path.separator}build.xml"/> <echo message="Path: ${basedir}${path.separator}build.xml${path.separator} ${basedir}${path.separator}build.properties"/> </target> </project> The following output will be displayed if you execute ant command on the command prompt with appropriate path.

Convert the path in to properties This example illustrates how to convert path in to properties. In this example, refid is a reference to an object defined elsewhere in the file. The reference allows you to reuse the chunks of the build file so that common classpath and path can be shared among targets. Many tasks have a refid attribute assigning the value of reference object to the property name with the name attribute. In this example, the java file is converted from src directory to build directory and the lib directory refers to the common lib directory of apache tomcat home directory. The path of tomcat home is changed in to the property name. The source code of build.xml is as follows: <?xml version="1.0" encoding="UTF-8"?> <project name="convert path" default="compile" basedir="."> <property environment="env"/> <property name="tomcatHome" value="${env.TOMCAT_HOME}"/> <property name="dir.src" value="src"/> <property name="dir.build" value="build"/> <property name="dir.lib" value="lib"/> <path id="project.classpath"> <pathelement location="${dir.src}"/> <fileset dir="${tomcatHome}/common/lib"> <include name="*.jar"/> </fileset> <fileset dir="${dir.lib}"> <include name="*.jar"/> </fileset> </path> <target name="clean"> <delete dir="${dir.build}"/> <delete dir="${dir.lib}"/> </target> <target name="prepare" depends="clean"> <mkdir dir="${dir.build}"/> <mkdir dir="${dir.lib}"/> <mkdir dir="${dir.src}"/> </target> <target name="compile" depends="prepare"> <pathconvert targetos="windows" property="windowsPath" refid="project.classpath"/> <echo>Path Directory = ${windowsPath}</echo> <javac destdir="${dir.build}" srcdir="${dir.src}"> <classpath refid="project.classpath"/> </javac> </target> </project> If you run the program, the following output will be generated.

File Separator This example allows you to build platform-specific paths and directory hierarchies. When you build a path with any of ant's task, Ant is quite happy to convert the separators in to ones appropriate for the operating system on which it is running. Ant will also do the conversion if you pass the string that you have built to its tasks. Therefore, you could rewrite the previous listing. Source code of build.xml: <project name="FileSeperator" default="echo" basedir="."> <target name="echo"> <echo message="The File name is: ${basedir}${file.separator}build.xml"/> <echo message="The directory Path is: ${basedir}${file.separator}build.xml${path.separator} ${basedir}${file.separator}build.properties"/> </target> </project> If the display shows a mixture of file separators, don't disturb ant that is still treating these as strings. The following output will be displayed if you execute ant command on the command prompt.

You might also like