Introduction to Ant
      @brownylin
Why

• Many IDEs have their own build
  systems, so why is Ant important to
  learn and use


• Answer:
 ‣ Eclipse may actually be using Ant
 ‣ Not just a build tool, must have for automation
What is Ant?



• Ant   Java
               Make    Make
           Java
Outline



•A First Ant Build
• Ant and Eclipse
• Ant programming
Prerequisite


Last login: Tue Aug 9 13:35:09 on ttys002
brownylins-MacBook:~ brownylin$ ant -version
Apache Ant(TM) version 1.8.2 compiled on June 3 2011
brownylins-MacBook:~ brownylin$ javac -version
javac 1.6.0_26
brownylins-MacBook:~ brownylin$ java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03-383-11A511)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-383, mixed mode)
brownylins-MacBook:~ brownylin$
Main.java


package oata;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
The Java Way
                   compile and run
md buildclasses
javac -sourcepath src -d buildclasses srcoataHelloWorld.java
java -cp buildclasses oata.HelloWorld




                         package
echo Main-Class: oata.HelloWorld>myManifest
md buildjar
jar cfm buildjarHelloWorld.jar myManifest -C buildclasses .
java -jar buildjarHelloWorld.jar
The Ant Way
A Simple build.xml


<?xml version="1.0"?>
<project name="firstbuild" default="compile" >
   <target name="compile">
      <javac srcdir="." />
      <echo>compilation complete!</echo>
   </target>
</project>
Build


brownylins-MacBook:FirstBuild brownylin$ ant
Buildfile: /Users/brownylin/Desktop/AntPlay/FirstBuild/build.xml

compile:
    [javac] Compiling 1 source file
     [echo] compilation complete!

BUILD SUCCESSFUL
Total time: 0 seconds
-verbose
Run



brownylins-MacBook:FirstBuild brownylin$ java Main a b .
a
b
.
Doing so shows the advantage of placing intermediate code into the build directory:
you can build a JAR file from it without having to list what files are included. This is
because all files in the directory tree should go in the JAR file, which, conveniently, is


                  Structure
the default behavior of the <jar> task.
    With the destination directories defined, we’ve now completed the directory
structure of the project, which looks like the illustration in figure 2.2. When the build




                                            Figure 2.2
                                            The directory layout for our project—
                                            keeping source separate from generated
                                            files. The shaded directories and files are
                                            created during the build.
<?xml version="1.0" ?>
<project name="structured" default="archive" >

   <target name="init">
      <mkdir dir="build/classes" />
      <mkdir dir="dist" />
   </target>

   <target name="compile" depends="init" >
      <javac srcdir="src" destdir="build/classes" />
   </target>

   <target name="archive" depends="compile" >
      <jar destfile="dist/project.jar" basedir="build/
classes" />
   </target>

   <target name="clean" depends="init">
      <delete dir="build" />
      <delete dir="dist" />
   </target>

</project>
Run


brownylins-MacBook:StructureBuild brownylin$ java -cp build/classes
org.antbook.welcome.Main a b .

a
b
.
Practice




• Tutorial: Hello World with Apache Ant
Outline



• A First Ant Build
•Ant and Eclipse
• Ant programming
Eclipse integrated with Ant



• Apache Ant 101: Make Java builds a
  snap

• Make Ant easy with Eclipse
Outline



• A First Ant Build
• Ant and Eclipse
•Ant programming
Introduction

• Encapsulate each activity in the build
  system into a high-level task

<target name="all">
    <mkdir dir="pkg"/>
    <jar basedir="obj" destfile="pkg/prog.jar"/>
    <copy file="index.txt" tofile="pkg/index.txt"/>
</target>
Ant Programming

• Think Ant script as a sequence of build
  tasks

• XML-based format, default naming
  build.xml

• Each Ant’s XML file contains a project
• Each project contains one or more
  targets that represent something the
  user can build
An Example (1/2)
<project name="ant-project" default="all">

    <property name="country" value="New Zealand"/>
    <property name="city" value="Christchurch"/>

    <target name="print-city">
        <echo message="The nicest place in the world is"/>
        <echo message="${city}, ${country}"/>
    </target>

    <target name="print-math">
        <echo message="Two plus two equals four"/>
    </target>

    <target name="all" depends="print-city, print-math">
        <echo message="Thank you!"/>
    </target>

</project>
An Example (2/2)

• Result
     $ ant
     Buildfile: build.xml
     print-city:
          [echo] The nicest place in the world
     is
          [echo] Christchurch, New Zealand
     print-math:
          [echo] Two plus two equals four
     all:
          [echo] Thank you!
     BUILD SUCCESSFUL
     Total time: 218 milliseconds
Using Target (1/4)

• A target is a convenient way to group
  tasks that need to be executed
  sequentially

              ant   compile
              ant   jar
              ant   package
              ant   clean
              ant   javadoc


• The name of an Ant target isn’t
  related to the name of any disk files
Using Target (2/4)

• Internal target
 ‣ Never invoked directly from the command line


<target name="java" depends="init, make-directories">

    ...

</target>
Using Target (3/4)

• Conditional
  <property name="log-enabled" value="1"/>

  <target name="append-to-log" if="log-enabled">
      <echo message="Appending..."/>
  </target>



• Direct execute target
  <target name="java" depends="init, make-dir">
      ...
      <antcall target="check-rules"/>
      ...
  </target>
Using Target (4/4)

• across multiple build files
  <target name="java" depends="init, make-dir">
      ...
      <ant antfile=”utilities.xml” target="check"/>
      ...
  </target>



• <antcall> performance suffers
• <import>
 ‣ Direct insertion
 ‣ Inherit a set of targets and override
Defining Properties (1/3)

• Defined by different ways
 1. As a string
<property name="wife" value="Grace"/>
<property name="dog" value="Stan"/>
<property name="request"
        value="${wife}, please take ${dog} for a walk"/>


 2. As a file system location

<property name="obj-dir" location="obj/i386/debug"/>

${obj-dir} evaluates to
C:UsersPeterworkspaceAnt_Buildspropertiesobji386debug
Defining Properties (2/3)

 • Defined by different ways
    3. Automatically set by the runtime environment
<echo>${os.name}</echo>   // Windows Vista
<echo>${ant.file}</echo>  // C:UsersPeterworkspaceAnt_Builds
                             propertiesbuild.xml
<echo>${user.name}</echo> // Peter


    4. As the result of a <condition> task (is-
       windows set true if system is windows)
<condition property="is-windows">
    <contains string="${os.name}" substring="Windows"/>
</condition>
Defining Properties (3/3)

• Defined by different ways
 5. Defined on the user’s command line (manually
    specifying vs. hard-coding into the build.xml)

        $ ant -Dname=Jones print-name




 6. Loaded from an external properties file
    (externalize a common set of properties)

      <loadproperties srcfile="values.prop"/>
Properties Scope

• Available after defined (top-level or
  inside a target)

• Can be defined only once in a given
  project

• <ant> and <antcall> tasks
 ‣ Enable you to pass property values into the
    newly invoked target (override any previous
    definition only during the execution of that
    target)
Built-In and Optional Tasks

• Basic file operations
• Archiving (.jar, .zip, etc...)
• The compilation of Java code
• The automatic generation of API
  documentation

• Direct access to version-control tools
• Build lifecycle features (build version
  numbers, sending email messages, and
  playing sounds)
uses the B.class file without recompiling it. As a result, nothing that B.java
imports or extends is ever recompiled.

         <javac> and <depend>
   This algorithm works properly in many cases, but it causes incorrect builds in
other cases. (And this is where things get complex.) Imagine a case in which class
A imports class B, which then imports class C (see Figure 7.2). If both A.java
and C.java have been recently modified, the Java compiler is asked to recom-
pile both those files. When compiling class A, the compiler examines B.class
(because B is <depend srcdir="${src}" destdir="${obj}" /> with respect
               imported by A), but because B.class is up-to-date
to B.java, it’s never recompiled. Class Adestdir="${obj}"/>
              <javac srcdir="${src}" therefore uses the existing version of
class B.


                        imports                           imports
         A.java                            B.java                              C.java



recompiles                    examines                              recompiles



         A.class                           B.class                             C.class

Figure 7.2 The <javac> task doesn’t recompile B.java, even though C.java has
changed.
<chomd>, <copy>

• <chmod>
 ‣ Sets the access permissions on a file or
   directory

• <copy>
 ‣ Similar to the Windows copy command and the
   UNIX cp command
<fileset>, <patternset>,
          <condtion>
• Selecting Multiple Files and Directories
    <copy todir="pkg" flatten="true">
        <fileset dir="src">
            <include name="**/*.jpg"/>
            <include name="**/*.png"/>
            <exclude name="**/*flag*"/>
        </fileset>

        <fileset dir="lib">
            <include name="**/*.gif"/>
            <exclude name="**/*flag*"/>
        </fileset>
    </copy>
Extending Ant

•   <exec>: enables you to invoke a shell command

•   <java>: invoke an arbitrary collection of Java
    code by specifying the class path and class
    name

•   <macrodef>: create a new type of task, with the
    definition of that task written in Ant syntax

•   <taskdef>: enables you to implement a task
    using the full power of the Java language

•   <script>: permits code from other scripting
    languages to be directly embedded inside a
    build.xml file (Javascript, Python and Ruby)
Reference
Thanks you :)

Introduction to Apache Ant

  • 1.
  • 2.
    Why • Many IDEshave their own build systems, so why is Ant important to learn and use • Answer: ‣ Eclipse may actually be using Ant ‣ Not just a build tool, must have for automation
  • 3.
    What is Ant? •Ant Java Make Make Java
  • 4.
    Outline •A First AntBuild • Ant and Eclipse • Ant programming
  • 5.
    Prerequisite Last login: TueAug 9 13:35:09 on ttys002 brownylins-MacBook:~ brownylin$ ant -version Apache Ant(TM) version 1.8.2 compiled on June 3 2011 brownylins-MacBook:~ brownylin$ javac -version javac 1.6.0_26 brownylins-MacBook:~ brownylin$ java -version java version "1.6.0_26" Java(TM) SE Runtime Environment (build 1.6.0_26-b03-383-11A511) Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-383, mixed mode) brownylins-MacBook:~ brownylin$
  • 6.
    Main.java package oata; public classHelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
  • 7.
    The Java Way compile and run md buildclasses javac -sourcepath src -d buildclasses srcoataHelloWorld.java java -cp buildclasses oata.HelloWorld package echo Main-Class: oata.HelloWorld>myManifest md buildjar jar cfm buildjarHelloWorld.jar myManifest -C buildclasses . java -jar buildjarHelloWorld.jar
  • 8.
  • 9.
    A Simple build.xml <?xmlversion="1.0"?> <project name="firstbuild" default="compile" > <target name="compile"> <javac srcdir="." /> <echo>compilation complete!</echo> </target> </project>
  • 10.
    Build brownylins-MacBook:FirstBuild brownylin$ ant Buildfile:/Users/brownylin/Desktop/AntPlay/FirstBuild/build.xml compile: [javac] Compiling 1 source file [echo] compilation complete! BUILD SUCCESSFUL Total time: 0 seconds
  • 11.
  • 12.
  • 13.
    Doing so showsthe advantage of placing intermediate code into the build directory: you can build a JAR file from it without having to list what files are included. This is because all files in the directory tree should go in the JAR file, which, conveniently, is Structure the default behavior of the <jar> task. With the destination directories defined, we’ve now completed the directory structure of the project, which looks like the illustration in figure 2.2. When the build Figure 2.2 The directory layout for our project— keeping source separate from generated files. The shaded directories and files are created during the build.
  • 14.
    <?xml version="1.0" ?> <projectname="structured" default="archive" > <target name="init"> <mkdir dir="build/classes" /> <mkdir dir="dist" /> </target> <target name="compile" depends="init" > <javac srcdir="src" destdir="build/classes" /> </target> <target name="archive" depends="compile" > <jar destfile="dist/project.jar" basedir="build/ classes" /> </target> <target name="clean" depends="init"> <delete dir="build" /> <delete dir="dist" /> </target> </project>
  • 15.
    Run brownylins-MacBook:StructureBuild brownylin$ java-cp build/classes org.antbook.welcome.Main a b . a b .
  • 16.
    Practice • Tutorial: HelloWorld with Apache Ant
  • 17.
    Outline • A FirstAnt Build •Ant and Eclipse • Ant programming
  • 18.
    Eclipse integrated withAnt • Apache Ant 101: Make Java builds a snap • Make Ant easy with Eclipse
  • 19.
    Outline • A FirstAnt Build • Ant and Eclipse •Ant programming
  • 20.
    Introduction • Encapsulate eachactivity in the build system into a high-level task <target name="all"> <mkdir dir="pkg"/> <jar basedir="obj" destfile="pkg/prog.jar"/> <copy file="index.txt" tofile="pkg/index.txt"/> </target>
  • 21.
    Ant Programming • ThinkAnt script as a sequence of build tasks • XML-based format, default naming build.xml • Each Ant’s XML file contains a project • Each project contains one or more targets that represent something the user can build
  • 22.
    An Example (1/2) <projectname="ant-project" default="all"> <property name="country" value="New Zealand"/> <property name="city" value="Christchurch"/> <target name="print-city"> <echo message="The nicest place in the world is"/> <echo message="${city}, ${country}"/> </target> <target name="print-math"> <echo message="Two plus two equals four"/> </target> <target name="all" depends="print-city, print-math"> <echo message="Thank you!"/> </target> </project>
  • 23.
    An Example (2/2) •Result $ ant Buildfile: build.xml print-city: [echo] The nicest place in the world is [echo] Christchurch, New Zealand print-math: [echo] Two plus two equals four all: [echo] Thank you! BUILD SUCCESSFUL Total time: 218 milliseconds
  • 24.
    Using Target (1/4) •A target is a convenient way to group tasks that need to be executed sequentially ant compile ant jar ant package ant clean ant javadoc • The name of an Ant target isn’t related to the name of any disk files
  • 25.
    Using Target (2/4) •Internal target ‣ Never invoked directly from the command line <target name="java" depends="init, make-directories"> ... </target>
  • 26.
    Using Target (3/4) •Conditional <property name="log-enabled" value="1"/> <target name="append-to-log" if="log-enabled"> <echo message="Appending..."/> </target> • Direct execute target <target name="java" depends="init, make-dir"> ... <antcall target="check-rules"/> ... </target>
  • 27.
    Using Target (4/4) •across multiple build files <target name="java" depends="init, make-dir"> ... <ant antfile=”utilities.xml” target="check"/> ... </target> • <antcall> performance suffers • <import> ‣ Direct insertion ‣ Inherit a set of targets and override
  • 28.
    Defining Properties (1/3) •Defined by different ways 1. As a string <property name="wife" value="Grace"/> <property name="dog" value="Stan"/> <property name="request" value="${wife}, please take ${dog} for a walk"/> 2. As a file system location <property name="obj-dir" location="obj/i386/debug"/> ${obj-dir} evaluates to C:UsersPeterworkspaceAnt_Buildspropertiesobji386debug
  • 29.
    Defining Properties (2/3) • Defined by different ways 3. Automatically set by the runtime environment <echo>${os.name}</echo> // Windows Vista <echo>${ant.file}</echo> // C:UsersPeterworkspaceAnt_Builds propertiesbuild.xml <echo>${user.name}</echo> // Peter 4. As the result of a <condition> task (is- windows set true if system is windows) <condition property="is-windows"> <contains string="${os.name}" substring="Windows"/> </condition>
  • 30.
    Defining Properties (3/3) •Defined by different ways 5. Defined on the user’s command line (manually specifying vs. hard-coding into the build.xml) $ ant -Dname=Jones print-name 6. Loaded from an external properties file (externalize a common set of properties) <loadproperties srcfile="values.prop"/>
  • 31.
    Properties Scope • Availableafter defined (top-level or inside a target) • Can be defined only once in a given project • <ant> and <antcall> tasks ‣ Enable you to pass property values into the newly invoked target (override any previous definition only during the execution of that target)
  • 32.
    Built-In and OptionalTasks • Basic file operations • Archiving (.jar, .zip, etc...) • The compilation of Java code • The automatic generation of API documentation • Direct access to version-control tools • Build lifecycle features (build version numbers, sending email messages, and playing sounds)
  • 33.
    uses the B.classfile without recompiling it. As a result, nothing that B.java imports or extends is ever recompiled. <javac> and <depend> This algorithm works properly in many cases, but it causes incorrect builds in other cases. (And this is where things get complex.) Imagine a case in which class A imports class B, which then imports class C (see Figure 7.2). If both A.java and C.java have been recently modified, the Java compiler is asked to recom- pile both those files. When compiling class A, the compiler examines B.class (because B is <depend srcdir="${src}" destdir="${obj}" /> with respect imported by A), but because B.class is up-to-date to B.java, it’s never recompiled. Class Adestdir="${obj}"/> <javac srcdir="${src}" therefore uses the existing version of class B. imports imports A.java B.java C.java recompiles examines recompiles A.class B.class C.class Figure 7.2 The <javac> task doesn’t recompile B.java, even though C.java has changed.
  • 34.
    <chomd>, <copy> • <chmod> ‣ Sets the access permissions on a file or directory • <copy> ‣ Similar to the Windows copy command and the UNIX cp command
  • 35.
    <fileset>, <patternset>, <condtion> • Selecting Multiple Files and Directories <copy todir="pkg" flatten="true"> <fileset dir="src"> <include name="**/*.jpg"/> <include name="**/*.png"/> <exclude name="**/*flag*"/> </fileset> <fileset dir="lib"> <include name="**/*.gif"/> <exclude name="**/*flag*"/> </fileset> </copy>
  • 36.
    Extending Ant • <exec>: enables you to invoke a shell command • <java>: invoke an arbitrary collection of Java code by specifying the class path and class name • <macrodef>: create a new type of task, with the definition of that task written in Ant syntax • <taskdef>: enables you to implement a task using the full power of the Java language • <script>: permits code from other scripting languages to be directly embedded inside a build.xml file (Javascript, Python and Ruby)
  • 37.
  • 38.