Introduction to Ant

43
Introduction to Ant James Brucker

description

Introduction to Ant

Transcript of Introduction to Ant

  • Introduction to AntJames Brucker

  • What is Ant?Ant is a build tool -- it builds software according to a set of rules.Ant can determine which products depend on which sources, and only build the parts that are out-of-date.An Apache Jakarta projectJakarta is an umbrella heading for all the Java related Apache projectsOpen source, Apache LicenseProject Home: http://ant.apache.org/

  • Example of Using Ant (1)Here is a project with a "build.xml" file it the project directory. First we try asking for help on the build tasks:cmd> ant help [echo] Usage: ant target [echo] [echo] target is one of: [echo] clean - delete files from the build directory [echo] build - compile java source code [echo] buildall - recompile everything (clean first) [echo] dist - create a distribution in dist directory [echo] javadoc - create Javadoc in doc/api dir [echo] test - run unit testsNote: many build.xml files don't have a "help" task, so they may not print this message.

  • Example of Using Ant (2)We see there is "build" target, so we use it to compile the source:cmd> ant build

    init: [mkdir] Created dir: world/build [copy] Copying 1 file to world/build

    build: [javac] Compiling 8 source files to build/classes [javac] Compiling 3 source files to build/test-classes

    BUILD SUCCESSFULThe build.xml file told Ant that it must run the "init" target before the "build" target, so we see output from two tasks.Ant performs the "init" targetAnt performs the "build"

  • Example of Using Ant (3)Since "build" succeeded, we can try creating a jar file (dist).cmd> ant dist

    init:build:

    dist: [mkdir] Created dir: dist [jar] Building jar: dist/world-1.0.jar [copy] Copying 2 files to world/dist

    BUILD SUCCESSFULThe build.xml file told Ant that "dist" depends on "init" and "build", but the output from these targets exist and are up-to-date."dist" requires that the "init" and "build" task be performed, but Ant sees that these targets are already up-to-date, so it does nothing

  • Typical Development CycleThe typical work cycle for building a project with Ant is:buildcompile sourcestestrun unit teststest-reportgenerate reportsdistcreate runnable product

  • A Little HistoryFor years (decades) developers have used a program called "make" to automate project builds.Make gets information from a Makefile.Example: Apache web serverdownload the source code for Apache httpdunzip or untar the source codein the top source directory type: configurethen type: makewait (it may take several minutes)type: make install

  • Ant: a modern "make"Makefile designed for humans to read and edit. Not optimal for processing by software.Make is written in terms of processing instructions for types of files, plus application-specific "tasks". Example:# build object (*.o) files from C (*.c) file%.o: %.c${CC} -c ${CFLAGS} $< Ant allows developers to define there own rules, and has a more expressive syntax.Ant uses XML for rules file: easier for software to read and write.

  • Installing AntWindows:Download from http://ant.apache.org/Unzip to a convenient directory (no spaces preferred). I use: D:\lib\antAdd ant-dir\bin to the PATH. I use:ANT_HOME=D:\lib\antPATH=%PATH%;%ANT_HOME%\binUbuntu Linux:"apt-get install ant" will install the GNU Java and lots of other packages. Don't do it!Download Ant from ant.apache.org, unzip (e.g. /opt), and add to your path. This way you can use Sun's JRE.

  • Test the InstallationDOS-Never-Dies> ant -help

    ant [options] [target [target2 [target3] ...]]Options: -help, -h print this message -version print the version and exit -quiet, -q be extra quiet -verbose, -v be extra verbose -logfile use given file for log -buildfile use given buildfile -f | -file '' -D= use value for given property -keep-going, -k execute all targets that do not depend on failed target(s) -propertyfile load all properties from file If you get a "command not found" message, then ant/bin isn't on your PATH. If java is not found, then the JDK "bin" directory isn't on your PATH.

  • Sample ApplicationWorld/ project folderbuild.xmlAnt build filesrc/source codeworld/domain/City.java...test/test sourceworld/domain/CityTest.javabuild/build productsclasses/java classesdist/final productsworld-1.0.jarlib/dependent jarsmysql-connector-bin.jar

  • A Simple Ant Build fileThe default build file name is: build.xml World country facts using JDBC

  • A Simple Ant Build file (2)The actual work is defined in "targets": ... instructions for "init" job instructions for "build" job instructions for "dist" job

  • Define a "build" taskThis task tells Ant how to compile our program

  • "build" depends on "init" taskMost projects have an "init" task to create output directories.

    (this is not required)

    Ant wildcards

  • Test Your Build FileCmd> ant buildif your build file is "mybuild.xml" then...Cmd> ant -f mybuild.xml buildBuildfile: mybuild.xmlinit: [mkdir] Created dir: workspace/World/build/test [copy] Copying 2 files to ...

    build: [echo] World: workspace/World/mybuild.xml [javac] Compiling 6 source files to build/classes

    BUILD SUCCESSFUL

  • Create a DistributionDefine a "dist" task to create the project jar file.

  • Test the "dist" targetCmd> ant buildif your build file is "mybuild.xml"...Cmd> ant -f mybuild.xml buildBuildfile: mybuild.xmlinit:

    build:

    dist: [mkdir] Created dir: dist [jar] Building jar: dist/worldfacts-1.0.jar [copy] Copying 2 files to world/dist

  • Use properties instead of stringsWe have used "build/classes", "src", ... many times in the build file.Difficult to maintain and potential for typing errors.src.dir = location of source codebuild.dir = build output base directorybuild.classes.dir = location of build classes

    dist.dir = location of distributionlib.dir = location of required librariesdoc.dir = documentation base directory

    source = source compliance level (1.5, 1.6 ...)target = output compliance level (1.5, 1.6 ...)

  • Use properties instead of strings

  • Substitute properties for stringsSubstitute property names in the build rules:

  • Test the updated build.xml fileDelete the "build" directory.Run "ant build" again.Expect some errors:typing errors (forgot "." in name)Ant may create a file named "${build.xxx.dir}" if you have a misspelled property name in the build file

  • Create a "test" task

  • What Are Tasks?Ant has a large set of built-in tasks, such as:output a messagecreate a directory (if it doesn't exist)copy a file, directory, or treecompile files using java compilercreate a jar filerun JUnit tests

  • Defines a variable ("property") that can be used throughout a build script. To access value of a property use: ${propertyname}.Useful for defining names of locations and files used repeatedly.Example:

  • (2)Read all the properties from a file. The file is a plain text file with lines of the form "name=value", like Java properties files Properties can be imported from system environment!Prefix environment properties with a "env."

  • Copies a file or set of files to another location. Does not overwrite existing files if they are newer than the source file (unless you specify that you want it to overwrite).Copy a single file.

  • : copy sets of filesCopy files from one directory to another, omit any java source files.

    Copy all files from the directory ../backup/ to src_dir. Replace occurrences of "@TITLE@" in the files with "Foo".

  • Deletes files, directories, or sets of files.Delete a single file.Delete all *.bak files from this directory and sub-directories. Delete the build directory and everything in it.

  • Display a message on terminal. It has 2 forms:Display a one-line message:

    Usage: ant targetclean - delete compiler output filesbuild - compile source codedist - create a distribution

    Display many lines of text:

    [echo] Hello Ants

  • Using A good build.xml file should have a help or usage target:

    Usage: ant target

    where 'target' is one of: clean - delete compiler output files build - compile source code dist - create a distribution

  • Create a directory.Creates a subdirectory named "jars" in the location specified by the "dist.dir" property.

  • Compiles Java source code. Attempts to analyze source such that up to date .class file are not recompiled.Example: Compile all java source files under ${src.dir} and put the .class files in the ${build.classes} directory. Include debugging information in the .class files.

  • (2)You can specify additional source directories and further restrict which files are compiled using include and exclude .

  • Creates a JAR file from a set of files or updates an existing JAR.Will automatically supply a manifest file for the JAR or use one you specify.Example: make a jar file including all files in build/classes

  • Create a JAR file from all the files in ${build}/classes and ${src}/resources. (two sets of files)Any files named *Test.class in the build directory are not included in the JAR.

  • Creates Javadocs from Java source code files.Example: Build Javadoc only for the packages beginning with "org.ske..." in the ${src}\ directory.

    This command will search all subdirectories of ${src} for *.java files.

  • Invoke a Java program from within an Ant build file.Can fork a separate process so that a System.exit() does not kill the Ant build.

  • Invoke a class named test.Main in a separate Java VM. The Java VM is invoked using the options: -Xrunhprof:cpu=samples,file=log.txt,depth=3to request profiling.

  • More Ant TasksThe Apache Ant distribution includes more than 50 core tasks and many optional tasks.Examples: zip, gzip, war (create a war file), Many tasks correspond to standard Linux commands, like mkdir, copy, move. You can write your own Ant tasks using .See Ant manual (ant/docs directory) for how to use each task.

  • ToolsList of Ant tools: http://ant.apache.org/external.html NetBeans creates build.xml files for NetBeans projects. Eclipse can "export" an Ant build file, but it contains a lot of Eclipse-specific references that make the build file not portable.Ivy (http://ant.apache.org/ivy) is a dependency manager for Ant. Automatically downloads dependencies, similar to what Maven does (Ivy can use Maven repositories).

  • ResourcesAnt Home: http://ant.apache.orgApache Ant Manual. Installed with ant, in the ant/docs directory. The Ant Manual documents all Ant tasks. Ant: The Definitive Guide. O'Reilly. Terse, but lots of info.