Ant and Maven.doc

Embed Size (px)

Citation preview

  • 8/10/2019 Ant and Maven.doc

    1/85

    Setting Up a Project Using Ant

    Ant in the Build Process

    Ant is a popular and widely used open source build tool, written in Java. Indeed, it is

    probably themost widely used build tool in the Java world. It is supported by virtually

    all modern IDEs, and (being a Java application) runs on almost any Java-riendlyplatorm.

    In a nutshell, Ant helps you transorm the source code, libraries, and other iles that

    ma!e up your pro"ect into a deliverable sotware pac!age. And, more importantly, ithelps you do this in an orderly, repeatable manner. I you design your build script well,you can also ensure that it will behave the same way on any machine. #his leads theway to automatic builds, which can be run on a remote machine with little or no humanintervention.

    Ant is a highly le$ible tool%you can ma!e it do pretty much anything you want.

    &owever, this le$ibility can come at a cost o comple$ity. 'ood Ant build scripts arewritten in a way that will be easy to read and maintain in a years time.

    Features of Apache Ant Ant is the most complete Java build and deployment tool available.

    Ant is platorm neutral and can handle platorm speciic properties such as ile separato

    Ant can be used to perorm platorm speciic tas!s such as modiying the modiied time

    a ile using touch command.

    Ant scripts are written using plain *+. I you are already amiliar with *+, you can

    learn Ant pretty uic!ly.

    Ant is good at automating complicated repetitive tas!s.

    Ant comes with a big list o predeined tas!s.

    Ant provides an interace to develop custom tas!s.

    Ant can be easily invo!ed rom the command line and it can integrate with ree and

    commercial IDEs

    Installing Ant

    It is assumed that you have already downloaded and installed Java Development it (JD)your computer

  • 8/10/2019 Ant and Maven.doc

    2/85

    Apache Ant is distributed under the Apache /otware icense, a ully-ledged open sourcelicense certiied by the open source initiative.#he latest Apache Ant version, including ull-source code, class iles and documentation canound athttp://ant.apache.org.

    1. Ensure that the JA0A1&2+E environment variable is set to the older where your JD is

    installed.3. Download the binaries rom http455ant.apache.org

    6. 7n8ip the 8ip ile to a convenient location using 9in8ip, win:A:, ;-8ip or similar tools, c4< older.

    =. >reate a new environment variable called A?#1&2+E that points to the Ant installationolder, in this case c4

  • 8/10/2019 Ant and Maven.doc

    3/85

    .

    A Simple Ant Build File

    Directory structure for our project

    Directory

    srctest

    lib

    build

    build5classes

    Contents

    Application source code

    7nit test code

    Cro"ect dependencies

    Any iles generated by the build process

    >ompiled Java classes

    build5test-classes >ompiled unit tests

    dist Distribution iles, such as bundled JA: or 9A: iles

  • 8/10/2019 Ant and Maven.doc

    4/85

    &aving a clean, well-deined directory structure is important or any pro"ect, and isparticularly important i you are using a tool li!e Ant. A clear directory layout ma!esthe build script easier to write and understand. /eparating compiled classes rom sourcecode, or e$ample, ma!es it easier to do a clean recompile simply by deleting the target

    directory, and ma!es it easier to place source code (and onlysource code) under version

    control.7sing a libdirectory to store your dependencies is one commonly used approach in

    Ant pro"ects, though it is not the only solution to this problem.

    #his is not the only way to store dependencies. Indeed, !eeping them in the libdirec-

    tory may mean that your JA:s end up being stored in your version control system. #hisis not always ideal. +aven uses a dierent approach, where JA: ilesare stored on a central repository, and dependencies are listed in the build ile, insteado in one o the pro"ect directories.

    +aven uses a similar standardi8ed directory structure which can also

    be used or Ant pro"ects.

    For our irst e$ample, we will be wor!ing with a simple one-class application that

    displays some inormation about the installed J0+ and operating system. #his re-mar!ably useul piece o code is shown here4

    pac!age com.it.ta$calculatorG

    public class +ain H

    public static void main(/tring args) H

    /tring "vm K /ystem.getCroperty(L"ava.versionL)G

    /tring os?ame K /ystem.getCroperty(Los.nameL)G

    /tring os0ersion K /ystem.getCroperty(Los.versionL)G

    /ystem.out.println(L:unning Java L M "vm

    M L on L M os?ame

    M L (version L M os0ersion M L)L)G

    N

    N

    ?ow lets see how you could use Ant to build this application. At this stage, we "ust

    want to compile our code and bundle up a JA: ile containing the compiled classes.

    ou could do this with abuild.$mlile, along the ollowing lines4

    OP$ml [email protected] P

    Opro"ect nameKLta$-calculatorL deaultKLpac!ageL

    Otarget nameKLinitL

    Om!dir dirKLbuild5classesL 5

    Om!dir dirKLdistL 5

    O5target

    Otarget nameKLcompileL dependsKLinitL descriptionKL>ompile Java codeL

    O"avac srcdirKLsrcL destdirKLbuild5classesL5

    O5target

    Otarget nameKLpac!ageL dependsKLcompileL descriptionKL'enerate JA: ileL

  • 8/10/2019 Ant and Maven.doc

    5/85

    O"ar destileKLdist5ta$-calculator."arL basedirKLbuild5classesL5

    O5target

    Otarget nameKLcleanL descriptionKLDeletes generated directoriesL

    Odelete dirKLbuildL 5

    Odelete dirKLdistL 5

    O5target

    O5pro"ect

    ets go through this build ile, and see how it uses the basic concepts we discussed

    earlier. i!e all Ant build scripts, the root element is called . #he main roleo the element is to act as a container or the other build elements such asproperties, targets, and tas!s. It also lets you deine an (optional) deault target.

    Each target uses various built-in Ant tas!s. #he irst thing we need to do in our build

    process is create any missing directories. ou need to ma!e sure these directories havebeen created beore compiling your classes. /o, the irst target, called Qinit,R simply

    creates thebuildand distdirectories using the mkdirtas!4

    Otarget nameKLinitL

    Om!dir dirKLbuild5classesL 5Om!dir dirKLdistL 5

    O5target

    9e dont need to create the QbuildR directory beore the Qbuild5classesR directory be-

    cause Ant will do this automatically or us.

    ?e$t we need to compile our classes. #he QcompileR target usesjavac(or, more pre-

    cisely, thejavacAnt tas!) to compile the source code in the src directory and place the

    compiled classes in thebuild5classesdirectory4

    Otarget nameKLcompileL dependsKLinitL descriptionKL>ompile Java codeL

    O"avac srcdirKLsrcL destdirKLbuild5classesL5

    O5target

    #he Qpac!ageR target creates a JA: ile in the dist directory containing all o the com-

    piled classes in thebuild5classesdirectory4

    Otarget nameKLpac!ageL dependsKLcompileL descriptionKL'enerate JA: ileL

    O"ar destileKLdist5ta$-calculator."arL basedirKLbuild5classesL5

    O5target

    Finally, the QcleanR target simply deletes the generated directories using the deletetas!4

    Otarget nameKLcleanL dependsKLinitL descriptionKLDeletes generated directoriesL

    Odelete dirKLbuildL 5 Odelete dirKLdistL 5

    O5target

    Running Ant

    9e are now ready to run this build script. ou can do so by running Ant in the root

    directory o your pro"ect. I you run Ant with no arguments, Ant will invo!e the deaulttarget, which is Qpac!ageR or this pro"ect4

    $ antSuildile4 build.$ml

  • 8/10/2019 Ant and Maven.doc

    6/85

    init4

    m!dir >reated dir4 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5build5classes

    m!dir >reated dir4 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5dist

    compile4

    "avac >ompiling @ source ile to 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo

    5build5classes

    pac!age4 "ar Suilding "ar4 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5dist

    5ta$-calculator."ar

    S7ID /7>>E//F7

    #otal time4 @ second

    Alternatively, you can speciy the target you want to run, as shown here with the QcleanR

    target4

    $ ant clean

    Suildile4 build.$ml

    init4

    clean4

    delete Deleting directory 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5build

    delete Deleting directory 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5dist

    S7ID /7>>E//F7

    #otal time4 seconds

    ou can also run several targets at the same time, simply by listing them as arguments

    on the command line4

    $ ant clean compileSuildile4 build.$ml

    clean4

    delete Deleting directory 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5build

    delete Deleting directory 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5dist

    init4

    m!dir >reated dir4 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5build5classes

    m!dir >reated dir4 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5dist

    compile4

    "avac >ompiling @ source ile to 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo

    5build5classes

    S7ID /7>>E//F7

    #otal time4 3 seconds

    Sy convention, Ant iles are calledbuild.$ml, but you can speciy a dierent build script

    using the -foption4

    $ ant -f my-special-buildfile.xml

    Finally, li!e many tools, you can activate a verbose mode (using the -vcommand-line

    option) to display more details about what Ant is doing. #his can be useul when de-bugging your build scripts4

    $ ant -v

    Apache Ant version @.;. compiled on July @@ 3;

  • 8/10/2019 Ant and Maven.doc

    7/85

    Suildile4 build.$ml

    Detected Java version4 @.T in4 5usr5lib5"vm5"[email protected]"re

    Detected 2/4 inu$

    parsing buildile 5home5wa!aleo5pro"ects5"ava-power-tools5sample-code5ch@5ant-demo

    5build.$ml with 7:I K ile45home5wa!aleo5pro"ects5"ava-power-tools5sample-code5ch@5ant-demo5build.$ml

    Cro"ect base dir set to4 5home5wa!aleo5pro"ects5"ava-power-tools5sample-code5ch@

    5ant-demo...

  • 8/10/2019 Ant and Maven.doc

    8/85

    +ost Ant targets are not designed to be run in isolation. Seore compiling the Java

    source code, we need to create the target directories. And we obviously need to compilethe latest version o the source code beore we can generate a new version o the JA:ile. In other words, there is a precise order in which the targets need to be e$ecuted.>ertain targets depend on others.

    In Ant, you use the dependsattribute to declare a targets direct dependencies4Otarget nameKLpac!ageL dependsKLcompileL descriptionKL'enerate JA: ileL

    Otarget nameKLcompileL dependsKLinitL descriptionKL'enerate JA: ileL

    In this e$ample, the Qpac!ageR target depends on the QcompileR target to compile the

    Java classes, which in turn depends on the QinitR target to prepare the output directories.

    In act, the Qpac!ageR target alsodepends on Qinit,R but we dont need to list QinitR inthe Qpac!ageR target dependencies because it will automatically be called when theQcompileR target is e$ecuted. #hese dependencies can be e$pressed as a dependencygraph, as shown in the above igure.

    /ome targets can have multiple dependencies. For e$ample, in the ollowing code theQtestR target directly depends on both the Qunit-testR and the Qintegration-testR targets.

    Otarget nameKLtestL dependsKLunit-test, integration-testL descriptionK

    L'enerate JA: ileL

    Ant is airly smart about how it handles dependencies. For e$ample, i both the Qunit-

    testR and the Qintegration-testR targets depend on the QcompileR target, this target willonly be e$ecuted once.

    Documenting Your Project

    Documenting build scripts is important, and Ant build iles are no e$ception. et

    unattended, they can uic!ly become a nightmare to understand, both or you andother developers later on.

  • 8/10/2019 Ant and Maven.doc

    9/85

    In addition to traditional techniues such as *+ comments, Ant comes with a ew

    built-in eatures to help you document your build scripts. #he descriptionattribute letsyou provide a short description or your targets, as shown here4

    Otarget nameKLcompileL dependsKLinitL descriptionKL>ompile Java codeL

    O"avac srcdirKLsrcL destdirKLbuild5classesL5

    O5target

    It is a good idea to use the descriptionattribute or the targets in your build script that

    are intended or e$ternal use. ou can then use the -projecthelpcommand-line optionto list the main build targets, complete with a brie description. 9ith large build scripts(and Ant build scripts can become very large), this can be a valuable time-saver4

    $ ant -projecthelp

    Suildile4 build.$ml

    +ain targets4

    compile >ompile Java code

    pac!age 'enerate JA: ileclean Deletes generated directories

    Deault target4 pac!age

    Compiling Your a!a Code in Ant

    In Java development, one o the most undamental things that any build script needs

    to do is compile your code. In Ant, the tas! provides a convenient one-stopshop or Java compilation.

    ets loo! at a simple use o the tas!. In the e$ample given above, we use a

    simple orm o this tas! to compile the Java classes in the src5main directory, and placethe compiled classes in the build5classes directory4

    Otarget nameKLcompileL dependsKLinitL descriptionKL>ompile Java codeL

    O"avac srcdirKLsrcL destdirKLbuild5classesL5

    O5target

    #his is euivalent to e$ecuting thejavactool as shown here4

    Ujavac -noarn -d build!classes src!main

    In most real applications, your application will reuire a set o libraries both to compile

    and to run. In Ant pro"ects, these libraries are oten stored (in the orm o JA: iles) in

    a directory called lib. 9hen you compile your application, you need to tell Ant whereto ind these libraries.

    Ant comes with some very powerul eatures to help you do this. Ant e$cels at deining

    and manipulating classpaths and other ile path deinitions. At its simplest, you can use the

    tag to identiy a particular

    library using the locationattribute4

    Opath idKL"unit.classpathL locationKLlib5"unit."arL5

    #his path could also be deined in the same way using the path attribute. &owever, in

    addition to deining single JA: iles or directories, thepathattribute lets you use a morepath-li!e construction using a combination o directory paths and a JA: ile, as shown

  • 8/10/2019 Ant and Maven.doc

    10/85

    here4

    Opath idKL"unit.classpathL pathKLbuild5classes4lib5"unit."arL5

    2ne o the nice things about the Ant path-handling eatures is that they are (li!e the

    underlying Java ACIs) portable across dierent operating systems. &ere, by convention,we use 7ni$-style paths containing orward slashes (Q5R). For e$ample, on a 9indowsmachine, Ant will automatically translate the above path into Qbuildompile Java codeL

    O"avac srcdirKLsrcL

    destdirKLbuild5classesL

    classpathreKLcompile.classpathL 5

    O5target

    Alternatively, i you dont thin! you will need this classpath elsewhere in your build

    ile, you can embed the element directly in the tas!4

    Otarget nameKLcompileL dependsKLinitL descriptionKL>ompile Java codeL

    O"avac srcdirKLsrcL destdirKLbuild5classesL

    Oclasspath Oileset dirKLlibL includesKLV."arL5

    O5classpath

    O5"avac

    O5target

    #hese paths actually use a shorthand notation or convenience. ou can also use em-

    bedded tags or a more readable notation, which is useul when many separate classpathelements are reuired. #his is also convenient i you want to reuse paths deined else-

    where in the build ile. #he tag lets you deine a classpath element usingeither a JA: ile, a directory, or even a reerence to another classpath element4

  • 8/10/2019 Ant and Maven.doc

    11/85

    Opath idKLtest.classpathL

    Opath reidKLcompile.classpathL5

    Opathelement locationKLlib5"unit."arL5

    Opathelement pathKLbuild5test-classesL5

    O5path

    ou can also use path-li!e e$pressions within the tas! itsel to tell Ant what

    classes to include or which ones should be e$cluded rom the compilation process,using the includesand excludesattributes. For e$ample, to compile only the classes in

    the com.mycompany.myapp.web pac!age (and below), you could do this4

    O"avac srcdirKLsrcL destdirKLbuild5classesL includesKLcom5mycompany5myapp5web5VVL 5

    2ne reuent reuirement when compiling Java code is to compile or a speciic Java

    version. For e$ample, you may use Java T on your development machine, but need todeploy to an environment where only Java @.= is supported. ou can ensure that yourJava code is compatible with Java @.=, and that none o the nice Java B syntactic sugar

    is used, by setting thesourceattribute to Q@.=.R /imilarly, you can tell Ant to generatebyte-code compatible with a Java @.= J0+ by speciying the targetattribute as Q@.=.R

    O"avac srcdirKLsrcL destdirKLbuild5classesL sourceKL@.=L targetKL@.=L 5

    ou may also need to indicate i you want the source code compiled with debug in-

    ormation. Sy deault, this is turned o, but it can come in handy when testing and

    debugging your code. #o turn this option on, set the debugattribute to QonR (or QtrueR)4

    O"avac srcdirKLsrcL destdirKLbuild5classesL debugKLonL 5

    Despite its name, the tas! is not tied to the standard /un Java compiler, also

    called javac. In act, ans o alternative compilers li!e Ji!es and '>J can use thesecompilers, or a number o other more e$otic choices, by speciying the compiler

    attribute4O"avac srcdirKLsrcL destdirKLbuild5classesL compilerKL"i!esL5

    ou can also deine this value or the entire build ile by setting the build.compiler

    property.

    As you can see, the tas! provides a powerul, le$ible tool or Java compilation.

    +any o the techniues covered here are typical o many Ant tas!s, and we will seemore e$amples o these later on.

    Understanding Ant datatypes and properties

    Datatype o!er!ie"

    2ne o the great advantages Ant has over the alternatives to building and pac!aging Javapplications is that it understands the primary problem domain, that o building Javapro"ects. +ost steps to build a typical Java pro"ect deal with iles and paths (such asclasspaths). Ant provides datatypes to handle these two concepts natively. ou can thin!an Ant datatype as similar to Javas own built-in core classes4 data that can bepassed around and provided to tas!s. #he ileset and path datatypes, and several others,orm the basic building bloc!s o Ant build iles.

    >lasspath-related headaches are commonplace in Java development. Ant ma!es dealingwith classpaths much more natural and pleasant than the command-line manual alternat

  • 8/10/2019 Ant and Maven.doc

    12/85

    and provides or the reuse o deined classpaths wherever needed. For e$ample, compilisource code reuires that reerenced classes be in the classpath.A path can be deined oor compilation with O"avac, and reused or e$ecution (via O"ava). 2ne o theconseuences o classpaths being speciied inside the build ile is that Ant can be invo!ewithout an e$plicitly deined system classpath, ma!ing it easy to install Ant and build apro"ect with little or no environmental coniguration.@ Another no less importantconseuence is that classpaths can be easily and tightly controlled. #his reduces

    >A//CA#& coniguration problems, both or compilation and e$ecution.A set o iles is a common entity to manipulate or such tas!s as compiling, pac!aging,copying, deleting, and documenting. Deining a ileset o all ."ava iles, or e$ample, isstraightorward4

    Sy providing an id attribute, we are deining a reerence. #his reerence name can be uslater wherever a ileset is e$pected. For e$ample, copying our source code to anotherdirectory using the previouslydeinedsource.fileset is

    Propertyo!er!ie"

    Ants property handling mechanism allows or build ile e$tensibility and reusability byparameteri8ing any string-speciied item. #he control users get over build iles can bedramatically increased with the techniues shown in this chapter. For e$ample, changingbuild to use a dierent version o a third-party library, perhaps or testing purposes, canmade as trivial as this4

    ant -Dstruts.jar=/home/ant/newstruts/struts.jar

    In this case, struts.jar represents an Ant property, and in our build ile, we reer to with special synta$: ${struts.jar}. A !ey eature o an Ant property is its

    immutabilityG it resists change once set.

    FI#$S$%S

    Implicitly, all build processes will operate on sets o iles, either to compile, copy, deleteor operate on them in any number o other ways. Ant provides the ileset as a nativedatatype. It is diicult to imagine any useul build that does not use a ileset. /ome tas!support paths, which implicitly support ilesets, while other tas!s support ilesets directland this distinction should be made clear in each tas!s documentation.A ileset is a set o iles rooted rom a single directory. Sy deault, a ileset speciied witonly a root directory will include all the iles in that entire directory tree, including iles

    all subdirectories recursively. For a concrete running e$ample that will demonstrateileset eatures as we discuss them, lets copy iles rom one directory to another4

    In its current orm, all iles rom the web directory are copied to the new1web directory#his e$ample will evolve into copying only speciic iles, altering them during the copywith to!en replacement, and lattening the directory hierarchy in the new1web directory

    Fileset e&amples

    During a build, you oten need to build a ileset by including or e$cluding sets o iles. Aew e$amples o typical ilesets ollow.

  • 8/10/2019 Ant and Maven.doc

    13/85

    Include all JA: iles in the lib directory (nonrecursive, no subdirectories are considered

    Include all ."ava iles below the test directory that end with the word Q#estR

    All non-J/C pages in the web directory and below4

    Sy deault, includes and e$cludes are case-sensitive, but this can be disabled by speciycasesensitive="false". The and elements are calledpatternsets.

    PA%%$R'S$%S

    Filesets accomplish the include5e$clude capability by utili8ing another o Ants coredatatypes4 the patternset. A patternset is a collection o ile matching patterns. A patterns

    itsel does not reer to any actual iles until it is nested in a ileset and thereorerooted at a speciic directory. A pattern is a path-matching speciication similar to 7ni$-and +/-D2/-based ile matching. E$amples o this have already been shown with V."arused to represent all iles with the ."ar e$tension in the top directory andVV5V."sp to represent all iles in the entire directory tree with the ."sp e$tension.#he pattern matching eatures are as ollows:

    V matches 8ero or more characters.W P matches a single character.W VV, used as the name o a directory, represents matching o all directories romthat point down, matching 8ero or more directories. A pattern ending with a trailing 5 or < implies a trailing VV. Implicitly a Oileseholds a patternset, but patternsets can also be speciied independently, allowingthe reuse o patternsets in multiple ilesets.Catternset attributes. Including and e$cluding patterns allows ilesets to be deinprecisely to encompass only the iles desired. #he includesile and e$cludesileadds a level o indirection and e$ternal customi8ation.

    Attribute Descriptionincludes Comma-separated list of patterns of les that must be included. All

    are included when omitted.

    excludes Comma-separated list of patterns of les that must be excluded. No

    (except default excludes are excluded when omitted.includesfile The name of a le! each line of this le is ta"en to be an include patt

    #ou can specif$ more than one include le b$ usin% nestedincludesfile elements.

    excludesfile The name of a le! each line of this le is ta"en to be an exclude pat

    #ou can specif$ more than one exclude le b$ usin% nestedexcludesfile elements.

    E$cludes ta!e precedence, so that i a ile matched both an include and e$clude patterthe ile would be e$cluded. Elements corresponding to these attributes are also availabas child elements o Opatternset or increased le$ibility and control.#he elements are Oinclude, Oe$clude, Oincludesile, and Oe$cludesile.

    Each o these elements has a name attribute. For Oinclude and

  • 8/10/2019 Ant and Maven.doc

    14/85

    Oe$clude, the name attribute speciies the pattern to be included or e$cluded,respectively. For the Oincludesile and Oe$cludesile elements, the name attributerepresents a ile name. Each o these elements has i5unless attributes,which are covered in the conditional patternset section later in this chapter &ere are soe$amples o patternsets4

    #he Opatternset element is not always e$plicitly speciied when used within a ilesetileset implicitly contains patternsets. 2ur running copy e$ample is shown again usingpatternset to include all J/C iles4

    #his is euivalent to

    &ad we speciied "ust V."sp, only the J/C iles in the web directory would have beencopied, but no iles in its subdirectories.

    Catternsets may be nested within one another, such as

    #his is a contrived e$ample simply demonstrating the nesting capability. #his nesting unnecessary in this e$ample, but datatype reerences ma!e the nesting capabilitypowerul. Catternset nesting is a eature introduced with Ant @.B

    S$#$C%(RS

    Ant @.B includes a sophisticated new eature, called selectors, orselecting theilesincluded in a ileset.Ants built-in selectors

    Selector Description &or"s li"e a patternset or element t

    match les based on a pattern. 'elects les based on a director$ depth ran%e.

    'elects les that are less, eual, or more than a specied si)

    'elects les (and optionall$ directories that ha*e been lastmodied before, after, or on a specied date. 'elects les if the$ exist in another director$ tree.

    'elects les that are newer than correspondin% ones in

    another director$ tree. 'elects les that contain a strin%.

    #hese selectors can be combined inside selector containers to provide grouping andlogic. #he containersare, , , , and.>ontainersmay be nested inside containers, allowing or the construction o comple$ selectionlogic. :ather than detailing every available selector, container, and their options, we

    reer you to Ants documentation or this inormation. 9e will, however,provide a couple o e$amples showing how selectors wor!.

  • 8/10/2019 Ant and Maven.doc

    15/85

    #o compare two directory trees and copy the iles that e$ist in one tree but not anothewe use a combination o and:

    #he tas! is copying only the iles rom the web directory that do not e$ist ithe currentiles directory. 7sing the selector, we can choose only the that contain a certain string:

    2nly the iles containing the te$t Q/ystemR in the web directory are copied to thecurrentiles directory. Sy deault is case-sensitive, but can be changedusing casesensitive="no".

    All rules must be satisied beore a ile is considered part o a ileset, so when usingselectors in con"unction with patternsets, the ile must match the include patterns, munot match any e$clude patterns, and the selector rules must test positively.A selector enables you to write your own selector logic in a Java class.

    FI#%$RC)AI'S A'D FI#%$RR$AD$RS

    Crocessing te$t iles has never been so easy with Ant until the introduction, in [email protected], o Filter>hains and Filter:eaders. A Filter:eader is a simple ilter o te$t inputthat can remove or modiy the te$t beore it is output. A Filter>hain is an ordered groo one or more Filter:eaders. A Filter>hain is analogous to piping output rom

    one command to another in 7ni$, with the output o one command being the input tothe ne$t, and so on.#here are a number built-in Filter:eaders, as shown in table

    Ants built-in FilterReadersFilterReader Description

    . +enerates name=value" lines for basic and 'trin%

    datat$pe constants found in a class le. eplaces Ant propert$ *alues.

    xtracts the rst specied number of lines.

    nl$ lines containin% the specied strin% are passe

    throu%h. nl$ lines matchin% specied re%ular expression(s are pass

    throu%h. All lines ha*e a prex prepended.

    /erforms to"en substitution, 0ust as ltersets do.

    emo*es 1a*a st$le comments.

    emo*es line brea"s, defaultin% to \r" and \n" but

    charactersstripped can be specied.

    emo*es lines be%innin% with a specied set of

    characters. eplaces tabs with a specied number of spaces.

    xtracts the last specied number of lines.

  • 8/10/2019 Ant and Maven.doc

    16/85

    *APP$RS

    Ants mapper datatype is used to match sets o iles with one another. #here are severbuilt-in mapper types as shown in table. +appers are used by, , and and several other tas!s. Depending on the mapper type,toand from attributes may be reuired.

    Identity mapper

    #he target ile name maps e$actly to the source ile name. #heto and from attrib

    are not used by theidentity mapper.

    Sy deault, the tas! uses theidentity mapper. #he ollowing two Ocopytas!s have the same eect4

    Flatten mapper#heflatten mapper removes all directory path inormation rom the source ilename to map to the target ile name. The to and from attributes are not used. #helatten mapper is useul in copying iles rom a nested directory structure into asingle directory eliminating the hierarchy.#o copy all J/C pages rom the web directory hierarchy into a single lat directory,the flatten mapper is used in this manner:

    ?ote that i multiple iles have the same name in the source ileset, regardless o directoonly one o them will ma!e it to the destination directoryG it is unspeciied which one itwill be.

    *erge mapper

    #he target ile name remains i$ed to the to attribute speciied. All source ile namesmap to the single target.

    #hemerge mapper is used with in cases where many iles map to asingle destination. For e$ample, many iles are bundled together into a single Xip ile.A property can be set i the Xip contains all the latest sources:

    /aving time by s!ipping unnecessary steps4 Ouptodate#o determine i target iles are up-to-date with source iles, Ant provides the Ouptodatetas!. +ost tas!s (such as O"avac) deal with source5target out-o-datechec!ing internally, but there are cases where it is necessary to do this yoursel. Fore$ample, the J7nit test (see chapter = or in-depth coverage) tas! does no dependencychec!ing and simply runs all tests regardless o whether or not any .class iles weremodiied. /!ipping the unit test target i all the test related iles are up-to-date dramaticallyimproves build time without sacriicing integrated testing4

  • 8/10/2019 Ant and Maven.doc

    17/85

    Deferring the discussion of the +mapper, element for just a moment- this e&ample

    is setting the property tests.unnecessary to true if each module from the

    source tree is not ne"er than its corresponding .class file. /%his default is changed 0y

    specifying a !alue attri0ute.1 %his e&ample is sho"ing a one2to2one mapping from

    source file to target file- also ignoring any non2.ja!a files in the source tree. (ther scenarios

    ta3e ad!antage of many2to2one mappings or other more comple& mappings

    a!aila0le "ith the mappers. Com0ining the use of +uptodate, and conditional targets

    is a useful techni4ue to allo" your 0uild file to handle some dependency chec3ing

    that tas3s do not.

    #hemerge

    mapperin

    is not e$tremely useul since all iles get copied tothe same ile, with the last unpredictable ile becoming the sole new ile. #here is oneinteresting case, however, that is worthy o mention. I, or e$ample, you have a directocontaining a single ile whose name is not precisely !nown (perhaps with a timestampsui$), you can copy this ile to a !nown ile name using themerge mapper:

    Assume that there is a single ile in the data directory called data13333.dat, yetthis ile name is dynamically generated. #he use o the merge mapper will copy it tothe output directory with the name data.dat. #his particular techniue, remember, isonly useul with ilesets containing a single ile.

    Rege&p mapper

    #he !ing o all mappers, but over!ill or most cases, isregexp. #hefrom attributespeciies a regular e$pression. 2nly source iles matchingthe from patternareconsidered.#he target ile name is built using theto pattern with pattern substitutionsrom thefrom pattern, including\0 or the ull matched source ile name and\1through\9 or patterns matched with enclosing parenthesis in thefrom pattern.In order to use theregexp mapper, a regular e$pression library is needed. #he Ant

    documentation reers to several implementations. 9e recommend Ja!arta 2:2,although JD @.= comes with an implementation as well and is used by deault ipresent. /imply drop the JA: ile or the regular e$pression implementation intoA?#1&2+E5lib to have it automatically recogni8ed by Ant. &eres a simple e$amplehaving the same eect as theglob mappere$ampletomapall.java ilesto.java.bak iles:

    E$ample4

    ADDI%I('A# A'% DA%A%YP$S9e have covered the Ant datatypes that are reuently used by Ant tas!s, but there areeveral other datatypes that are used by a smaller number o tas!s.

    5ipFilesetSuilding an archive that contains the contents o other archive iles can be accomplishedusing the datat$pe. A not only allows puttingthe contents o one archive inside another, it also provides the capability to prei$an archives contents within another. For e$ample, when building the 9A: ile orour search engine application, we incorporate the Javadoc + in an api subdirectoryand our documentation under the help directory. #hese were not the directory

    names used during our build process, yet the 9A: ile will have these names in itsstructure.

  • 8/10/2019 Ant and Maven.doc

    18/85

    .

    .

    .

    #he tas!s that support the XipFileset datatype are , ,, an.

    PR(P$R%I$SCerhaps the most important concept to ully understand in Ant is its notion o propertiesCroperties are loosely analogous to variables in that they are mappings betweennames and values and, not coincidentally, are very similar conceptually to "ava.util.Croperties.Ant properties are typically, depending on the conte$t o their use, denoted by${property.name}within the build ile. #o e$amine the properties provided

    #his generates output similar to this4echo:

    [echo] ant.file = C:\AntBook\Sections\Learning\datatypes\properties.xml

    [echo] ant.home = c:\AntBook\jakarta-ant-1.5Beta1

    [echo] ant.java.version = 1.3

    [echo] ant.version = Apache Ant version 1.5Beta1 compiled on April 30 2002

    [echo] basedir = C:\AntBook\Sections\Learning\datatypes

    Built-in properties

    Name Defnitionant.file The absolute path of the build le.

    ant.home The path to executin% *ersion of Ant2s root director. ant.java.version The 134 *ersion Ant detected! currentl$ it can hold the *alu

    1.1, 1.2,

    1.3, and 1.4

    .ant.project.name The name of the pro0ect that is currentl$ executin%! it is set in thenam

    attribute of .

    ant.version. The *ersion of Ant

    basedir The absolute path of the pro0ect5s basedir (as set with thebasedirattribute of 6pro0ect7.

    #his e$ample was run with the-f command-line option to speciy a dierent build

    ile name as shown inant.file. Sy the time o publication, many o us will probablysee 1.4 for ant.java.version. #he latest release version o Ant at the time owriting was version @.B Seta, but it will be an oicial release by the time o publication

    #hebasedir property deaults to the path o the current build ile, and can bechanged by speciyingbasedir on the element or controlled e$ternallyusing property overrides as discussed shortly.Implicitly, all J0+ system properties are provided as Ant properties, allowing valuableinormation such as the users home directory path and the current username tobe utili8ed as desired. #he J0+ system properties will vary rom platorm-to-platorm,but there are many that you can rely on, or e$ample

  • 8/10/2019 Ant and Maven.doc

    19/85

    &ere are sample results rom running this code on a 9indows machine:[echo] user.name = erik

    [echo] user.home = C:\Documents and Settings\erik

    [echo] java.home = c:\jdk1.3.1\jre

    Setting properties "ith the +property, tas3#he tas! allows build iles to deine their own sets o custom properties.#he most common variants o creating properties are

    W ?ame5value attributesW oad a set o properties rom a properties ileW oad environment variables

    Setting and using a simple propertyA typical development-versus-production build dierence is in the enabling or disablingo debug mode on compilation. /ince we want a single build ile with a single tas!, we use a property to parameteri8e it. 9e deine a property named

    build.debug andset its valuetoon (the value that uses on its debuatribute).

    Enhancingthe example, we now ha*e this:

    #he obvious ne$t step is to vary that property valueG to begin, lets load propertiesrom a ile.

    #oading properties from a properties fileA useul method to provide coniguration and settings inormation to a build processis to load all name5value pairs rom a properties ile that creates internal Ant propertiesor each one. #o demonstrate4 we create a ile namedbuild.properties inthe root directory o our pro"ect, where our build ile lives. #his ile has the ollowingcontents4build.debug=off

    #o load it we use one o the variants o the tas!:

    Croperty values in the properties ile may also contain property reerences. For e$ampleconsider a properties ile containing these lines4build.dir=build

    output.dir=${build.dir}/output

    9hen loaded, output.dir will have the valuebuild/output. Forward-reerencingproperty values may be used in a single properties ile as wellG i the previous lineshad been in opposite order, the same results would be obtained. >ircular deinitionswill cause a build ailure.

    NOTE Croperties that reer to relative paths are best set using the locationvariant. /ee QFi$ing properties to absolute path locations.R Croperties setrom a properties ile are set as a simple values./ince properties are immutable, you may want to load properties rom a ile and prei$their name. In the last e$ample, had we usedprefix="temp", the propertiescreated would have been temp.build.dir and temp.output.dir. #his is a nicetric! toThe absolute path of the pro0ect5s basedir (as set with thebasedirattribute of 6pro0ect7.two property iles that may have the same named property, yet ensthat you have access to both values.

    (!erriding a property

    First, a little pop-ui8%e$amine the ollowing code lines and guess their outputgiven the properties ile "ust deined4

  • 8/10/2019 Ant and Maven.doc

    20/85

  • 8/10/2019 Ant and Maven.doc

    21/85

    W E$istence o a J0+ system resource

    Customi7ing Your Build Script Using Properties

    In development, people oten spea! o the D: (Dont :epeat oursel) principle. #his

    is a general principle aimed at ma!ing code more readable and easier to maintain byavoiding the duplication o data. In a Java application, or e$ample, !ey values that are

    used in several places, or that may need to be modiied easily, are stored as constantsor as parameters in a coniguration ile. #his ma!es the code easier to read and under-stand, and ma!es maintenance less o a headache.

    In Ant, you can do the same sort o thing by using the tag, which lets you

    declare constant values that can be used throughout the rest o your build ile. Declaringa property is straightorwardG you "ust need to provide a nameand valueattribute, asshown here4

    Oproperty nameKL"avac.debugL valueKLonL5

    I you are reerring to a directory, you can use the locationattribute instead o value4

    Oproperty nameKLbuild.dirL locationKLbuildL5

    #his property value will be set to the absolute ilename o the builddirectory.

    #o use a property elsewhere in the build ile, you "ust uote the name o the property

    surrounded by $"...#. For e$ample, you can subseuently reer to this property anywherein your build ile as $"build.dir#. ou could use the tas! to display the propertyvalue to the screen, as shown here4

    Otarget nameKLdisplay-propertiesL

    OechoDebug K UH"avac.debugNO5echo

    OechoSuild directory (build.dir) K UHbuild.dirNO5echo

    O5target

    >alling this target would display the value o this property on the console. 2n my

    machine, it displays the ollowing4

    $ ant display-properties

    Suildile4 build.$ml

    display-properties4

    echo Suild directory (build.dir) K 5home5"ohn5pro"ects5ta$-calculator5build

    S7ID /7>>E//F7

    #otal time4 seconds

    Another way to do this would be to use the tas!, which, as the name

    suggests, lets you display all o the current property values to the console4

    Otarget nameKLdisplay-propertiesL

    Oechoproperties 5

    O5target

    Croperties can also be used to ta!e into account environment dierences on each de-

    velopers machine. For e$ample, you may need to store a path to a local server or toapplication directories, which may be dierent on dierent machines. #o do this, youcan store local properties in an ordinary Java properties ile. #he ollowing directorieswould be dierent on 7ni$ and 9indows machines. 2n a inu$ development bo$,you might have the ollowing set o properties4

  • 8/10/2019 Ant and Maven.doc

    22/85

    chec!style.home K 5usr5local5tools5chec!style

    pmd.home K 5usr5local5tools5pmd

    indbugs.home K 5usr5local5tools5indbugs

    cobertura.home K 5usr5local5tools5cobertura

    2n a 9indows machine, by contrast, you might have something li!e this4

  • 8/10/2019 Ant and Maven.doc

    23/85

    chec!style.home K >4

    Oechochec!style.home K UHchec!style.homeNO5echo

    Oechopmd.home K UHpmd.homeNO5echo

    Oechoindbugs.home K UHindbugs.homeNO5echo

    Oechocobertura.home K UHcobertura.homeNO5echo

  • 8/10/2019 Ant and Maven.doc

    24/85

    9hen you run this, the property values will be loaded and integrated into the build ile4

    $ ant compile

    Suildile4 build.$ml

    echo chec!style.home K 5usr5local5tools5chec!style

    echo pmd.home K 5usr5local5tools5pmd

    echo indbugs.home K 5usr5local5tools5indbugs

    echo cobertura.home K 5usr5local5tools5cobertura ...

    ou can ma!e your build ile more robust by setting up sensible deault values or locally

    deined properties. 2ne very powerul eature o Ant properties (which has caused alot o conusion among ine$perienced Ant users) is immutability. 2nce deined, Antproperties cannot be modiied or the duration o the build, no matter how manytags reer to them aterward. In other words, the irst declaration o anyproperty wins.

    ets loo! at a practical e$ample. /uppose you deine a property called

    $"javac.debug#to indicate i you want to include debug inormation in your compiled

    classes. ou could do this as ollows4

    Oproperty nameKL"avac.debugL valueKLoL5

    ...

    Otarget nameKLcompileL dependsKLinitL descriptionKL>ompile Java codeL

    Oecho messageKLDebug4 UH"avac.debugNL 5

    O"avac srcdirKLUHsrc.dirNL

    destdirKLUHbuild.classes.dirNL

    classpathreKLcompile.classpathL

    debugKLUH"avac.debugNL5

    O5target

    9hen you run this, unsurprisingly, the $"javac.debug#property is set to QoR4

    $ ant compile

    Suildile4 build.$ml

    ...

    compile4

    echo Debug4 o

    S7ID /7>>E//F7

    #otal time4 seconds

    ?ow suppose you write a ile called local.properties that you store in your pro"ect

    directory. #his properties ile contains your own personal preerences or build optionssuch as debugging. In it, you stipulate that debugging should be on4

    "avac.debug K on

    And now we incorporate this properties ile into our build ile (note that we include

    the properties ile beforethe property declaration)4

  • 8/10/2019 Ant and Maven.doc

    25/85

    9hen you run the build again, the irst declaration o $"javac.debug#(in the properties

    ile) is considered deinitive, and the second (in the build ile) is ignored4

    $ ant compile

    Suildile4 build.$ml

    ...

    compile4

    echo Debug4 on

    S7ID /7>>E//F7

    #otal time4 seconds

    #he story doesnt end there, however. ou can override any property value rom the

    command line, using the -Dcommand-line option. For e$ample, here we override the$"javac.debug#property value to Qo.R #his will ta!e precedence over all other propertydeclarations4

    $ ant -Djavac.debugoff compile

    Suildile4 build.$ml

    init4

    compile4

    echo Debug4 o

    S7ID /7>>E//F7

    #otal time4 seconds

    8enerating Documentation "ith a!adoc

    #echnical documentation is an important part o any pro"ect, and Javadoc is one o the

    cornerstones o technical documentation in Java. Javadoc produces a uite decent,usable set o ACI documentation or your Java code, which can be a valuable aid as acommunication tool, helping team members understand what other team members aredoing. 2 course, good Javadoc reuires well-written and meaningul comments within

  • 8/10/2019 Ant and Maven.doc

    26/85

    the source code, and enorcing that is a tall order or any tool. And Javadoc documen-

    tation is by deinition low-level reerence material%it can be very useul or anapplication developer amiliar with the application, but it will be o limited use or anew developer trying to learn the application architecture. Despite these reservations,Javadoc should be an integral part o any development pro"ect.

    It is a good idea to generate Javadoc as part o your build process. Javadoc documen-tation should be generated and published alongside the compiled source code and theunit test results as part o the automatic build liecycle. In Ant, you can do this using

    the tas!. #his tas! has a lot o attributes and nested elements, but only aew are essential. &ere is a simple e$ample4

    Otarget nameKL"avadocL dependsKLcompile,initL descriptionKL'enerate JavaDocs.L

    O"avadoc sourcepathKLUHsrc.dirNL

    destdirKLUHreports."avadocNL

    authorKLtrueL

    versionKLtrueL

    useKLtrueL

    accessKLprivateL lin!sourceKLtrueL

    windowtitleKLUHant.pro"ect.nameN ACIL

    Oclasspath

    Opath reidKLcompile.classpathL 5

    Opathelement pathKLUHbuild.classes.dirNL 5

    O5classpath

    OdoctitleOZ>DA#[email protected]"ect.nameNO5h@O5doctitle

    ObottomOZ>DA#AOi>opyright [\@T]G 3; All :ights :eserved.

    O5iO5bottom

    O5"avadoc

    O5target

    #his tas! will generate Javadoc documentation or all the classes in the UHsrc.dirN

    directory. 9e needed to provide it with a classpath containing both the compiledclasses and the application dependencies. 9e did this using an embedded structure. 9e could also have deined this classpath elsewhere in the build ileand reerred to it using the classpathrefattribute.

    +ost o the other attributes used here are airly sel-e$planatory. #he listsourceattributecauses Ant to insert lin!s in the Javadoc document to the source code in + orm.#his is similar to the +aven J*: plugin, although the ormatting is less polished. #he

    accessproperty determines what parts o the classes should be documented. &ere wedocument everything, rom theprivateields up. I you want a more succinct view, you

    might want to limit the "avadoc to theprotectedor even to only thepublicields andmethods.

    #here are many other options or this tas!, ar too many, in act, to cover here. +ost

    involve ine-tuning ormatting details, and arent particularly interesting. ou can limit

    the classes being documented by providing a list o pac!ages in the packagenamesat-tribute, although i you separate your test classes rom your application source code,the reasons or doing so are generally more rare.

  • 8/10/2019 Ant and Maven.doc

    27/85

    Javadoc documentation is generated in the orm o a sel-contained web site. #his

    ma!es it easy to deploy to your local pro"ect web site, or to bundle up with your library,as most open source pro"ects do.

    Pac3aging Your Application

    2nce you have compiled and tested your application, the ne$t step is to bundle up the

    compiled code into a deliverable application or library. #his can ta!e dierent orms,depending on your pro"ect4 you may have to prepare a JA: ile, a 9A: ile, or possiblya XIC or #A: ile containing the e$ecutable code plus other iles such as documentationand source code. Ant has many powerul eatures that can help you prepare your ap-plication or delivery. In the ollowing sections, we will loo! at a ew o the moreinteresting ones.

    8enerating a AR File

    #he most undamental Java pac!aging mechanism is the JA: ile. A JA: ile is essen-tially a XIC ile containing a hierarchy o compiled Java classes, plus some metadata.9A: and EA: iles are similar, with some e$tra constraints on their internal directorystructure and content.

    #he basic usage o the tas! is simple. &ere is an e$ample rom our sample ap-

    plication, where we bundle the compiled classes into a JA: ile4

    Oproperty nameKLpro"ect.nameL valueKLHant.pro"ect.nameNL 5

    Oproperty nameKLpro"ect.versionL [email protected] 5

    ...

    Otarget nameKLpac!ageL dependsKLcompileL descriptionKL'enerate JA: ileL

    O"ar destileKLUHdist.dirN5UHpro"ect.nameN-UHpro"ect.versionN."arL basedirK LUHbuild.classes.dirNL5

    O5target

    :unning this will (surprise, surpriseZ) generate a JA: ile containing your compiled

    classes4

    $ ant clean package

    Suildile4 build.$ml

    clean4

    delete Deleting directory 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5dist

    delete Deleting directory 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5reports

    init4

    m!dir >reated dir4 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5dist

    m!dir >reated dir4 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5reports5$ml

    m!dir >reated dir4 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5reports5html

    compile4

  • 8/10/2019 Ant and Maven.doc

    28/85

    pac!age4

    "ar Suilding "ar4 5home5wa!aleo5pro"ects5"pt-sample-code5ant-demo5dist5

    ta$-calculator-@.."ar

    S7ID /7>>E//F7

    #otal time4 seconds

    9e use the +aven convention or naming JA: iles here, which is to add the version

    number to the end o the ilename. #his ma!es it easier to identiy ile versions at a

    glance. #he pro"ect name comes rom the ant.project.nameproperty, which is deinedin the Opro"ect root element. 7sing a dierent property means that developers areree to change the name o the generated JA: ile by overriding this variable.V

    I you need to deploy iles rom several dierent directories, you can use ele-

    ments to deine which iles to include. For e$ample, i you also want to include iles

    rom the src5resourcesdirectory, you could do the ollowing4

    Oproperty nameKLpro"ect.nameL valueKLHant.pro"ect.nameNL 5

    Oproperty nameKLpro"ect.versionL [email protected] 5 ...

    Otarget nameKLpac!ageL dependsKLcompileL descriptionKL'enerate JA: ileL

    O"ar destileKLUHdist.dirN5UHpro"ect.nameN-UHpro"ect.versionN."arL

    Oileset dirKLUHbuild.classes.dirNL5

    Oileset dirKLsrc5resourcesL5

    O5"ar

    O5target

    I we have a loo! inside the JA: ile generated by this tas!, we might notice the e$tra

    +E#A-I?F directory, which contains a ile called +A?IFE/#.+F. #his is wheremetadata about the version o the ile is stored, along with other details such as theproduct and vendor names4

    Ujar -tf dist!tax-calculator-&.'.jar

    +E#A-I?F5

    +E#A-I?F5+A?IFE/#.+F

    com5

    com5"avapowertools5

    com5"avapowertools5antdemo5

    com5"avapowertools5antdemo5domain5

    com5"avapowertools5antdemo5web5

    com5"avapowertools5antdemo5+ain.class

    com5"avapowertools5antdemo5domain5>ustomer.class

    com5"avapowertools5antdemo5domain5#a$>alculator.class

    com5"avapowertools5antdemo5domain5#a$:ate.class

    com5"avapowertools5antdemo5web5#a$>alculator>ontroller.clas...

    Sy deault, the +A?IFE/#.+F ile contains very little. A sample is shown here4

  • 8/10/2019 Ant and Maven.doc

    29/85

    +aniest-0ersion4 @.

    Ant-0ersion4 Apache Ant @.;.

    >reated-Sy4 @.T.-b@B (/un +icrosystems Inc.)

    &owever, this ile is a great place to put version and build numbers and5or timestamps.

    Cutting a version number and a build number (or timestamp) into your deployed pac!-ages is a good habit to get into%you never !now when you need to wor! out e$actlywhich build has "ust been deployed into production. In Ant, you can add e$tra detailsinto the +A?IFE/#.+F ile using the element in the tas!4

    Otarget nameKLpac!ageL dependsKLcompileL descriptionKL'enerate JA: ileL

    Otstamp

    Oormat propertyKLbuild.dateL patternKLEEEE, d ++++ yyyyL5

    Oormat propertyKLbuild.timeL patternKLhh4mm aL5

    O5tstamp

    O"ar destileKLUHdist.dirN5UHpro"ect.nameN-UHpro"ect.versionN."arL

    basedirKLUHbuild.classes.dirNL

    Omaniest

    Oattribute nameKLSuilt-SyL valueKLUHuser.nameNL5

    Oattribute nameKL/peciication-#itleL valueKLUHpro"ect.nameNL5

    Oattribute nameKL/peciication-0ersionL valueKLUHpro"ect.versionNL5

    Oattribute nameKL/peciication-0endorL valueKLA>+E IncorporatedL5

    Oattribute nameKLImplementation-#itleL valueKLcommonL5

    Oattribute nameKLImplementation-0ersionL valueKLUHpro"ect.versionN

    - built at UHbuild.timeN on UHbuild.dateN L5

    Oattribute nameKLImplementation-0endorL valueKLA>+E IncorporatedL5

    O5maniest

    O5"ar

    O5target

    &ere we use the tas! to generate a timestamp corresponding to the current

    time. #his tas! automatically sets three properties4 D()A*+, )()A*+, and

    ),DA. #he irst two (D()A*+and )()A*+) are set to the current date and time,respectively, in a airly machine-riendly (but not particularly readable) ormat (e.g.,Q3;Y3R and Q33=,R respectively). #he ),DAvalue is more readable (e.g., QAu-gust 3 3;R), but or a build date, we want something a little more precise. /o, weuse the nested element to set some properties o our own. #he deployed+A?IFE/#.+F ile will now loo! something li!e this4

    +aniest-0ersion4 @.

    Ant-0ersion4 Apache Ant @.;.

    >reated-Sy4 @.T.-b@B (/un +icrosystems Inc.)

    Suilt-Sy4 wa!aleo

    /peciication-#itle4 ta$-calculator

    /peciication-0ersion4 @./peciication-0endor4 A>+E Incorporated

    Implementation-#itle4 common

    Implementation-0ersion4 @. - built at @43T C+ on +onday, 3 August

    Implementation-0endor4 A>+E Incorporated

  • 8/10/2019 Ant and Maven.doc

    30/85

    8enerating a 9AR File or an $AR File

    9eb applications are usually distributed in the orm o a 9A: ile. 9A: iles can

    (usually) be deployed to any Java web server using a very simple deployment procedure.#he e$act procedure will vary rom one application server to another, but it is usuallysomething that can be done by a system administrator without a detailed understanding

    o the application.

    A 9A: ile is simply a JA: ile with a ew e$tra reuirements. In particular, a 9A:

    ile needs a special directory called 9ES-I?F, which contains application classes, libra-ries, and coniguration iles. Files placed under this directory cannot be accesseddirectly on the deployed web application, so this is a convenient place to put compiledclasses, libraries, coniguration iles, and J/C pages. #he basic directory structure o a9A: ile is illustrated in the ollowing table.

    A typical A/ directory structure

    Directory

    5

    9ES-I?F5

    Description

    Cublicly accessible web pages

    >oniguration iles, not visible rom the web site

    9ES-I?F5classes >ompiled classes

    9ES-I?F5lib Application libraries

    #he tas! is an e$tension o the tas! that ta!es into account the special

    structure o a 9A: ile. ou use special nested elements to deine the iles to go intothe 9ES-I?F5classes, 9ES-I?F5libor 9ES-I?Fdirectories.

    /uppose you need to generate a 9A: ile or a J/C-based web application. #he J/C ilesare stored in a directory called web. #his directory also contains the 9ES-I?F sub-directory, where we store the web.$mlile and any other coniguration iles we need.&owever, the application libraries and compiled classes will be obtained rom otherpro"ect directories.

    ou can create a 9A: ile rom this directory structure using the tas!, as shown

    here4

    Oproperty nameKLweb.dirL locationKLwebL 5

    Oproperty nameKLdist.dirL locationKLdistL 5

    Otarget nameKLwarL dependsKLcompileL descriptionKL'enerate 9A: ileL

    Owar destileKLUHdist.dirN5UHpro"ect.nameN-UHpro"ect.versionN.warL web$mlKLUHweb.dirN59ES-I?F5web.$mlL

    Oileset dirKLUHweb.dirNL 5

    Oclasses dirKLUHbuild.classes.dirNL5

    Olib dirKLUHlibNL

    Oinclude nameKLV."arL 5

    O5lib

    O5war

    O5target

  • 8/10/2019 Ant and Maven.doc

    31/85

    #he usage o this tas! is similar to the tas! we saw previously (see Q'enerating

    a JA: File,R earlier in this section), with a ew additions. #he most important conig-

    uration ile in the 9ES-I?F directory is the web.$ml ile. As can be seen here, you use theebxmlattribute to speciy the location o this ile.

    As with the tas!, you can use one or more elements to deine the iles

    you want to deploy in the root directory. In addition, the element deines theiles that will be placed in the 9ES-I?F5classes directory. And the element deinesthe application libraries to be deployed in the 9ES-I?F5libdirectory.

    i!e the tas!, the tas! will generate a +A?IFE/#.+File in the +E#A-I?F

    directory. And li!e the tas!, you can use the element to add e$trainormation into this ile.

    For more comple$ applications, a 9A: ile will not be enough. I you are developing

    an EJS-based application, you may need to deploy your application as an EA: ile. An

    EA: ile, li!e a 9A: ile, is an e$tension o the JA: ile ormat. Instead o a web.$ml

    ile, every EA: ile contains anapplication.$ml

    ile. #he Oear tas!, another e$tensiono the Ojar tas!, is airly easy to use. ou simply speciy the location o your applica-tion.$ml ile using the app$ml attribute, and then use one or more Ofileset elementsto indicate what iles need to be bundled. For e$ample, i you wanted to deploy theprevious 9A: ile, plus a ew particular JA: iles (stored in a directory speciied by the

    $"ear.lib#property), you could do the ollowing4

    Otarget nameKLearL dependsKLwarL descriptionKL'enerate EA: ileL

    Oear destileKLUHdist.dirN5UHpro"ect.nameN-UHpro"ect.versionN.earL

    app$mlKLsrc5metadata5application.$mlL

    Oileset ileKLUHdist.dirN5UHpro"ect.nameN-UHpro"ect.versionN.warL 5

    Oileset dirKLUHear.libNL

    Oinclude nameKLV."arL 5

    O5ileset

    O5ear

    O5target

    Deploying Your Application

    2nce you have generated a pac!aged version o your application, you will certainly

    want to deploy it. For e$ample, i you are developing a web application, you may wantto deploy it to a web server on your own machine, or to a remote server or testing. 2r,i you are developing a shared library, you may copy your latest version to a local web

    server, where other users can consult the documentation and download the ACI.

    Copying Files

    #he simplest way to deploy an application is to copy the pac!aged ile to the targetserver. 2 course, this will only wor! i the target server is hosted on the developmentmachine or i the target server has a shared drive that can be mapped to rom thedevelopment5build machine, and the current user has write access to these directories.

  • 8/10/2019 Ant and Maven.doc

    32/85

    Secause this is generally the case or a local development machine, this approach is

    oten a simple, pragmatic way to deploy (and redeploy) a web application to a locallyrunning application server. ou can copy a ile to another directory by using the

    tas!, as shown here4

    Oproperty nameKLtomcat.install.dirL locationKLUHuser.homeN5servers5tomcat

    5apache-tomcat-B.B.36L 5

    Otarget nameKLlocal.deployL dependsKLwarL descriptionKLDeploy to local

    #omcat instanceL

    Ocopy ileKLUHdist.dirN5UHpro"ect.nameN-UHpro"ect.versionN.warL

    todirKLUHtomcat.install.dirN5webappsL 5

    O5target

    In this e$ample, we simply deined a property pointing to a local #omcat installation,

    and used the tas! to copy the generated 9A: ile to the #omcat webappsdirectory, where #omcat will be able to pic! it up and deploy it automatically. +anyapplication servers wor! in the same way.

    2 course, you may want to rename the 9A: ile on the way. #ypically, you may wantto strip o the version number when you deploy the web application so that users can

    simply access the application using the pro"ect name. ou can do this using the tofileattribute instead o todir4

    Oproperty nameKLtomcat.install.dirL locationKLUHuser.homeN5servers5tomcat

    5apache-tomcat-B.B.36L 5

    Otarget nameKLlocal.deployL dependsKLwarL descriptionKLDeploy to local

    #omcat instanceL

    Ocopy ileKLUHdist.dirN5UHpro"ect.nameN-UHpro"ect.versionN.warL

    toileKLUHtomcat.install.dirN5webapps5UHpro"ect.nameN.warL 5

    O5target

    As you might e$pect, you arent limited to copying a single ile. ou can also use the

    tas! to copy sets o iles, using the usual Ant path-li!e tags. For e$ample, youmight want to deploy the latest Javadoc to a local Apache web server. /uppose your

    Apache servers web directory is 5var5www5public1html, with a special subdirectory oreach pro"ect. #he Javadoc needs to be deployed to a directory called"avadocdirectlyunderneath the pro"ect directory. I you are running Ant on the same machine as the

    Apache server, you could deploy your Javadoc simply using the tas!, as shownhere4

    Oproperty nameKLweb.dirL locationKL5var5www5public1htmlL 5

    Otarget nameKLlocal.documentationL dependsKL"avadocL

    descriptionKLDeploy documentation to local web serverL

    Ocopy todirKLUHweb.dirN5UHpro"ect.nameN5"avadocL

    Oileset dirKLUHreports."avadocL5

    O5copy

    O5target

  • 8/10/2019 Ant and Maven.doc

    33/85

    #he tas! is a powerul, le$ible tool or ile manipulation, and here we only

    cover its main eatures. >hec! out the Ant documentation or more details about whatit can do.

    (ther Deployment %echni4ues

    Ant provides many other ways to deploy your application. For e$ample, the tas!lets you deploy to an F#C server. And the tas! lets you deploy iles using thewidely used (/ecure >opy) />C protocol. A simple e$ample o the tas! is shownhere4

    Otarget nameKLremote.deployL dependsKLwarL

    descriptionKLDeploy to a remote integration server using />CL

    Oscp ileKLUHdist.dirN5UHpro"ect.nameN-UHpro"ect.versionN.warL

    todirKLuser^testserver45home5integration5tomcatbase5webappsL

    passwordKLpasswordL5

    O5target

    #here are also many third-party libraries that can help you here.

    Using Ant in $clipse

    Ant is well-supported in virtually all modern Java IDEs, and Eclipse is no e$ception.

    Eclipse allows you to create a new Eclipse pro"ect using an e$isting Ant ile, and rec-ogni8es the structure o Ant build iles. #he 2utline view gives you a structured visiono your build ile. In addition, you can e$ecute any target directly rom within Eclipseusing the conte$tual menu

  • 8/10/2019 Ant and Maven.doc

    34/85

    Using Ant in 'etBeans

    Ant integrates smoothly into ?etSeans. Indeed, by deault, ?etSeans uses Ant inter-

    nally to organi8e your pro"ect, even i you dont as! it to. ?etSeans automaticallyrecogni8es Ant build iles and displays the build ile targets. As in Eclipse, you cane$ecute targets directly using the conte$tual menu.

    Real time e&ample for 0uild.&ml - compiles the ej0 code- pac3ages to jar file and deploys to j0oss se

    +:&ml !ersion;

  • 8/10/2019 Ant and Maven.doc

    35/85

    +include name;

  • 8/10/2019 Ant and Maven.doc

    36/85

    +delete dir;

  • 8/10/2019 Ant and Maven.doc

    37/85

    Setting Up a Project Using *a!en

    *a!en and the De!elopment Build Process

    9e loo! at the second ma"or player in the Java build tools arena4

    +aven.+aven is an increasingly popular open source build management tool or en-terprise Java pro"ects, designed to ta!e much o the hard wor! out o the build process.+aven uses a declarative approach, in which the pro"ect structure and contents aredescribed, rather then the tas!-based approach used in Ant or in traditional +a!e ilesor shell scripts. +aven also strongly promotes the use o standard directory structuresand a well-deined build liecycle. #his helps enorce company-wide developmentstandards and reduces the time needed to write and maintain build scripts.

    +avens authors describe +aven as a Qpro"ect management ramewor!,R and it is in-

    deed much more than "ust a simple build scripting tool. +avens declarative, standards-based approach to pro"ect build management simpliies many aspects o the pro"ectliecycle. As well as catering or compiling, building, testing, and deploying yourapplication with a minimum o eort, +aven oers a number o other !ey advantages4

    W Cro"ect dependencies are declared and managed in a clean, transparent way, which

    reduces the ris! o dependency-related errors and ma!es or better documentation.

    W +aven lets you easily generate useul, high-uality, technical documentation and

    reports about the current state o the pro"ect and pro"ect team members. ?ote thatwe arent ta!ing about a good user manual, which is an altogether dierent issue,but, rather, about technical documentation, written by developers or developers.

    In many technical pro"ects, decent technical documentation is woeully inade-uate. It is nevertheless a vital part o modern sotware development, especiallywhen dislocated teams are involved.

    W +aven proposes a clear standard directory layout or source code, pro"ect resources

    and coniguration iles, generated output, and pro"ect documentation. #his ma!esit easier to understand new +aven pro"ects, and also ma!es the +aven build scriptscleaner and simpler.

    W +aven integrates smoothly with source code repositories, continuous integration

    servers, and issue trac!ing systems.

    W #he +aven build cycle is le$ible4 it is easy to integrate additional build tas!s, usinge$isting +aven plug-ins or by writing Ant scriptlets.All o these points ma!e +aven an invaluable tool or Java development teams

  • 8/10/2019 Ant and Maven.doc

    38/85

    *a!en and Ant

    9ithout a doubt, the most popular and most well-!nown build tool in the Java sphere

    is Ant. Ant is a ine tool and a hugely successul open source pro"ect.+illions o Java developers are amiliar with it. And, as we will see throughout the resto the boo!, there is hardly a Java tool in e$istence that doesnt integrate with Ant.

    &owever, when you write a lot o Ant build scripts, you ind yoursel as!ing yoursel(and other team members) the same uestions over and over again4 9here will thesource code goP 9hat about the unit testsP &ow do we handle dependenciesP &ow willwe bundle up the deliverable applicationP 9hat shall we call the main targetsP Indi-vidually, Ant lets you deal with each o these tas!s with a high degree o le$ibility andpower. &owever, you still have to write the tas!s rom scratch or duplicate and modiyan Ant script rom a previous pro"ect. And when you move to a new pro"ect or company,you need to as! these uestions once again to (begin to) understand the build processin place.

    +any (although not all) pro"ects do ollow airly common and well-!nown patterns. A

    lot o what you need to conigure in your build process is pretty much run-o-the-mill.It always seems a shame to redo the wor! again or each new pro"ect.

    +aven can help you here. +aven ta!es a lot o the grunt wor! out o the build process,

    and tries to lever the combined e$perience and best practice o a large community odevelopers. Sy adhering to a certain number o conventions and best practices, +avenlets you remove the drudgery o all the low-level tas!s in your build scripts. In the resto this chapter, we will see how.

    Installing *a!en

    In this chapter, we will go through how to install +aven 3 on various platorms. #hebasic installation process is straightorward, and is the same or all platorms. +aven

    is a pure Java tool, so irst o all you need to ensure that there is a recent version o Java(@.= or later) on your machine. #hen, download the latest distribution rom the +avendownload site and e$tract it into an appropriate directory. Finally, "ust add the binsubdirectory to the system path.

    I you are amiliar with installing Java tools, this should be enough to get you started.

    In the rest o this chapter, we discuss some more detailed environment-speciicconsiderations.

  • 8/10/2019 Ant and Maven.doc

    39/85

    Installing *a!en on a Uni& *achine

    9e run through how to install +aven into a 7ni$ environment.

    Installing +aven in a 7ni$-based environment is a relatively simple tas!. Download

    the latest version in the ormat o your choice, and e$tract it to an appropriate directory.

    >onventions vary greatly rom one system to another, and rom one system adminis-trator to another4 I generally place the maven installation in a nonuser-speciic directorysuch as 5usr5local, as shown here4

    \ cd 5usr5local

    \ tar $v8 maven-3..;-bin.tar.g8

    \ ls

    #his will e$tract the maven installation in a directory called maven-3..;. For conven-

    ience, on a 7ni$ system, I generally create a symbolic lin! to this directory to ma!eupgrades easier to manage4

    \ ln -s maven-3..; maven

    \ ls -altotal @T

    drw$r-$r-$ 6 root root =]T 3T-Y-T @64@Y .

    drw$r-$r-$ B6 root root =]T 3T-;-3 3@463 ..

    lrw$rw$rw$ @ root root @@ 3T-Y-T @64@; maven - maven-3..;

    drw$r-$r-$ T root root =]T 3T-Y-T @64@; maven-3..;

    ?ow "ust add the maven5bin directory to your environment path. #ypically, you will set

    this up in one o your environment initiali8ation scripts (or e$ample, i you are usingSash, you could place this coniguration in the _5.bashrc ile i you "ust need to set itup or your account, or in 5etc5bashrc i you want to set it up or all users on this

    machine). Dont orget to ma!e sure that the JA0A1&2+E environment variable is deined

    as well. &ere is a typical e$ample4CA#&KUCA#&45usr5local5maven5bin

    JA0A1&2+EK5usr5lib5"vm5"ava

    e$port CA#& JA0A1&2+E

    ?ow chec! that it wor!s by running the mavencommand rom the command line4

    \ mvn --version

    +aven version4 3..;

  • 8/10/2019 Ant and Maven.doc

    40/85

  • 8/10/2019 Ant and Maven.doc

    41/85

    Installing *a!en on a 9indo"s *achine

    Installing +aven on a 9indows machine is also relatively straightorward, although

    the application still lac!s the graphical installation pac!age amiliar to 9indows users.First, download and un8ip the +aven distribution into an appropriate directory. +ost9indows machines will have a graphical compression utility that you can use to e$tractthe XIC ile, although i you are stuc!, you can always use the Java "ar command-linetool, as shown here4

    >4 "ar -$ maven-3..=-bin.8ip

    In t, +aven has been installed in the C4

  • 8/10/2019 Ant and Maven.doc

    42/85

    compiled classes will be placed, and creating a classpath that contains any dependenciesneeded to compile your classes. Seore invo!ing the compiler, you need to be sure tocreate the target directory. #he corresponding Ant script might loo! something li!e this4

    Opro"ect nameKL!iller-appL

    ...

    Oproperty nameKLsrc.dirL locationKLsrc5main5"avaL5 Oproperty nameKLtarget.dirL locationKLtarget5classesL5

    ...

    Opath idKLcompile.classpathL

    Oileset dirKLlibL

    Oinclude nameKLVV5V."arL5

    O5ileset

    O5path

    ...

    Otarget nameKLinitL

    Om!dir directoryKLUHtarget.dirNL5

    O5target

    Otarget nameKLcompileL dependsKLinitL descriptionKL>ompile the application classesL

    O"avac srcdirKLUHsrc.dirNL

    destdirKLUHtarget.dirNL

    classpathreKLcompile.classpathL

    [email protected]

    [email protected]

    5

    O5target

    O5pro"ect

    #o compile your application, you would invo!e the QcompileR target4

    U ant compile

    In +aven, the build ile or this pro"ect would be somewhat dierent. First o all, you

    would not need to declare the source and target directories.In act, the only thing that we need t

    speciy is that our pro"ect code is written using Java B language eatures, or a Java B J0+.+aven uses components called plug-ins to do most o the serious wor!. #he plug-in

    that handles Java compilation is called maven-compiler-plugin. /o, to set up Java com-pilation in our +aven script, all we need to do is to conigure this plug-in, which wedo as ollows4

    Opro"ect...

    ...

    Obuild

    Oplug-ins

    OZ-- 7sing Java B --

    Oplugin

    OartiactIdmaven-compiler-pluginO5artiactId

    Oconiguration

    [email protected]

    [email protected]

    O5coniguration

    O5plugin

    O5plug-ins O5build

  • 8/10/2019 Ant and Maven.doc

    43/85

    ...

    O5pro"ect

    ?ote that had we been using the deaultjavacsource and target values, even this con-

    iguration would not have been needed.

    #he one thing that we glossed over here is the +aven euivalent o the libdirectory.

    In Ant, the libraries reuired by a pro"ect are stored in a local pro"ect directory, otencalled lib. In the above e$ample, we deined a classpath called compile.classpath, whichincluded all the JA: iles in this directory.

    +aven uses a totally dierent approach. In +aven, JA: iles are rarely, i ever, stored

    in the pro"ect directory structure. Instead, dependencies are declared within the buildscript itsel.

    An e$tract rom a list o +aven dependencies is shown here4

    Opro"ect...

    ...

    OZ-- C:2JE># DECE?DE?>IE/ --

    Odependencies

    OZ-- &ibernate --

    Odependency

    OgroupIdorg.hibernateO5groupId

    OartiactIdhibernateO5artiactId

    Oversion6.3.=.O5version

    O5dependency

    OZ-- og=" --

    Odependency

    OgroupIdlog="O5groupId

    OartiactIdlog="O5artiactId [email protected].@=O5version

    O5dependency

    ... O5dependencies

    O5pro"ect

    Dependency management is a ma"or eature o +aven 3, and we loo! at it in much

    more detail in Q+anaging #ransitive DependenciesQ in ch3-dependency-manage-ment.

    #he third part o our C2+ ile contains inormation that is largely irrelevant or the

    tas! at hand (compiling our Java class), but will come in handy later on. At the start oeach +aven C2+ ile, you will ind a list o descriptive elements describing things li!ethe pro"ect name, version number, how it is to be pac!aged, and so on. #his is shown

    here4

    Opro"ect...

    OZ-- C:2JE># DE/>:IC#I2? --

    Omodel0ersion=..O5model0ersion

    OgroupIdcom.mycompanyO5groupId

    OartiactIdmyappO5artiactId

    Opac!aging"arO5pac!aging

    Onameiller applicationO5name

    [email protected]

    Odescription+y new !iller appO5description

    ...

    O5pro"ect

    &ere is the complete corresponding +aven build ile4

  • 8/10/2019 Ant and Maven.doc

    44/85

    OP$ml [email protected] encodingKL7#F-YLP

    Opro"ect $mlnsKLhttp455maven.apache.org5C2+5=..L

    $mlns4$siKLhttp455www.w6.org53@5*+/chema-instanceL

    $si4schemaocationKLhttp455maven.apache.org5C2+5=.. http455maven.apache.org

    5maven-v=11.$sdL

    OZ-- C:2JE># DE/>:IC#I2? --

    Omodel0ersion=..O5model0ersion

    OgroupIdcom.mycompanyO5groupId OartiactIdmyappO5artiactId

    Opac!agingwarO5pac!aging

    Onameiller applicationO5name

    [email protected]

    Odescription+y new !iller appO5description

    OZ-- S7ID >2?FI'7:A#I2? --

    Obuild

    Oplug-ins

    Oplugin

    OartiactIdmaven-compiler-pluginO5artiactId

    Oconiguration

    [email protected] [email protected]

    O5coniguration

    O5plugin

    O5plug-ins

    O5build

    OZ-- C:2JE># DECE?DE?>IE/ --

    Odependencies

    OZ-- &ibernate --

    Odependency

    OgroupIdorg.hibernateO5groupId

    OartiactIdhibernateO5artiactId

    Oversion6.3.=.O5version

    O5dependency

    OZ-- og=" --

    Odependency

    OgroupIdlog="O5groupId

    OartiactIdlog="O5artiactId

    [email protected].@=O5version

    O5dependency

    ...

    O5dependencies

    O5pro"ect

    /o a +aven build ile is not necessarily any shorter than an Ant build ile or an euiv-

    alent pro"ect. Sut the nature o the inormation it contains is very dierent. Ant userswill notice that there is no sign o any target-li!e structures, or any indication o whatgoals can be run4V

    U mvn compile

    In a similar manner, this same build ile can be used to run the applications unit tests,

    stored by convention in the src5test5"avadirectory, by invo!ing the QtestR goal4

    Umvn test

    And this same build ile can be used to bundle up a JA: ile containing the compiled

    classes, via the Qpac!ageR goal4U mvn package

  • 8/10/2019 Ant and Maven.doc

    45/85

    #here are many other goals. 9e will cover the main ones in the remainder o this

    chapter, and in the other +aven-related chapters o this boo!.

    #his illustrates another o +avens strong points4 all o these goals are standard +aven

    goals and will wor! in a similar way on any +aven pro"ect.

    As can be gleaned here, one o the guiding principles o +aven is to use sensible deault

    values wherever possible. #his is where the +aven conventions play an important role.

    +aven pro"ects are e$pected to respect a certain number o conventions, such as placingyour main source code in the src5main5"ava directory and your test code in the

    src5main5test directory. #hese conventions are largely deined in aspecial C2+ ile, the so-called /uper C2+, rom which every C2+ is e$tended. Inpractice, this means that i you respect the standard +aven conventions, you can getaway with surprisingly little in your C2+ ile.

    Project Conte&t and Artifacts

    #he irst part o a C2+ ile basically introduces the pro"ect and its conte$t, including

    the group and artiact IDs that uniuely identiy this pro"ect in the +aven world, as

    well as how the artiact is pac!aged ("ar, war, ear`), and the current version number.#his is a small but crucial part o the +aven C2+ ile, in which you deine many !eyaspects o your pro"ect. A typical e$ample is shown here4

    Opro"ect $mlnsKLhttp455maven.apache.org5C2+5=..L

    $mlns4$siKLhttp455www.w6.org53@5*+/chema-instanceL

    $si4schemaocationKLhttp455maven.apache.org5C2+5=..

    http455maven.apache.org5maven-v=11.$sdL

    Omodel0ersion=..O5model0ersion

    OgroupIdcom.mycompany.accountingO5groupId

    OartiactIdaccounting-coreO5artiactId

    Opac!aging"arO5pac!aging Oversion@.@O5version

    ...

    #he inormation in this section is used to identiy the pro"ect uniuely and, in particular,

    the artiact that it produces. #his is one o the hallmar!s o +aven, and it is what enablesyou to deine very precisely your pro"ects dependencies. Indeed, the inormation in this sectionallows +aven to derive a uniue path to the artiact generated by this pro"ect..

    com5mycompany5accounting5accounting-core5@.@5accounting-core-@.@."ar

  • 8/10/2019 Ant and Maven.doc

    46/85

    com5mycompany5accounting groupid

    accounting-core articatId

    @.@ versionId

    accounting-core artiactId

    "ar pac!aging

    ets loo! at how +aven does this in a little more detail.

    #he element is supposed to identiy a particular pro"ect or set o libraries

    within a company or organi8ation. Sy convention, it oten corresponds to the initialpart o the Java pac!age used or the application classes (e.g., Qorg.apache.mavenR or+aven pro"ects, Qorg.springramewor!R or the /pring libraries, and so on), althoughthis is not always the case. 9hen the artiact is deployed to a +aven repository, the

    group0dis split out into a matching directory structure on the repository.

    #he artifact0drepresents the actual name o the pro"ect. #his, combined with the

    group0d, should uniuely identiy the pro"ect.

    Every pro"ect also has a element, which indicates the current version number.

    #his number usually reers to ma"or releases (Q&ibernate 6.3.=,R Q/pring 3..B,R andso on), as opposed to speciic build numbers, which are dierent or each build. Eachversion has its own directory on the +aven repository, which is a subdirectory o thepro"ect directory.

    /o, in the above e$ample, the generated artiact would be stored on the +aven repo-

    sitory in a directory called com5mycompany5accounting5accounting-core5@.@.

    9hen it comes to inally generating a deliverable pac!age, +aven supports many di-

    erent ile ormats. At the time o this writing, supported pac!age types included pom,

    "ar, maven-plugin, e"b, war, ear, rar, and par. As the name suggests, you use the

    element to indicate the pac!aging type. For e$ample, in this listing, +aven

    will generate a ile called accounting-core-@.@."ar. #he Q"arR e$tension comes rom theelement. +aven saves you the hassle o !nowing e$actly what iles needto go into the delivered pac!age and what iles were delivered. All you need to do isprovide the type and +aven will do the rest.

    Finally, there is an optional element called that can be used to distinguish

    dierent distributions o the same version o a product. For e$ample, you might havea distribution or Java @.=, and a dierent distribution or Java B. #he #est?' unit

    testing library does "ust this. #he pro"ect description or the Java B version o this prod-uct might contain something li!e this4

    OgroupIdorg.testngO5groupId

    OartiactIdtestngO5artiactId

    Opac!aging"arO5pac!aging

    OversionB.BO5version

    Oclassiier"d!@BO5classiier

    #his would produce a ile called testng-B.@-"d!@B."ar. #he euivalent version or Java

    @.= would be testng-B.@-"d!@=."ar.

    *anaging Dependencies2ne o the most powerul +aven eatures is the way it handles dependencies. A typical

  • 8/10/2019 Ant and Maven.doc

    47/85

    medium-si8e Java pro"ect can reuire do8ens, or even hundreds, o JA: iles. 9ithouta strict dependency management strategy, this can uic!ly become out o control. Itcan rapidly become diicult to !now e$actly what library versions a particular pro"ectis using, and conlicting dependency reuirements can trigger hard-to-ind errors.+aven addresses these issues using a two-pronged approach, based on the notions odeclarative dependencies and a central repository o JA: iles.

    In +aven, a pro"ects dependencies are declared in the pom.xml ile. #he

    section, shown here, lets you list the libraries that your applicationneeds to compile, be tested, and be run. Dependencies are deined using the +avenartiact naming schema (see QCro"ect >onte$t and Artiacts,R earlier in this section),which allows you to precisely identiy the e$act version o each library you need. Inaddition, you usually only need to list the libraries you need directly to compile yourcode4 with a eature called #ransitive Dependencies +aven 3 will discover and retrieve anyadditional libraries that thoselibraries need to wor!.

    &ere is a simple e$ample o the dependencies section in a C2+ ile4

    ...

    Odependencies

    Odependency

    OgroupIdorg.hibernateO5groupId

    OartiactIdhibernateO5artiactId

    Oversion6.@O5version

    O5dependency

    Odependency

    OgroupId"unitO5groupId

    OartiactId"unitO5artiactId

    Oversion6.Y.@O5version

    OscopetestO5scope

    O5dependency O5dependencies

    ...

  • 8/10/2019 Ant and Maven.doc

    48/85

    9e are saying that our application reuires &ibernate 6.@ (and, implicitly, all the other

    libraries that this version o &ibernate reuires). And, to run our unit tests, we needJ7nit 6.Y.@.

    Customi7ing Your Build Process

    Although optional, the section is a !ey part o any but the simplest o C2+iles. #his section is where you tailor your +aven pro"ect build process to your e$actneeds, deining various plug-in conigurations and setting up additional tas!s that needto be perormed at various points in the build liecycle.

    #he +aven build process is very le$ible, and it is easy to integrate new tas!s by using

    plug-ins. Clug-ins are a powerul way to encapsulate build logic into reusable compo-nents, or use in uture pro"ects. ou may use plug-ins to generate source code rom a9/D ile or rom &ibernate mappings, or e$ample. +any plug-ins are available, bothrom the +aven web site and rom other third-party providers such as >odehaus.V

    Secause they are used e$tensively in the standard +aven build liecycle tas!s, you also

    can use plug-ins to customi8e e$isting aspects o the +aven liecycle. A common e$-ample o this type o coniguration, shown in the e$ample below, is to conigure the

    maven-compiler-plugin, which compiles the pro"ect source code or use with Java B (bydeault, the +aven compiler generates code compatible with JD @.6).

    #he section is also where resource directories are deined. ou also can deine

    resources that will be bundled into the inal pac!age produced by the pro"ect, andresources that need to be on the classpath during unit tests. Sy deault, any iles placed

    in the src5main5resources will be pac!aged into the generated pro"ect artiact. Any iles

    in src5test5resources will be made available on the pro"ect classpath during unit tests.

    ou also can add additional resource directories. In the ollowing e$ample, we set upan additional resource directory or &ibernate mapping iles. At build-time, these ilesautomatically will be bundled into the resulting pro"ect artiact, along with the com-piled classes and other resource iles.

    #he ollowing listing illustrates a typical build section, illustrating these e$amples4

    ...

    Obuild

    Oplug-ins

    Oplugin

    OgroupIdorg.apache.maven.plug-insO5groupId

    OartiactIdmaven-compiler-pluginO5artiactId

  • 8/10/2019 Ant and Maven.doc

    49/85

    Oconiguration

    [email protected]

    [email protected]

    O5coniguration

    O5plugin

    O5plug-ins

    Oresources

    Oresource Odirectorysrc5main5hibernateO5directory

    O5resource

    O5resources

    O5build

    ...

    Setting Up Reporting

    An important part o any pro"ect is internal communication. Although it is not a silver

    bullet, a centrali8ed technical pro"ect web site can go a long way toward improvingvisibility within the team, especially with large or geographically dispersed teams. #he

    site generation unctionality in +aven 3 lets you set up a proessional-uality pro"ectweb site with little eort.

    ou use the section to conigure options or +aven site generation. In the

    absence o any reporting section, +aven will generate a simple site with inormationabout the pro"ect derived rom the inormation provided in the C2+ ile. #he

    section lets you add many other additional reports, such as "avadoc, unittest results, >hec!style or C+D reports, an