SlideShare ist ein Scribd-Unternehmen logo
1 von 38
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 :)

Weitere ähnliche Inhalte

Was ist angesagt?

EclipseMAT
EclipseMATEclipseMAT
EclipseMAT
Ali Bahu
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 

Was ist angesagt? (20)

Intro to-ant
Intro to-antIntro to-ant
Intro to-ant
 
Introduction to Apache Ant
Introduction to Apache AntIntroduction to Apache Ant
Introduction to Apache Ant
 
Java build tool_comparison
Java build tool_comparisonJava build tool_comparison
Java build tool_comparison
 
An introduction to maven gradle and sbt
An introduction to maven gradle and sbtAn introduction to maven gradle and sbt
An introduction to maven gradle and sbt
 
Mastering Maven 2.0 In 1 Hour V1.3
Mastering Maven 2.0 In 1 Hour V1.3Mastering Maven 2.0 In 1 Hour V1.3
Mastering Maven 2.0 In 1 Hour V1.3
 
Maven 3.0 at Øredev
Maven 3.0 at ØredevMaven 3.0 at Øredev
Maven 3.0 at Øredev
 
Introduction To Ant
Introduction To AntIntroduction To Ant
Introduction To Ant
 
Ant tutorial
Ant tutorialAnt tutorial
Ant tutorial
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
EclipseMAT
EclipseMATEclipseMAT
EclipseMAT
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Apache ant
Apache antApache ant
Apache ant
 
Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
 
Introduction To Ant1
Introduction To  Ant1Introduction To  Ant1
Introduction To Ant1
 
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
dJango
dJangodJango
dJango
 
Custom deployments with sbt-native-packager
Custom deployments with sbt-native-packagerCustom deployments with sbt-native-packager
Custom deployments with sbt-native-packager
 
Play Framework workshop: full stack java web app
Play Framework workshop: full stack java web appPlay Framework workshop: full stack java web app
Play Framework workshop: full stack java web app
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
 

Andere mochten auch (6)

Apache Ant
Apache AntApache Ant
Apache Ant
 
Apache ANT
Apache ANTApache ANT
Apache ANT
 
ANT
ANTANT
ANT
 
Apache Ant
Apache AntApache Ant
Apache Ant
 
Apache ANT vs Apache Maven
Apache ANT vs Apache MavenApache ANT vs Apache Maven
Apache ANT vs Apache Maven
 
Manen Ant SVN
Manen Ant SVNManen Ant SVN
Manen Ant SVN
 

Ähnlich wie Introduction to Apache Ant

Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
Tino Isnich
 
How to start using Scala
How to start using ScalaHow to start using Scala
How to start using Scala
Ngoc Dao
 
Gradle - time for a new build
Gradle - time for a new buildGradle - time for a new build
Gradle - time for a new build
Igor Khotin
 

Ähnlich wie Introduction to Apache Ant (20)

Ant_quick_guide
Ant_quick_guideAnt_quick_guide
Ant_quick_guide
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
 
Build Scripts
Build ScriptsBuild Scripts
Build Scripts
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012
 
How to start using Scala
How to start using ScalaHow to start using Scala
How to start using Scala
 
GradleFX
GradleFXGradleFX
GradleFX
 
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
 
IBM Index 2018 Conference Workshop: Modernizing Traditional Java App's with D...
IBM Index 2018 Conference Workshop: Modernizing Traditional Java App's with D...IBM Index 2018 Conference Workshop: Modernizing Traditional Java App's with D...
IBM Index 2018 Conference Workshop: Modernizing Traditional Java App's with D...
 
Improving your Gradle builds
Improving your Gradle buildsImproving your Gradle builds
Improving your Gradle builds
 
Introduction to Maven
Introduction to MavenIntroduction to Maven
Introduction to Maven
 
Simple build tool
Simple build toolSimple build tool
Simple build tool
 
DCSF19 Dockerfile Best Practices
DCSF19 Dockerfile Best PracticesDCSF19 Dockerfile Best Practices
DCSF19 Dockerfile Best Practices
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with Gradle
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with Gradle
 
Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]
 
The Fairy Tale of the One Command Build Script
The Fairy Tale of the One Command Build ScriptThe Fairy Tale of the One Command Build Script
The Fairy Tale of the One Command Build Script
 
Gradle - time for a new build
Gradle - time for a new buildGradle - time for a new build
Gradle - time for a new build
 
Scala, docker and testing, oh my! mario camou
Scala, docker and testing, oh my! mario camouScala, docker and testing, oh my! mario camou
Scala, docker and testing, oh my! mario camou
 
Build Automation of PHP Applications
Build Automation of PHP ApplicationsBuild Automation of PHP Applications
Build Automation of PHP Applications
 

Mehr von Shih-Hsiang Lin

Mehr von Shih-Hsiang Lin (13)

Introduction to GNU Make Programming Language
Introduction to GNU Make Programming LanguageIntroduction to GNU Make Programming Language
Introduction to GNU Make Programming Language
 
Ch6 file, saving states, and preferences
Ch6 file, saving states, and preferencesCh6 file, saving states, and preferences
Ch6 file, saving states, and preferences
 
[C++ gui programming with qt4] chap9
[C++ gui programming with qt4] chap9[C++ gui programming with qt4] chap9
[C++ gui programming with qt4] chap9
 
Ch5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internetCh5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internet
 
Ch4 creating user interfaces
Ch4 creating user interfacesCh4 creating user interfaces
Ch4 creating user interfaces
 
Ch3 creating application and activities
Ch3 creating application and activitiesCh3 creating application and activities
Ch3 creating application and activities
 
[C++ GUI Programming with Qt4] chap7
[C++ GUI Programming with Qt4] chap7[C++ GUI Programming with Qt4] chap7
[C++ GUI Programming with Qt4] chap7
 
[C++ GUI Programming with Qt4] chap4
[C++ GUI Programming with Qt4] chap4[C++ GUI Programming with Qt4] chap4
[C++ GUI Programming with Qt4] chap4
 
Function pointer
Function pointerFunction pointer
Function pointer
 
Introduction to homography
Introduction to homographyIntroduction to homography
Introduction to homography
 
Git basic
Git basicGit basic
Git basic
 
Project Hosting by Google
Project Hosting by GoogleProject Hosting by Google
Project Hosting by Google
 
An Introduction to Hidden Markov Model
An Introduction to Hidden Markov ModelAn Introduction to Hidden Markov Model
An Introduction to Hidden Markov Model
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

Introduction to Apache Ant

  • 1. Introduction to Ant @brownylin
  • 2. 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
  • 3. What is Ant? • Ant Java Make Make Java
  • 4. Outline •A First Ant Build • Ant and Eclipse • Ant programming
  • 5. 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$
  • 6. Main.java package oata; public class HelloWorld { 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
  • 9. A Simple build.xml <?xml version="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
  • 13. 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.
  • 14. <?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>
  • 15. Run brownylins-MacBook:StructureBuild brownylin$ java -cp build/classes org.antbook.welcome.Main a b . a b .
  • 16. Practice • Tutorial: Hello World with Apache Ant
  • 17. Outline • A First Ant Build •Ant and Eclipse • Ant programming
  • 18. Eclipse integrated with Ant • Apache Ant 101: Make Java builds a snap • Make Ant easy with Eclipse
  • 19. Outline • A First Ant Build • Ant and Eclipse •Ant programming
  • 20. 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>
  • 21. 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
  • 22. 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>
  • 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 • 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)
  • 32. 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)
  • 33. 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.
  • 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)