Apache Ant - Building Simple Java Projects
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. 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. Ant, as a part of Apache Jakarta Project is an open source solution based on java platform. With the advent of time, it gained popularity and used widely. 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 1.8.1.Introduction to Apache Ant (Another Neat Tool)
Ant is an open source build technology developed by Apache intended to build processes in Java environment. It is a similar kind of tool like make but it does not use shell commands to extend the functionality. The use of shell commands in make brings about the integrity with other languages too but this also makes it platform specific. In contrast, 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 platform, that’s why 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 2010. 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. After the download completes, unzip this file and install the apache-ant-1.8.2 folder to the root directory of C:\ drive. Therefore, path for the Ant directory will be C:\apache-ant-1.8.1. Now, we have to set some environment variables. Select the item "System" in the Control Panel of your system and click on the tab named "Advanced". You will see a button named "Environment Variables" appears, click it. Under Environment variables, you will find two user variables, viz., ANT_HOME and CLASS_PATH. Set the path value C:\apache-ant-1.8.2 to ANT_HOME variable and the path value C:\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 C:\apache-ant-1.8.2\bin; to Path variable.
Now, you have to check whether the installation process is done properly or not. 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 |
Project |
Attribute | Description | Requirement |
name | project name | not necessary |
default | target name which called by default | not necessary |
basedir | the base directory having all path, it contain absolute path | not necessary |
<project name="My Project" default="compile" basedir="."> |
An another tag is Target tag which has following five attributes:
Target |
Attribute | Description | Requirement |
name | target name | necessary |
depends | depends on another target | not necessary |
if | the name of the property that must be set in order for this target to execute. | not necessary |
unless | the name of the property that must not be set in order for this target to execute. | not necessary |
description | short description about target | not necessary |
<target name="buildWar" depends="init" description="build a war file"/> <target name="init" if="build"/><target name="init" unless="build"/> |
Next tag is property tag which has following four attribute:
Property |
Attribute | Description | Requirement |
name | name of the property, which is case-sensitive | not necessary |
value | name of task attribute, this is done by placing the property name between " ${ "name } " in the attribute value | necessary |
location | it contain property name | not necessary |
file | name of the property file | not necessary |
<property name="build" value="${build}"/> <property name="src" location="src"/> <property file="build.properties"/> |
The 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 Progammers_compile.jar file in to the 'dest' directory."> <jar jarfile="${dir.dest}/Progammers_compile.jar" basedir="${dir.build}"/> </target> </project> |
The output shows that a jar file named Progammers_compile.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("Prasobh.K"); } } |
Ant built-in Properties
Following 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. The following table shows the property name and it's description.
Ant's built-in properties:
Property | Description |
ant.file | The absolute path of the build file |
ant.project.name | The name of the project as set in the <project> element's name attribute. |
ant.home | The root directory of ant |
ant.version | The version of this ant installation. This is not just the version number and includes information such as the compilation date. |
ant.java.version | The version of the java that ant uses |
basedir | The absolute path of the project |
os.name | Operating system name |
java.home | Java home directory name |
user.home | User directory name |
user.name | 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>
</project>
<?xml version=
"1.0"
?>
<project name="
opensourzesupport" 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="
opensourzesupport"/>
<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>
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="prasobh"/> <property name="sql.pass" value="prasobh"/> <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> |
create table client ( client_id int not null auto_increment primary key, client_name text not null ); |
create table project ( project_id int not null auto_increment primary key, project_name text not null ); |
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="prasobh"/> <property name="sql.pass" value="prasobh"/> <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> |
create table client ( client_id int not null auto_increment primary key, client_name text not null ); |
create table project ( project_id int not null auto_increment primary key, project_name text not null ); |
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"); |
INSERT INTO project (project_name) VALUES ("codingdiary.com"); INSERT INTO project (project_name) VALUES ("opensourzesupport.blogspot.com"); 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"); |
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:
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="prasobh"/> <property name="sql.pass" value="prasobh"/> <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> |
create table client ( client_id int not null auto_increment primary key, client_name text not null ); |
create table project ( project_id int not null auto_increment primary key, project_name text not null ); |
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"); |
INSERT INTO project (project_name) VALUES ("codingdiary.com"); INSERT INTO project (project_name) VALUES ("opensourzesupport.blogspot.com"); 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"); |
UPDATE client SET client_name = "Mr. Dormet" WHERE client_id = "13"; |
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
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.8.2/lib/junit-3.8.1.jar" /> <pathelement location="/apache-ant-1.8.2/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 ); } } |
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
SVN Ant Task
use the following build file :
<?xml version="1.0"?>
<project name="svn-task" basedir="." default="checkout">
<!-- including the property file -->
<property file="svn.properties" />
<!-- path to the svnant libraries. including all jar files -->
<path id="svn.classpath">
<fileset dir="${svnant.home}">
<include name="*.jar"/>
</fileset>
</path>
<!-- load the svn task -->
<typedef resource="org/tigris/subversion/svnant/svnantlib.xml"
classpathref="svn.classpath" />
<!-- checkout from repository -->
<target name="checkout" >
<echo message="svn ant libraries located at ${svnant.home}" />
<svn javahl="false" username="${svn.repository.user}" password="${svn.repository.passwd}" >
<checkout url="${svn.repository.url}" revision="HEAD" destPath="." />
</svn>
</target>
<!-- update working directory from repository -->
<target name="update" >
<echo message="svn ant libraries located at ${svnant.home}" />
<svn username="${svn.repository.user}" password="${svn.repository.passwd}" >
<update dir="." />
</svn>
</target>
</project>
<!-- svn.properties -->
svnant.home=D:/svnant-1.0.0/lib
svn.repository.url=***/trunk
svn.repository.user=$$$$
svn.repository.passwd = @@@@
include the folowing jar files :
javasvn.jar
svnant.jar
svnClientAdapter.jar
svnjavahl.jar
download svnant-1.1.0-RC2 from foloowing link : -
Using Conditional Logic with ant
see following example
<if>
<equals arg1="${env}" arg2="dev" />
<then>
<antcall target="checkoutFromTrunc"/>
</then>
<elseif >
<equals arg1="${env}" arg2="production" />
<then>
<antcall target="checkoutFromTag"/>
</then>
</elseif>
<else>
<echo message="" />
<echo message=" -Denv=${env} is not valid arrgument" />
</else>
</if>
by default ant doesn't suppot if task.additional jar(ant-contrib-1.0b3.jar) needed
download from http://sourceforge.net/projects/ant-contrib/files/ant-contrib/1.0b3/ant-contrib-1.0b3-bin.zip/download
specify following in xml to load if task
<!-- load the additional ant task like if -->
<taskdef resource="net/sf/antcontrib/antlib.xml" />
Ant SCP Task
see following example :
<scp file="myfolder/my.txt" todir="username:password@ip:dirPath"
port="portNumer"
sftp="true"
trust="true"/>
use jsch-0.1.44.jar file..either copy in ant lib dir or set classpath..
Ant OptionPane Task(input Prompt)
OptionPane
Description
Solicit and receive response from user.
This task is a wrapper for the JOptionPane object. It can be used to display message boxes to the user, confirmation boxes, or to obtain a text response. You control the dialog box type using the type property.
This task provides you full-control of the dialog box. You can set the title using the title property, the prompt message using the message property, and the icon using the style property. If it's a confirmation box then you can also choose which set of buttons you want using the optionbtns property.
This task can also be used to display a pick list to the user. The list is formed by using embedded
<option>
elements.Parameters
Attribute | Description | Required |
property | Specifies the property to store the user response. The response will be one of the following:
| Yes |
type | Specifies the type of dialog to display. Valid values for this property are:
| No |
style | Specifies the icon to display in the dialog. Valid values for this property are:
| No |
optionbtns | Specifies the buttons to display on a confirmation dialog. Is only valid when the type property is "confirm", for all other types the property is ignored. Valid values for this property are:
| No |
title | Specifies the title for the dialog. Default value is "Ant OptionPane". | No |
message | Specifies the message text to use for the dialog. While this property isn't strictly required, the user probably won't know what to do without it! | No |
initialval | If there are embedded <option> elements, then this property specifies which option from the set is to be initially selected. Otherwise this property specifies the text to initially appear in the input text box.Is only valid when the type property is "option", for all other types the property is ignored. | No |
Examples
<optionpane property="user.input" message="Are you sure?"/>
Displays a confirmation box with "Yes" and "No" buttons.
<optionpane property="user.input" type="message" style="information" title="Finished" message="Build finished!"/>
Displays a message box with an "Ok" button.
<optionpane property="user.input" type="input" message="Enter a subproject to build:"/>
Displays an empty input text box.
<optionpane property="user.input" type="option" message="Enter a subproject to build:" initialval="myproject"/>
Displays an input text box initially populated with "myproject".
<optionpane property="user.input" type="option" title="Choose Subproject" message="Pick one of the following subprojects:"> <option value="project1"/> <option value="project2"/> <optoin value="project3"/> </optionpane>
use optionpane.jar file..
<!-- load optionpane task --> <taskdef name="optionpane" classname="org.apache.tools.ant.taskdefs.optional.optionpane.OptionPane" />
put this in your xml file to load optionpane task.
No comments:
Post a Comment