Thursday, March 6, 2014

ANT

Apache ANT

- Ant stands for Another Neat Tool
- Originally used to build tomcat and was bundled as part of tomcat distribution

Features:
- Most complete Java build and deployment tool available
- scripts are written using plain XML. If you are familiar with XML, you can learn ANT pretty quickly
- good at automating complicated repetitive tasks
- comes with big list of predefined tasks
- provides interface to develop custom tasks
- can be easily invoked from command line and can integrate with free and commercial
IDEs.

Installing Apache Ant:
- Download binaries from http://ant.apache.org.
- unzip zip file to convenient location using winzip, winRar to say C:\folder
- Create a new environment variable called ANT_HOME that points to the Ant installation folder. In this case c:\apache-ant-1.8.2-bin folder.
- Append the path to Apache Ant batch file to the PATH environment variable. In our case, this
would be c:\apache-ant-1.8.2-bin\bin folder

Verifying apache ant installation
- C:\>ant -version

Ant Build File:
- build.xml should live in projects base directory.
- create a file called build.xml anywhere in your computer.
<?xml version="1.0"?>
<project name="Hello World Project" default="info">
<target name="info">
<echo> Hello World-Welcome to Apache Ant!</echo>
</target>
</project>

XML element project has three attributes:
name: name of the project(default)
default: default target for build script.
project can contain any number of targets.
basedir: root folder for project(optional)

Target: collection of task you want to run as one unit
Targets can have dependencies on other targets.
Deploy target may have dependency on package target and package target may have dependency on compile target and so forth.
Dependencies are denoted using depends attribute.

<target name="deploy" depends="package">
...
</target>
<target name="package" depends="clean,compile">
...
</target>
<target name="clean">
...
</target>
<target name="compile">
...
</target>

Target element has following attributes:
- name: name of target
- depends: comma seperated lists of all targets that this target depends on.
- description: short description of target

echo task is trivial task that prints the message.
In our case, it prints hello world message.

To run ant build file, open command prompt and navigate to folder where build.xml resides, and type ant info. You can also type ant instead.

you see following output:
[echo] Hello World - Welcome to Apache Ant!

Property Task:

Ant uses the property element which allows you to specify properties.
This allows the properties to change from one build to another or from one environment to other.

ant.file: full location of build file
ant.version: version of apache ant installation
basedir: basedir of build as specified in basedir attribute of project element
ant.java.version: version of JDK used by Ant
ant.project.name: name of project as specified in name attribute of project element
ant.project.default-target: default target of current project
ant.project.invoked-targets: comma seperated list of targets that were invoked in current project
ant.core.lib: full location of ant jar file
ant.home: home directory of ant installation
ant.library.dir: home directory for Ant library files

Property files:

Following shows build.xml and an associated build.properties file:

build.xml
<?xml version="1.0"?>
<project name="Hello World Project" default="info">
<property file="build.properties"/>
<target name="info">
<echo> Apache ant version is ${ant.version}- You are at
${sitename}</echo>
</target>
</project>

build.properties:
#Site name:
sitename=www.tutorialspoint.com
buildversion=3.3.2

Data types:

- Ant provides a number of predefined data types.

File Set:
- this data type represents collection of files.
- used as filter to include and exclude files that match particular pattern

<fileset dir="${src}" casesensitive="yes">
<include name="**/*.java"/>
<include name="**/*.stub"/>
</fileset>

Pattern set:
- pattern that allows to easily filter files or folders based on certain patterns.
- patterns can be created using following meta characters:
?: matches one character only
*- matches zero or many characters
**- matches zero or many directories recursively

<patternset id="java.files.without.stubs">
  <include name="src/**/*.java"/>
  <exclude name="src/**/*Stub*"/>
</patternset>

<fileset dir="${src}" casesensitive="yes">
  <patternset refid="java.files.without.stubs"/>
 </fileset>

File List:
- it can be applied to files that may or may not exist yet.
- it is similar to file set except that file list contains explicitly named lists of files and do not support wild cards.

<filelist id="config.files" dir="${webapp.src.folder}">
  <file name="applicationConfig.xml"/>
  <file name="faces-config.xml"/>
  <file name="web.xml"/>
  <file name="portlet.xml"/>
</filelist>

Filter set:
Using a Filter Set data type with the copy task, you can replace certain text in all files that match the pattern with a replacement value.

<copy todir="${output.dir}">
  <fileset dir="${releasenotes.dir}" includes="**/*.txt"/>
  <filterset>
    <filter token="VERSION" value="${current.version}"/>
  </filterset>
</copy>

Path data type:
The path data type is commonly used to represent a classpath. Entries in the path are separated using a semicolon or colon. However, these characters are replaced at the run time by the running system's path separator character.

<path id="build.classpath.jar">
  <pathelement path="${env.J2EE_HOME}/${j2ee.jar}"/>
  <fileset dir="lib">
      <include name="**/*.jar"/>
  </fileset>
</path>


This project will form the Hello World Fax Application project for the rest of this tutorial.

C:\work\FaxWebApplication>tree
Folder PATH listing
Volume serial number is 00740061 EC1C:ADB1
C:.
+---db
+---src
.   +---faxapp
.       +---dao
.       +---entity
.       +---util
.       +---web
+---war
    +---images
    +---js
    +---META-INF
    +---styles
    +---WEB-INF
        +---classes
        +---jsp
        +---lib


Let me explain the project structure.

db folder: database scripts are stored
src folder: java source code is stored
war folder:The images, js, META-INF, styles (css) are stored in the .
jsp folder: JSPs are stored 
lib folder: Third party jar files are stored.
WEB-INF\classes folder: The java class files will be stored in the 
The aim of this exercise is to build an ant file that compiles the java classes and places them in the WEB-INF\classes folder.

Here is the build.xml required for this project. Let us consider it piece by piece

<?xml version="1.0"?>
<project name="fax" basedir="." default="build">
    <property name="src.dir" value="src"/>
    <property name="web.dir" value="war"/>
    <property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
    <property name="name" value="fax"/>

    <path id="master-classpath">
        <fileset dir="${web.dir}/WEB-INF/lib">
            <include name="*.jar"/>
        </fileset>
        <pathelement path="${build.dir}"/>
    </path>

    <target name="build" description="Compile source tree java files">
        <mkdir dir="${build.dir}"/>
        <javac destdir="${build.dir}" source="1.5" target="1.5">
            <src path="${src.dir}"/>
            <classpath refid="master-classpath"/>
        </javac>
    </target>

    <target name="clean" description="Clean output directories">
        <delete>
            <fileset dir="${build.dir}">
                <include name="**/*.class"/>
            </fileset>
        </delete>
    </target>
</project>

First, let us declare some properties for the source, web and build folders.

<property name="src.dir" value="src"/>
<property name="web.dir" value="war"/>
<property name="build.dir" value="${web.dir}/WEB-INF/classes"/>

The clean target, as the name suggests deletes the files in the build folder.

<target name="clean" description="Clean output directories">
   <delete>
      <fileset dir="${build.dir}">
         <include name="**/*.class"/>
      </fileset>
   </delete>
</target>

The master-classpath holds the classpath information. In this case, it includes the classes in the build folder and the jar files in the lib folder.

<path id="master-classpath">
   <fileset dir="${web.dir}/WEB-INF/lib">
      <include name="*.jar"/>
   </fileset>
   <pathelement path="${build.dir}"/>
</path>

<target name="build" description="Compile main source tree java files">
   <mkdir dir="${build.dir}"/>
   <javac destdir="${build.dir}" source="1.5" target="1.5" debug="true"
             deprecation="false" optimize="false" failonerror="true">
      <src path="${src.dir}"/>
      <classpath refid="master-classpath"/>
   </javac>
</target>

Build documentation:

Putting it all together
Let us continue our theme of the Hello world Fax application. Let us add a documentation target to our Fax application project.

Below is an example javadoc task used in our project.

<target name="generate-javadoc">
    <javadoc packagenames="faxapp.*" sourcepath="${src.dir}"
        destdir="doc" version="true" windowtitle="Fax Application">
      <doctitle><![CDATA[= Fax Application =]]></doctitle>
      <bottom>
         <![CDATA[Copyright © 2011. All Rights Reserved.]]>
      </bottom>
      <group title="util packages" packages="faxapp.util.*"/>
      <group title="web packages" packages="faxapp.web.*"/>
      <group title="data packages"
                          packages="faxapp.entity.*:faxapp.dao.*"/>
    </javadoc>
    <echo message="java doc has been generated!" />
</target>


In this example, we have specified the javadoc to use the src.dir as the source directory, and doc as the target directory. We have also customized the window title, the header and footer information that appear on the java documentation pages.

Also, we have created three groups. One for the utility classes in our source folder, one group for the user interfaces classes and one group for the database related classes. You may notice that the data package group has two packages - faxapp.entity and faxapp.dao.

Running the javadoc ant task will now generate and place the java documentation files in the doc folder.

When the javadoc target is executed, it produces the following outcome:

C:\>ant generate-javadoc
Buildfile: C:\build.xml

java doc has been generated!

BUILD SUCCESSFUL
Total time: 10.63 second
The java documentation files are now present in the doc folder.

Creating JAR files:

The next logical step after compiling your java source files, is to build the java archive, i,e the JAR file. Creating JAR files with Ant is quite easy with the jar task. Presented below are the commonly used attributes of the jar task


Attributes           Description
basedir The base directory for the output JAR file. By default, this is set to the base directory of the project.
compress            Advises ant to compress the file as it creates the JAR file.
keepcompression            While the compress attribute is applicable to the individual files, the keepcompression attribute does the same thing, but it applies to the entire archive.
destfile The name of the output JAR file
duplicate             Advises Ant on what to do when duplicate files are found. You could add, preserve or fail the duplicate files.
excludes              Advises Ant to not include these comma separated list of files in the package.
excludesfile        Same as above, except the exclude files are specified using a pattern.
inlcudes               Inverse of excludes
includesfile         Inverse of excludesfile.
update Advises ant to overwrite files in the already built JAR file.

Continuing our Hello World Fax Application project, let us add a new target to produce the jar files. But before that let us consider the jar task:

<jar destfile="${web.dir}/lib/util.jar"
     basedir="${build.dir}/classes"
     includes="faxapp/util/**"
     excludes="**/Test.class"
/>

In this example, the web.dir property points to the path of the web source files. In our case, this is where the util.jar will be placed.

The build.dir property in this example points to the build folder where the class files for the util.jar can be found.

In this example, we create a jar file called util.jar using the classes from the faxapp.util.* package. However, we are excluding the classes that end with the name Test. The output jar file will be place in the webapp's lib folder.

If we want to make the util.jar an executable jar file we need to add the manifest with the Main-Class meta attribute.

Therefore the above example will be updated as:

<jar destfile="${web.dir}/lib/util.jar"
     basedir="${build.dir}/classes"
     includes="faxapp/util/**"
     excludes="**/Test.class">
     <manifest>
      <attribute name="Main-Class" value="com.tutorialspoint.util.FaxUtil"/>
     </manifest>
</jar>

To execute the jar task, wrap it inside a target (most commonly, the build or package target, and run them.

<target name="build-jar">
<jar destfile="${web.dir}/lib/util.jar"
     basedir="${build.dir}/classes"
     includes="faxapp/util/**"
     excludes="**/Test.class">
     <manifest>
      <attribute name="Main-Class" value="com.tutorialspoint.util.FaxUtil"/>
     </manifest>
</jar>
</target>

Running ant on this file will create the util.jar file for us..

The following outcome is the result of running the ant file:

C:\>ant build-jar
Buildfile: C:\build.xml

BUILD SUCCESSFUL

The util.jar file is now placed in the output folder.

Creating WAR files:

Creating WAR files with Ant is extremely simple, and very similar to the creating JAR files task. After all WAR file, like JAR file is just another ZIP file, isn't it?

The WAR task is an extension to the JAR task, but it has some nice additions to manipulate what goes into the WEB-INF/classes folder, and generating the web.xml file. The WAR task is useful to specify a particular layout of the WAR file.

Since the WAR task is an extension of the JAR task, all attributes of the JAR task apply to the WAR task. Below are the extension attributes that are specify to the WAR task:

Attributes           Description
webxml                Path to the web.xml file
lib           A grouping to specify what goes into the WEB-INF\lib folder.
classes  A grouping to specify what goes into the WEB-INF\classes folder.
metainf                Specifies the instructions for generating the MANIFEST.MF file.

Continuing our Hello World Fax Application project, let us add a new target to produce the jar files. But before that let us consider the war task. Consider the following example:

<war destfile="fax.war" webxml="${web.dir}/web.xml">
   <fileset dir="${web.dir}/WebContent">
      <include name="**/*.*"/>
   </fileset>
   <lib dir="thirdpartyjars">
      <exclude name="portlet.jar"/>
   </lib>
   <classes dir="${build.dir}/web"/>
</war>

As per the previous examples, the web.dir variable refers to the source web folder, i.e, the folder that contains the JSP, css,javascript files etc.

The build.dir variable refers to the output folder - This is where the classes for the WAR package can be found. Typically, the classes will be bundled into the WEB-INF/classes folder of the WAR file.

In this example, we are creating a war file called fax.war. The WEB.XML file is obtained from the web source folder. All files from the 'WebContent' folder under web are copied into the WAR file.

The WEB-INF/lib folder is populated with the jar files from the thirdpartyjars folder. However, we are excluding the portlet.jar as this is already present in the application server's lib folder. Finally, we are copying all classes from the build directory's web folder and putting into the WEB-INF/classes folder.

Wrap the war task inside an Ant target (usually package) and run it. This will create the WAR file in the specified location.

It is entirely possible to nest the classes, lib, metainf and webinf directors so that they live in scattered folders anywhere in the project structure. But best practices suggest that your Web project should have the Web Content structure that is similar to the structure of the WAR file. The Fax Application project has its structure outlined using this basic principle.

To execute the war task, wrap it inside a target (most commonly, the build or package target, and run them.

<target name="build-war">
   <war destfile="fax.war" webxml="${web.dir}/web.xml">
   <fileset dir="${web.dir}/WebContent">
      <include name="**/*.*"/>
   </fileset>
   <lib dir="thirdpartyjars">
      <exclude name="portlet.jar"/>
   </lib>
   <classes dir="${build.dir}/web"/>
</war>
</target>

Running ant on this file will create the fax.war file for us..

The following outcome is the result of running the ant file:

C:\>ant build-war
Buildfile: C:\build.xml

BUILD SUCCESSFUL
Total time: 12.3 seconds


The fax.war file is now placed in the output folder. The contents of the war file will be:

fax.war:
  +---jsp             This folder contains the jsp files
  +---css             This folder contains the stylesheet files
  +---js              This folder contains the javascript files
  +---images          This folder contains the image files
  +---META-INF        This folder contains the Manifest.Mf
  +---WEB-INF
        +---classes   This folder contains the compiled classes
        +---lib       Third party libraries and the utility jar files
        WEB.xml       Configuration file that defines the WAR package

Packaging applications:

Now it is time to put everything together to create a full and complete build.xml file. Consider build.properties and build.xml files as follows:

build.properties
deploy.path=c:\tomcat6\webapps
build.xml
<?xml version="1.0"?>

<project name="fax" basedir="." default="usage">
    <property file="build.properties"/>
    <property name="src.dir" value="src"/>
    <property name="web.dir" value="war"/>
    <property name="javadoc.dir" value="doc"/>
    <property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
    <property name="name" value="fax"/>

    <path id="master-classpath">
        <fileset dir="${web.dir}/WEB-INF/lib">
            <include name="*.jar"/>
        </fileset>
        <pathelement path="${build.dir}"/>
    </path>
   
    <target name="javadoc">
      <javadoc packagenames="faxapp.*" sourcepath="${src.dir}"
      destdir="doc" version="true" windowtitle="Fax Application">
        <doctitle><![CDATA[<h1>= Fax Application
          =</h1>]]></doctitle>
        <bottom><![CDATA[Copyright © 2011. All
          Rights Reserved.]]></bottom>
        <group title="util packages" packages="faxapp.util.*"/>
        <group title="web packages" packages="faxapp.web.*"/>
        <group title="data packages"
          packages="faxapp.entity.*:faxapp.dao.*"/>
      </javadoc>
    </target>

    <target name="usage">
        <echo message=""/>
        <echo message="${name} build file"/>
        <echo message="-----------------------------------"/>
        <echo message=""/>
        <echo message="Available targets are:"/>
        <echo message=""/>
        <echo message="deploy    --> Deploy application
          as directory"/>
        <echo message="deploywar --> Deploy application
          as a WAR file"/>
        <echo message=""/>
    </target>

    <target name="build" description="Compile main
      source tree java files">
        <mkdir dir="${build.dir}"/>
        <javac destdir="${build.dir}" source="1.5"
          target="1.5" debug="true"
          deprecation="false" optimize="false" failonerror="true">
            <src path="${src.dir}"/>
            <classpath refid="master-classpath"/>
        </javac>
    </target>

    <target name="deploy" depends="build"
      description="Deploy application">
        <copy todir="${deploy.path}/${name}"
          preservelastmodified="true">
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </copy>
    </target>

    <target name="deploywar" depends="build"
      description="Deploy application as a WAR file">
        <war destfile="${name}.war"
             webxml="${web.dir}/WEB-INF/web.xml">
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </war>
        <copy todir="${deploy.path}" preservelastmodified="true">
            <fileset dir=".">
                <include name="*.war"/>
            </fileset>
        </copy>
    </target>
   

    <target name="clean" description="Clean output directories">
        <delete>
            <fileset dir="${build.dir}">
                <include name="**/*.class"/>
            </fileset>
        </delete>
    </target>
</project>

In this example, we first declare the path to the webapps folder in Tomcat in the build properties file as the deploy.path variable. We also declare the source folder for the java files in src.dir variable. Then we declare the source folder for the web files in web.dir variable. javadoc.dir is the folder for storing the java documentation, and build.dir is the path for storing the build output files.

Then we declare the name of the web application, which is fax in our case.

We also define the master class path which contains the JAR files present in the WEB-INF/lib folder of the project. We also include the class files present in the build.dir in the master class path

The Javadoc target produces the javadoc required for the project and the usage target is used to print the common targets that are present in the build file.

The above example shows two deployment targets - deploy and the deploy war target

The deploy target copies the files from the web directory to the deploy directory preserving the last modified date time stamp. This is useful when deploying to a server that supports hot deployment.

The clean target clears all the previously built files.

The deploywar target builds the war file and then copies the war file to the deploy directory of the application server.

Deploying applications:

We are going to deploy the web application directly to the application's server deploy folder, then we are going to add few Ant targets to start and stop the services. Let us contnue with the Hello World fax web application. This is a continuation of the previous chapter, the new components are highlighted in red

build.properties

# Ant properties for building the springapp

appserver.home=c:\\install\\apache-tomcat-7.0.19
# for Tomcat 5 use $appserver.home}/server/lib
# for Tomcat 6 use $appserver.home}/lib
appserver.lib=${appserver.home}/lib

deploy.path=${appserver.home}/webapps

tomcat.manager.url=http://www.tutorialspoint.com:8080/manager
tomcat.manager.username=tutorialspoint
tomcat.manager.password=secret

build.xml:

<?xml version="1.0"?>

<project name="fax" basedir="." default="usage">
    <property file="build.properties"/>
    <property name="src.dir" value="src"/>
    <property name="web.dir" value="war"/>
    <property name="javadoc.dir" value="doc"/>
    <property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
    <property name="name" value="fax"/>

    <path id="master-classpath">
        <fileset dir="${web.dir}/WEB-INF/lib">
            <include name="*.jar"/>
        </fileset>
        <pathelement path="${build.dir}"/>
    </path>
   
    <target name="javadoc">
      <javadoc packagenames="faxapp.*" sourcepath="${src.dir}"
      destdir="doc" version="true" windowtitle="Fax Application">
        <doctitle><![CDATA[<h1>= Fax Application
          =</h1>]]></doctitle>
        <bottom><![CDATA[Copyright © 2011. All
          Rights Reserved.]]></bottom>
        <group title="util packages" packages="faxapp.util.*"/>
        <group title="web packages" packages="faxapp.web.*"/>
        <group title="data packages"
          packages="faxapp.entity.*:faxapp.dao.*"/>
      </javadoc>
    </target>

    <target name="usage">
        <echo message=""/>
        <echo message="${name} build file"/>
        <echo message="-----------------------------------"/>
        <echo message=""/>
        <echo message="Available targets are:"/>
        <echo message=""/>
        <echo message="deploy    --> Deploy application
          as directory"/>
        <echo message="deploywar --> Deploy application
          as a WAR file"/>
        <echo message=""/>
    </target>

    <target name="build" description="Compile main
      source tree java files">
        <mkdir dir="${build.dir}"/>
        <javac destdir="${build.dir}" source="1.5"
          target="1.5" debug="true"
          deprecation="false" optimize="false" failonerror="true">
            <src path="${src.dir}"/>
            <classpath refid="master-classpath"/>
        </javac>
    </target>

    <target name="deploy" depends="build"
      description="Deploy application">
        <copy todir="${deploy.path}/${name}"
          preservelastmodified="true">
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </copy>
    </target>

    <target name="deploywar" depends="build"
      description="Deploy application as a WAR file">
        <war destfile="${name}.war"
             webxml="${web.dir}/WEB-INF/web.xml">
            <fileset dir="${web.dir}">
                <include name="**/*.*"/>
            </fileset>
        </war>
        <copy todir="${deploy.path}" preservelastmodified="true">
            <fileset dir=".">
                <include name="*.war"/>
            </fileset>
        </copy>
    </target>
   

    <target name="clean" description="Clean output directories">
        <delete>
            <fileset dir="${build.dir}">
                <include name="**/*.class"/>
            </fileset>
        </delete>
    </target>
    <!-- ============================================================ -->
    <!-- Tomcat tasks -->
    <!-- ============================================================ -->

    <path id="catalina-ant-classpath">
        <!-- We need the Catalina jars for Tomcat -->
        <!--  * for other app servers - check the docs -->
        <fileset dir="${appserver.lib}">
            <include name="catalina-ant.jar"/>
        </fileset>
    </path>

    <taskdef name="install"
        classname="org.apache.catalina.ant.InstallTask">
        <classpath refid="catalina-ant-classpath"/>
    </taskdef>
    <taskdef name="reload"
        classname="org.apache.catalina.ant.ReloadTask">
        <classpath refid="catalina-ant-classpath"/>
    </taskdef>
    <taskdef name="list"
        classname="org.apache.catalina.ant.ListTask">
        <classpath refid="catalina-ant-classpath"/>
    </taskdef>
    <taskdef name="start"
        classname="org.apache.catalina.ant.StartTask">
        <classpath refid="catalina-ant-classpath"/>
    </taskdef>

 <taskdef name="stop"
         classname="org.apache.catalina.ant.StopTask">
        <classpath refid="catalina-ant-classpath"/>
    </taskdef>

    <target name="reload" description="Reload application in Tomcat">
        <reload url="${tomcat.manager.url}"
                 username="${tomcat.manager.username}"
                 password="${tomcat.manager.password}"
                 path="/${name}"/>
    </target>
</project>

In this exercise, we have used Tomcat as our application server. First, in the build properties file, we have defined some additional properties.

The appserver. home points to the installation path to the Tomcat application server.

The appserver.lib points to the library files in the Tomcat installation folder.

The deploy.path variable now points to the webapp folder in Tomcat.

Applications in Tomcat can be stopped and started using the Tomcat manager application. The URL for the manager application, username and password are also specified in the build.properties file. Next we declare a new CLASSPATH that contains the catalina-ant.jar. This jar file is required to execute Tomcat tasks through Apache Ant.

The catalina-ant.jar provides the following tasks:

Properties           Description
InstallTask           Installs a web application. Class Name: org.apache.catalina.ant.InstallTask
ReloadTask         Reload a web application. Class Name: org.apache.catalina.ant.ReloadTask
ListTask                Lists all web applications. Class Name: org.apache.catalina.ant.ListTask
StartTask             Starts a web application. Class Name: org.apache.catalina.ant.StartTask
StopTask              Stops a web application. Class Name: org.apache.catalina.ant.StopTask
ReloadTask         Reloads a web application without stopping. Class Name: org.apache.catalina.ant.ReloadTask
The reload task requires the following additional parameters. -
1) URL to the manager application
2)Username to restart the web application
3) Password to restart the web application
4)Name of the web application to be restarted

Let us issue the deploy-war command to copy the webapp to the Tomcat webapps folder and then let us reload the Fax Web application. The following outcome is the result of running the ant file:

C:\>ant deploy-war
Buildfile: C:\build.xml

BUILD SUCCESSFUL
Total time: 6.3 seconds

C:\>ant reload
Buildfile: C:\build.xml

BUILD SUCCESSFUL
Total time: 3.1 seconds
Once the above task is run, the web application is deployed and the web application is reloaded.

Executing Java code:

You can use Ant to execute java code. In this example below, the java class takes in an argument (administrator's email address) and sends out an email.

public class NotifyAdministrator
{
  public static void main(String[] args)
  {
    String email = args[0];
    notifyAdministratorviaEmail(email);
    System.out.println("Administrator "+email+" has been notified");
  }
  public static void notifyAdministratorviaEmail(String email)
  {
      //......
  }
}

Here is a simple build that executes this java class.

<?xml version="1.0"?>
<project name="sample" basedir="." default="notify">
  <target name="notify">
    <java fork="true" failonerror="yes" classname="NotifyAdministrator">
      <arg line="admin@test.com"/>
    </java>
  </target>
</project>
When the build is executed, it produces the following outcome:

C:\>ant
Buildfile: C:\build.xml

notify:
     [java] Administrator admin@test.com has been notified

BUILD SUCCESSFUL
Total time: 1 second
In this example, the java code does a simple thing - to send an email. We could have used the built in Ant task to do that. However, now that you have got the idea you can extend your build file to call java code that performs complicated things,

Eclipse Integration:

To integrate Ant into Eclipse:
- Make sure build.xml is part of your Java project and does not live in location taht is external to project.
- enable Ant view by going to Window>Show View>Other>Ant>Ant 
- open Project Explorer, drag the build.xml into the Ant view.

Clicking on targets, build/clean/usage will run Ant with target for you.
Clicking "fax" will execute default target-usage.

Ant eclipse plugin also comes with good editor for editiing build.xml files.
Editor is aware of build.xml schema and can assist you with code completion

To use Ant editor, right click your build.xml and select open with>Ant Editor.

Ant editor lists the target in right hand side.
The target list serves as bookmark that allows you to jump into editing particular target.

JUnit integration:

Junit is the commonly used unit testing framework for development based on Java. It is easy to use and easy to extend. There are a number of JUnit extensions available. If you are unfamiliar with Junit, you should download junit from www.junit.org and read the junit manual.

This tutorial discusses about executing the junit tests using Ant. Ant makes this straight forward through the Junit task.

Presented below are the attribute of the junit task.

Properties           Description
dir           Where to invoke the VM from. This is ignored when fork is disabled.
jvm        Command used to invoke the JVM. This is ignored when fork is disabled.
fork        Runs the test in a separate JVM
errorproperty    The name of the property to set if there is a Junit error
failureproperty The name of the property to set if there is a Junit failure
haltonerror         Stops execution when a test error occurs
haltonfailure      Stops execution when a failure occurs
printsummary   Advices Ant to display simple statistics for each test
showoutput       Adivces Ant tosend the output to its logs and formatters
tempdir                Path to the temporary file that Ant will use
timeout                Exits the tests that take longer to run than this setting (in milliseconds).
Let us continue the theme of the Hello World Fax web applicaiton and add a junit target.
The below example shows a simple junit test execution
<target name="unittest">
  <junit haltonfailure="true" printsummary="true">
    <test name="com.tutorialspoint.UtilsTest"/>
  </junit>
</target>
The above example shows the execution of Junit on the com.tutorialspoint.UtilsTest junit class. Running the above will produce the following output
test:
[echo] Testing the application
[junit] Running com.tutorialspoint.UtilsTest
[junit] Tests run: 12, Failures: 0, Errors: 0, Time elapsed: 16.2 sec

BUILD PASSED

No comments:

Post a Comment