Java: Ant: Simple script

What is Ant?

Ant is a utility, which helps us deploy on our local Application Server (e.g. Tomcat), for development purposes.

Ant saves time for continuous changes and continuous deployments.

We just work once to write the xml and then we run a script for deployment of our .war file.

A sample of ant xml is:

<?xml version="1.0" encoding="UTF-8"?>

<project default="warTarget" basedir=".">

    <property name="tomcat" value="D:/apache-tomcat-7.0.39" />
    <property name="tomcat.deployment" value="${tomcat}/webapps" />
    <property name="tomcat.bin" value="${tomcat}/bin" />
    <property name="base" value="." />
    <property name="source" value="${base}/src" />
    <property name="webinf" value="${base}/WebContent/WEB-INF" />
    
    <target name="warTarget">
        <copy todir="${webinf}/classes">
            <fileset dir="${source}" />
        </copy>
        <copy todir="${webinf}/classes/resources">
            <fileset dir="${base}/Resources" />
        </copy>
        <war warfile="Lexicon.war" needxmlfile="false">
            <fileset dir="${source}" />
            <fileset dir="${webinf}" />
        </war>
        <antcall target="deployTomcat" />
    </target>
    
    <target name="deployTomcat">
        <copy file="${base}/Lexicon.war" todir="${tomcat.deployment}" />
        <antcall target="startTomcat" />
    </target>

    <target name="startTomcat">
        <exec executable="${tomcat.bin}/startup.bat" />
    </target>
    
    <target name="stopTomcat">
        <exec executable="${tomcat.bin}/shutdown.bat" />
    </target>
    
</project>

Name this script build.xml and place it under the root project folder (at the same level with “src” directory).

This script has 4 steps:

  • warTarget: Creates the war, first copying files from some locations and then calls the next step, which is deployTomcat
  • deployTomcat: Copies the .war to Tomcat, then calls startTomcat
  • startTomcat: Starts Tomcat
  • stopTomcat: Is not called automatically and not used (you can terminate Tomcat by closing it’s window with CTRL+C)

We can run this xml with the following .bat file:

d:
cd D:\eclipse-juno-64bit\workspace\Lexicon
set CATALINA_HOME=D:/apache-tomcat-7.0.39
ant

Ant installation: Just unzip the folder downloaded from Apache Ant site and then put the Ant’s /bin directory into PATH environment variable.




Leave a Reply