Java Training Introduction to Ant

Document Sample
Java Training Introduction to Ant Powered By Docstoc
					         Java Training
      Introduction to Ant
         Written by Jeff Smith
Portions borrowed from the Apache Ant Website
                     What is Ant?

   Apache Ant is the defacto standard for building (compiling)
    Java applications. It is similar to make, but more powerful.
   Ant is free
   Ant can also be used for simple scripting such as copying,
    moving, and deleting files, creating directories, deleting
    directories, zipping files, etc.
   Ant is cross-platform compatible (Windows, Linux, Solaris,
    HP Unix, MacOS X, etc.)
   Ant can run from the command line
   Ant can be integrated into some IDEs (such as Eclipse)
                    Where is Ant?


   Ant can be downloaded from
     http://ant.apache.org/manual/index.html
     You can either download the latest semi-stable release
       or the latest stable release. We'll use the latest stable
       version.
     You can also download the source code for Ant if you
       are curious
     You need to have a JDK (Java Dev Kit) installed on your
       computer (1.4 or later, recommended)
                     Installing Ant


  Download Ant binary distribution (.zip or .tar)
 Unzip it
 Add environment variable to your computer
JAVA_HOME=<path to top level JDK>

For example:
JAVA_HOME=C:\Program Files\Java\jdk1.5.0_07
               Compiling With Ant



   For convenience, you can certainly compile your code and
    test it with your IDE, but you should create an Ant file for
    your project because
     It makes your project more portable
     It makes it easy for other developers using other IDEs to
        compile your code
    Buildfiles and Command Line -1

   Buildfiles (or Ant scripts) are xml files and are usually
    called build.xml
   To execute a buildfile, you can type "ant" (without the
    quotes) from a command window whose current directory
    contains the file build.xml
     this executes the default target which usually compiles
        (builds) your application
     you must have Ant in the operating system path and
        have installed a JDK
    Buildfiles and Command Line -2
   To execute a buildfile with a name other than build.xml, you
    pass in the buildfile name at the command line:
     ant -buildfile mybuildfile.xml
     it is recommended that you use the default name,
       build.xml, so it is easily identifiable as an ant buildfile.

   To execute a target (other than the default), you type
    something like:
     "ant dist" (to create distributable file)
     "ant javadoc" (to create javadoc documentation for
       project)
     this assumes you named your targets "dist" and
       "javadoc"
                        Targets -1
   Targets
     Targets are composed of task elements (things to do).
     Typically you have a target for compiling your project
       and a separate target for building a distributable
       (perhaps a jar file).
     You may also have a target for cleaning up (deleting)
       temporary directories used during the build
     Targets can depend on other targets. You can't execute
       the distributable task, for example, before you execute
       the compile task.
        there is a special depends attribute in the target
          entry that specifies any dependencies.
        if your distributable task is executed (and it includes
          a depends attribute for compile), it will execute the
          compile task first
                        Targets -2
  Targets (depends)
For example:
<target name="A"/>
<target name="B" depends="A"/>
<target name="C" depends="B"/>
<target name="D" depends="C,B,A"/>

   If we execute target D, first A is executed, then B, then C,
    and finally D.

   A target gets executed only once, even when more than one
    target depends on it
                        Targets -3
  Description attribute
    This optional attribute allows you describe your project.
      This description appears if the Ant user adds the
      command line option, "-projecthelp". This command line
      option also lists all the available targets in the buildfile.
    For example:
<description>
   NFS Monitor verifies that a cross mounted (PCNFS) drive is
   available by constantly polling it. support.
</description>

To view this description from the command line:
ant -projecthelp
                    Timestamp -1
   Timestamp attribute (tstamp)
     This optional attribute is generally placed in the
        initialization target (the first target executed).
     It lets you know how long the build took to complete
     On my last project (a big one), it took 3 minutes to build
        the project
     For example:
<target name="init" description="create build dir...">
    <!-- create the timestamp -->
    <tstamp/>
    <!-- create the build dir structure used by compile -->
    <mkdir dir="${build}"/>
</target>
                         Tasks -1
   Targets are composed of Tasks
     A task is simply a block of code to be executed. The task
       tag must be inside of an outer target tag
     A typical task might be "create this directory" or "compile
       the code in this directory"
     Tasks look like:


<name attribute1="value1" attribute2="value2" ... />
where name is task name (like "javac")
                    Comments -1
   Comments
     Adding comments to your buildfiles will make it easier for
      another programmer to understand it.
     Buildfiles employ the standard xml comments:


<!-- comment goes here -->

You can add asterisk characters if you like:

<!-- ***** comment goes here ***** -->
                     Properties -1
   Properties
     You can declare properties for your ant projects. These
       properties are declared inside the <project> tag, but
       outside any <target> tags.
     A property has a name and a value (kind of like a
       variable).
     You can use properties in the value of task attributes
       (tags). For example, instead of hardcoding a path like
       "/home/src/nfs/" in several targets in your buildfile, you
       could declare a property to store the path and then
       supply the path property in several places. Later on, if
       you needed to change the path, you could do it in just
       ONE place (the property tag), instead of for every target.
                      Properties -2
   Properties Example
     You can specify a build directory like so:
    <property name="build" location="/home/src/nfs/build"/>

     To use this property in the value of a task attribute, you
      use the ${property_name} syntax:
    <mkdir dir="${build}"/>
                     Properties -3
   Built in Properties
     Ant has several built in properties (you don't have to
       define yourself).
          Specifying A Classpath -1
   In your compile task, you may need to specify a classpath
    so the compiler can find external libraries you are using (like
    JavaMail).
   The java compiler (javac) looks in the standard JDK libraries
    as well as the classes specified in the classpath whenever it
    compiles code. We need to a way to add external libraries
    to the classpath within our Ant script.
   Ant scripts (build files) specify additional classes through a
    special path tag. For each additional directory you want to
    add to the classpath, you need to add a <pathelement> tag

(code example on next slide)
           Specifying A Classpath -2

   Classpath example:

<path id="build.classpath">
    <pathelement location="lib/mail.jar"/>
    <pathelement location="lib/activation.jar"/>
</path>

<target name="compile" depends="init" description="compile sourcecode">
    <javac srcdir="${src}" destdir="${build}">
        <classpath refid="build.classpath"/>
    </javac>
</target>
            Creating a Distributable -1


   Typically, you will combine all your class files into one, easy
    to work with, jar file. To achieve this, you will create a
    distributable task in your build.xml that executes the jar
    task. Your jar task might look like:

<jar manifest="manifest.txt" jarfile="${dist}/nfs.jar" basedir="${build}"/>


   For more on the manifest attribute, see the next slide
           Creating a Distributable -2
   manifest.txt makes the JAR runnable, since it specifies
     Class-Path –external libraries required to run
     Main-Class –the class containing the main() to run
   The manifest.txt file could be in the same dir as build.xml
    and might look something like:

Manifest-Version: 1.0
Class-Path: activation.jar mail.jar
Main-Class: com.cexp.wms.nfsmonitor.NFSMonitor

Note: If Class-Path is blank (no JARS required), make sure you have a
    space character after the colon:
Class-Path: <space char>
                 Sample Build File -1
<project name="NFSMonitor" default="dist" basedir=".">
    <description>
        NFS Monitor verifies that a cross mounted (PCNFS) drive is
        available by constantly polling it (with a configurable timeout
        between polls). If the drive becomes unavailable, NFS Monitor
        sends an email to app support.
    </description>

    <path id="build.classpath">
        <pathelement location="lib/mail.jar"/>
        <pathelement location="lib/activation.jar"/>
    </path>
                     Sample Build File -2
     <property name="app.name" value="nfsmonitor"/>
     <property name="src" location=“."/>
     <property name="build" location="build"/>
     <property name="dist" location="dist"/>
     <property name="javadocdir" location="docs/javadocs"/>

<!-- ******************** init (create build dir) ******************** -->

     <target name="init" description="create build dir...">
         <!-- create the timestamp -->
         <tstamp/>

          <!-- create the build dir structure used by compile -->
          <mkdir dir="${build}"/>
     </target>
                    Sample Build File -3


<!-- ******** compile (compiles all code in src tree to build dir) ************* -->

    <target name="compile" depends="init" description="compile sourcecode">
         <javac srcdir="${src}" destdir="${build}">
                  <classpath refid="build.classpath"/>
         </javac>
    </target>
                     Sample Build File -4

<!-- *********** dist (builds runnable jar and copies properties file to dist dir) ***** -->

<target name="dist" depends="compile" description="generate the distribution">
  <mkdir dir="${dist}"/>
  <jar manifest="manifest.txt" jarfile="${dist}/NFSMonitor.jar" basedir="${build}"/>
  <copy todir="${dist}">
    <fileset dir="${lib}"/>
  </copy>
  <copy file="src/com/cexp/wms/nfsmonitor/nfsmonitor.properties" todir="${dist}"/>
  <copy file="run.cmd" todir="${dist}"/>
  <delete dir="${build}"/>
</target>
                    Sample Build File -5
<!-- ******************** javadoc (generate javadoc html files) **************** -->

    <target name="javadoc" description="generate javadocs">
     <mkdir dir="${javadocdir}" />
     <javadoc packagenames="com.*"
           private="true"
           destdir="${javadocdir}"
           author="true"
           version="true">
       <sourcepath>
        <pathelement path="${src}"/>
       </sourcepath>
     </javadoc>
    </target>
                    Sample Build File -6


<!-- **************** clean (remove build directories) ***************** -->

    <target name="clean" description="clean up">
         <delete dir="${build}"/>
         <delete dir="${dist}"/>
         <delete dir="${javadocs}"/>
    </target>
</project>
               Sample Build File -7
   Ant Commands For This Sample build.xml
     To build (compile) the project and create the dist:
       ant
       To remove the build and javadocs directories
        ant clean
       To generate Javadoc documentation
        ant javadoc
       To execute the application (from the jar file)
        java -jar NFSMonitor.jar
   You can view this sample ant build file in its entirety at:
http://expressway2.cexp.com/info_services/D&L_Systems/java_ant.htm
      Project (Directory) Structure -1


   It is easier to work on other people's code when the project
    directory structure is familiar (and consistent)
   Typically, the top level directory contains the Ant files
     build.xml (Ant build file)
     manifest.txt (to specify required any JARS or a main
         class for a runnable JAR)
     Any optional readme or .cmd files
      Project (Directory) Structure -2
   Under the top directory you should have the following
    subdirectories
     dist - distributable directory contains all the files required
       to RUN or use your program (e.g. JAR files, properties
       files, image files, etc.)
     docs - project documents which may be split up into
       multiple subdirectories. One subdirectory should be
       called javadocs.
     lib - library directory contains any libraries (JAR files)
       required to compile and distribute your program
     src - top level of your source code. If you are using
       Eclipse, your Eclipse project file goes here.
      Project (Directory) Structure -3

   Here is a sample directory hierarchy for an ArchivePurge
    project
                         Exercise
Create a directory structure for your Shapes project
(moving the source code under a src directory).
Create an Ant script to build your Shapes project. Your Ant
script should provide targets for compiling the classes, creating
the distributable (a runnable JAR in the dist directory) and for
generating the javadocs.

Try to execute your distributable (runnable JAR) from the
command line:
 java –jar shapesPrj.jar

Try running the other targets (clean and javadoc)
    Importing Ant project into Eclipse
   Run Eclipse
   File Menu/New Project
   Java Project From Existing Ant BuildFile




   Navigate to build.xml file, click OK