Get More Refcardz! Visit refcardz.com #55 CONTENTS INCLUDE: The MVN Command Project Object Model Dependencies Plugins Debugging Profiles and more... n n n n n n Apache Maven 2 By Matthew McCullough <project> <modelVersion>4.0.0</modelVersion> <groupId>com.ambientideas</groupId> <artifactId>barestbones</artifactId> <version>1.0-SNAPSHOT</version> </project> About Apache Maven Maven is a comprehensive project information tool, whose most common application is building Java code. Maven is often considered an alternative to Ant, but as you’ll see in this Refcard, it offers unparalleled software lifecycle management, providing a cohesive suite of verification, compilation, testing, packaging, reporting, and deployment plugins. Super POM The Super POM is a virtual pom.xml file that ships inside the core Maven JARs, and provides numerous default settings. All projects automatically inherit from the Super POM, much like the Object super class in Java. Its contents can be viewed in one of two ways: Maven is receiving renewed recognition in the emerging development space for its convention over configuration approach to builds. This Refcard aims to give JVM platform developers a range of basic to advanced execution commands, tips for debugging Mavenized builds, and a clear introduction to the “Maven vocabulary”. View Super POM via SVN Open the following SVN viewing URL in your web browser: http://svn.apache.org/repos/asf/maven/components/branches/maven2.1.x/pom.xml View Super POM via effective-pom w ww.dzone.com Interoperability and Extensibility Run the following command in a directory that contains the most minimal Maven project pom.xml, listed above. New Maven users are pleasantly surprised to find that Maven offers easy-to-write custom build-supplementing plugins, reuses any desired aspect of Ant, and can compile native C, C++, and .NET code in addition to its strong support for Java and JVM languages and platforms, such as Scala, JRuby, Groovy and Grails. Hot Tip mvn help:effective-pom Multi-module Projects Maven showcases exceptional support for componentization via its concept of multi-module builds. Place sub-projects in sub-folders beneath your top level project and reference each with a module tag. To build all sub projects, just execute your normal mvn command and goals from a prompt in the top-most directory. All things Maven can be found at http://maven.apache.org <project> <!-- ... --> <packaging>pom</packaging> <modules> <module>servlets</module> <module>ejbs</module> <module>ear</module> </modules> </project> The mvn command Apache Maven 2 Maven supplies a Unix shell script and MSDOS batch file named mvn and mvn.bat respectively. This command is used to start all Maven builds. Optional parameters are supplied in a space-delimited fashion. An example of cleaning and packaging a project, then running it in a Jetty servlet container, yet skipping the unit tests, reads as follows: Get More Refcardz (They’re free!) Authoritative content Designed for developers n Written by top experts n Latest tools & technologies n Hot tips & examples n Bonus content online n New issue every 1-2 weeks n mvn clean package jetty:run –Dmaven.test.skip n Project object model The world of Maven revolves around metadata files named pom.xml. A file of this name exists at the root of every Maven project and defines the plugins, paths and settings that supplement the Maven defaults for your project. Subscribe Now for FREE! Refcardz.com Basic pom.xml Syntax The smallest valid pom.xml, which inherits the default artifact type of “jar”, reads as follows: DZone, Inc. | www.dzone.com 2 Artifact Vector Apache Maven 2 Conversely, if you ask Maven to execute a phase, all phases and bound plugin goals up to that point in the lifecycle are also executed. This example requests the deploy lifecycle phase, which will also execute the verification, compilation, testing and packaging phases. Each Maven project produces an element, such as a JAR, WAR or EAR, uniquely identified by a composite of fields known as groupId, artifactId, version, type, and an optional classifier. This vector of fields uniquely distinguishes a Maven artifact from all others. mvn deploy Many Maven reports and plugins print the details of a specific artifact in this colon separated fashion: Online and Offline During a build, Maven attempts to download any uncached referenced artifacts and proceeds to cache them in the ~/.m2/ repository directory on Unix, or in the %USERPROFILE%/.m2/ repository directory on Windows. groupid:artifactid:type:version:scope An example of this output for the core Spring JAR would be: org.springframework:spring:jar:2.5.6:compile To prepare for compiling offline, you can instruct Maven to download all referenced artifacts from the Internet via the command: Execution Groups Maven divides execution into four nested hierarchies. From most-encompassing to most-specific, they are: Lifecycle, Phase, Plugin, and Goal. mvn dependency:go-offline If all required artifacts and plugins have been cached in your local repository, you can instruct Maven to run in offline mode with a simple flag: Lifecycles, Phases, Plugins and Goals Maven defines the concept of language-independent project build flows that model the steps that all software goes through during a compilation and deployment process. mvn <phase or goal> -o Built-in Maven Lifecycles Maven ships with three lifecycles; clean, default, and site. Many of the phases within these three lifecycles are bound to a sensible plugin goal. Hot Tip The official lifecycle reference, which extensively lists all the default bindings, can be found at http://maven.apache.org/guides/introduction/ introduction-to-the-lifecycle.html The clean lifecycle is simplistic in nature. It deletes all generated and compiled artifacts in the output directory. Clean Lifecycle Lifecycle Phase represent a well-recognized flow of steps (Phases) used in software assembly. Lifecycles Remove all generated and compiled artifacts in preperation for a fresh build. clean Each step in a lifecycle flow is called a phase. A phase is bound to zero or more plugin goals. post-clean The default lifecycle defines the most commonly used phases for building an application, ranging from compilation of the code to installation of the completed artifacts, such as a JAR, into a remote Maven repository. A plugin is a logical grouping and distribution (often a single JAR) of related goals, such as JARing. A goal, the most granular step in Maven, is a single executable task within a plugin. For example, discrete goals in the jar plugin include packaging the jar (jar:jar), signing the jar (jar:sign), and verifying the signature (jar:sign-verify). Default Lifecycle Lifecycle Phase At the command prompt, either a phase or a plugin goal can be requested. Multiple phases or goals can be specified and are separated by spaces. If you ask Maven to run a specific plugin goal, then only that goal is run. This example runs two plugin goals: compilation of code, then JARing the result, skipping over any intermediate steps. mvn compile:compile jar:jar | Purpose validate Cross check that all elements necessary for the build are correct and present. initialize Set up and bootstrap the build process. generate-sources Generate dynamic source code process-sources Filter, sed and copy source code generate-resources Generate dynamic resources process-resources Filter, sed and copy resources files. compile Compile the primary or mixed language source files. process-classes Augment compiled classes, such as for code-coverage instrumentation. generate-test-sources Generate dynamic unit test source code. Executing a Phase or Goal DZone, Inc. Purpose pre-clean www.dzone.com 3 process-test-sorces Filter, sed and copy unit test source code. generate-test-resources Generate dynamic unit test resources. process-test-resources Filter, sed and copy unit test resources. test-compile Compile unit test source files test Execute unit tests prepare-package Manipulate generated artifacts immediately prior to packaging. (Maven 2.1 and above) package Bundle the module or application into a distributable package (commonly, JAR, WAR, or EAR). Hot Tip Execute tests that require connectivity to external resources or other components post-integration-test verify Inspect and cross-check the distribution package (JAR, WAR, EAR) for correctness. install Place the package in the user’s local Maven repository. deploy Upload the package to a shared Maven repository. Standard Scopes Each dependency can specify a scope, which controls its visibility and inclusion in the final packaged artifact, such as a WAR or EAR. Scoping enables you to minimize the JARs that ship with your product. The site lifecycle generates a project information web site, and can deploy the artifacts to a specified web server or local path. Site Lifecycle Lifecycle Phase Purpose pre-site Cross check that all elements necessary for the build are correct and present. site Generate an HTML web site containing project information and reports. post-site site-deploy You can use the search engine at www.mvnrepository.org to find dependencies by name and get the xml necessary to paste into your pom.xml <project> <dependencies> <dependency> <groupId>com.yourcompany</groupId> <artifactId>yourlib</artifactId> <version>1.0</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies> <!-- ... --> </project> pre-integration-test integration-test Apache Maven 2 Scope Description compile Needed for compilation, included in packages. test Needed for unit tests, not included in packages. provided Needed for compilation, but provided at runtime by the runtime container. system Needed for compilation, given as absolute path on disk, and not included in packages. import An inline inclusion of a POM-type artifact facilitating dependency-declaring POM snippets. Upload the generated web site to a shared HTML server. Default Goal Plugins The default goal codifies the author’s intended usage of the build script. Only one goal or lifecycle can be set as the default. The most common default goal is install. Adding a Plugin A plugin and its configuration are added via a small declaration, very similar to a dependency, in the <build> section of your pom.xml. <project> [...] <build> <defaultGoal>install</defaultGoal> </build> [...] </project> <build> <!-- ... --> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <configuration> <maxmemory>512m</maxmemory> </configuration> </plugin> </plugins> </build> Help Help for a Plugin Lists all the possible goals for a given plugin and any associated documentation. Common Plugins Maven created an acronym for its plugin classes that aggregates “Plain Old Java Object” and “Maven Java Object” into the resultant word, Mojo. mvn help:describe –D<pluginname> Help for POMs To view the composite pom that’s a result of all inherited poms: There are dozens of Maven plugins, but a handful constitute some of the most valuable, yet underused features: mvn help:effective-pom Help for Profiles To view all profiles that are active from either manual or automatic activation: mvn help:active-profiles surefire Runs unit tests. checkstyle Checks the code’s styling clover Code coverage evaluation. enforcer Verify many types of environmental conditions as prerequisites. assembly Creates ZIPs and other distribution packages of apps and their transitive dependency JARs. Dependencies Hot Tip Declaring a Dependency To express your project’s reliance on a particular artifact, you declare a dependency in the project’s pom.xml. DZone, Inc. | The full catalog of plugins can be found at: http://maven.apache.org/plugins/index.html www.dzone.com 4 Apache Maven 2 Predefined Properties (Partial List) Visualize Dependencies Users often mention that the most challenging task is identifying dependencies: why they are being included, where they are coming from and if there are collisions. Maven has a suite of goals to assist with this. List a hierarchy of dependencies. mvn dependency:tree List dependencies in alphabetic form. mvn dependency:resolve ${env.PATH} Any OS environment variable such as EDITOR, or GROOVY_ HOME. Specifically, the PATH environment variable. ${project.groupId} Any project node from the aggregated Maven pom.xml. Specifically, the Group ID of the project ${project.artifactId} Name of the artifact. ${project.basedir} Path of the pom.xml. ${settings. localRepository} The path to the user’s local repository. ${java.home} Any Java System Property. Specifically, the Java System Property path to its home. ${java.vendor} The Java System Property declaring the JRE vendor’s name. ${my.somevar} A user-defined variable. List plugin dependencies in alphabetic form. mvn dependency:resolve-plugins Analyze dependencies and list any that are unused, or undeclared. Hot Tip mvn dependency:analyze Repositories Project properties could previously be referenced with a ${pom.basedir} prefix or no prefix at all ${basedir}. Maven now requires that you prefix these variables with the word project ${project. basedir}. Define a Property You can define a new custom property in your pom.xml like so: Repositories are the web sites that host collections of Maven plugins and dependencies. <project> [...] <properties> <my.somevar>My Value</my.somevar> </properties> [...] </project> Declaring a Repository <repositories> <repository> <id>JavaDotNetRepo</id> <url>https://maven-repository.dev.java.net</url> </repository> </repositories> Debugging The Maven community strongly recommends using a repository manager such as Nexus to define all repositories. This results in cleaner pom.xml files and centrally cached and managed connections to external artifact sources. Nexus can be downloaded from http://nexus.sonatype.org/ Exception Full Stack Traces If a Maven plugin is reporting an error, to see the full detail of the exception’s stack trace run Maven with the -e flag. Popular Repositories mvn <yourgoal> -e Central http://repo1.maven.org/maven2/ Output Debugging Info Java.net https://maven-repository.dev.java.net/ Codehaus http://repository.codehaus.org/ Whenever reporting a Maven bug, or troubleshooting a problem, turn on all the debugging info by running Maven like so: JBoss http://repository.jboss.org/maven2 mvn <yourgoal> -X Debug Maven Core/Plugins� Hot Tip Core Maven operations and plugins can be stepped through with any JPDA-compatible debugger, the most common option being Eclipse. When run in debug mode, Maven will wait for you to connect your debugger to socket port 8000 before continuing with its lifecycle. A near complete list of repositores can be found at http://www.mvnbrowser.com/repositories.html Property Variables mvnDebug <yourgoal> A wide range of predefined or custom of property variables can be used anywhere in your pom.xml files to keep string and path repetition to a minimum. Preparing to Execute Maven in Debug Mode Listening for transport dt_socket at address: 8000 Debug a Unit Test Your suite or an individual unit test can be debugged in much the same fashion by telling the Surefire test-execution plugin to wait for you to attach a debugger to port 5005. All properties in Maven begin with ${ and end with }. Hot Tip To list all abailable properties, type mvn help:expresions at the command prompt. mvn test -Dmaven.surefire.debug Listening for transport dt_socket at address: 5005 DZone, Inc. | www.dzone.com 5 Source Code Management Hot Tip Configuring SCM Your project’s SCM connection can be quickly configured with just three XML tags, which adds significant capabilities to the scm, release, and reactor plugins. The full Maven Profile reference, including details about when to use each of the profile definition files, can be found at http://maven.apache.org/guides/ introduction/introduction-to-profiles.html Profile Activation The connection tag is your read-only view of your repository and developerConnection is the writable link. URL is your web-based view of the source. Profiles can be activated manually from the command line or through an activation rule (OS, file existence, Maven version, etc.). Profiles are primarily additive, so best practices suggest leaving most off by default, and activating based on specific conditions. <scm> <connection>scm:svn:http://myvendor.com/ourrepo/trunk</ connection> <developerConnection> scm:svn:https://myvendor.com/ourrepo/trunk </developerConnection> <url>http://myvendor.com/viewsouce.pl</url> </scm> Hot Tip Apache Maven 2 Manual Profile Activation mvn <yourgoal> –P YourProfile Automatic Profile Activation Over 12 SCM systems are supported by Maven. The full list can be viewed at http://docs.codehaus.org/display/SCM/SCM+Matrix <project> [...] <profiles> <profile> <id>YourProfile</id> [...settings, build, etc...] <activation> <os> <name>Windows XP</name> <family>Windows</family> <arch>x86</arch> <version>5.1.2600</version> </os> <file> <missing>somefolder/somefile.txt</missing> </file> </activation> </profile> </profiles> [...] </project> Using the SCM Plugin The core SCM plugin offers two highly useful goals. The diff command produces a standard Unix patch file with the extension .diff of the pending (uncommitted) changes on disk that can be emailed or attached to a bug report. mvn scm:diff The update-subprojects goal invokes a recursive scm-provider specific update (svn update, git pull) across all the submodules of a multimodule project. Cutting a Release mvn scm:update-subprojects Maven offers excellent automation for cutting a release of your project. In short, this is a plugin-guided ceremony for verifying that all tests pass, tagging your source code repository, and altering the POMs to reflect a product version increment. Profiles Profiles are a means to conditionally turn on portions of Maven configuration, including plugins, pathing and configuration. The prepare goal runs the unit tests, continuing only if all pass, then increments the value in the pom <version> tag to a release version, tags the source repository accordingly, and increments the pom version tag back to a SNAPSHOT version. The most common uses of profiles are for Windows/Unix platform-specific variations and build-time customization of JAR dependencies based on the use of a specific Weblogic, Websphere or JBoss J2EE vendor. mvn release:perform <project> [...] <profiles> <profile> <id>YourProfile</id> [...settings, build, plugins etc...] <dependencies> <dependency> <groupId>com.yourcompany</groupId> <artifactId>yourlib</artifactId> </dependency> <dependencies> </profile> </profiles> [...] </project> Archetypes An archetype is a powerful template that uses your corporate Java package names and project name in the instantiated project and establishes a baseline of dependencies, with a bonus of basic sample code. You can leverage public archetypes for quickly starting a project that uses a familiar stack, such as Struts+Spring, or Tapestry+Hibernate. You can also create private archetypes within your company to offer new projects a level of consistent dependencies matching your approved corporate technology stack. Profile Definition Locations Profiles can be defined in pom.xml, profiles.xml (parallel to the pom.xml), ~/.m2/settings.xml, or $M2_HOME/conf/settings. xml. DZone, Inc. Using an Archetype The default behavior of the generate goal is to bring up | www.dzone.com 6 a menu of choices. You are then prompted for various replaceables such as package name and artifactId. Type this command, then answer each question at the command line prompt. Apache Maven 2 http://myfaces.apache.org http://tapestry.formos.com/maven-repository http://scala-tools.org http://www.terracotta.org/download/reflector/maven2/ Reports mvn archetype:generate Creating Archetypes Maven has a robust offering of reporting plugins, commonly run with the site generation phase, that evaluate and aggregate information about the project, contributors, it’s source, tests, code coverage, and more. An archetype can be created from an existing project, using it as the pattern by which to build the template. Run the command from the root of your existing project. mvn archetype:create-from-project Adding a Report Plugin Archetype Catalogs <reporting> <plugins> The Maven Archetype plugin comes bundled with a default catalog of applications it can create, but other projects on the Internet also publish catalogs. To use an alternate catalog: <plugin> <artifactId>maven-javadoc-plugin</artifactId> </plugin> </plugins> </reporting> mvn archetype:generate –DarchetypeCatalog=<catalog> A list of the most commonly used catalogs is as follows: local remote http://repo.fusesource.com/maven2 http://cocoon.apache.org http://download.java.net/maven/2 Hot Tip A BOUT t h e A u t h o r RECO M M EN D E D B o o k Matthew McCullough is an Open Source Architect with the Denver, Colorado consulting firm Ambient Ideas, LLC which he co-founded in 1997. He’s spent the last 13 years passionately aiming for ever-greater efficiencies in software development, all while exploring how to share these practices with his clients and their team members. Matthew is a nationally touring speaker on all things open source and has provided long term mentoring and architecture services to over 40 companies ranging from startups to Fortune 500 firms. Feedback and questions are always welcomed at [email protected] you Several sources for Maven have appeared online for some time, but nothing served as an introduction and comprehensive reference guide to this tool -until now. Maven: The Definitive Guide is the ideal book to help you manage development projects for software, webapplications, and enterprise applications. And it comes straight from the source. BUY NOW books.dzone.com/maven-definitive-guide Professional Cheat Sheets You Can Trust by... rns e t t n Pa g i s De “Exactly what busy developers need: simple, short, and to the point.” ld ona McD son a J By m z.co ired Insp e by th GoF ller se Best E: LUD IN C ility TS EN nsib NT spo CO f Re o in d Cha man Com reter rp Inte tor ... ore Itera tor dm dia d an Me rver tho se Me S Ob RN plate TTE Tem Cha Mo ef re R c n Get con tinu ed sn’t r doe ndle e ha d th st an que re le a have James Ward, Adobe Systems to r ndle e ha ith th st w ue req ome. in the e to renc refe listed in ick s A cta qu s, a s NP je rn e b e IG vid s, patt able O pro DES ram . ign us ard UT des diag le f Re refc r oF) ABO mp ts o lass oke erns exa Inv ur (G lemen es c d o Patt d h rl F n f o ig suc s: E inclu go al w n rn Des rn c D a e re e is je ts tt G g AN Th patt , and a t ob mentin l 23 sign Pa M c a h u c M in tr e nd Ea tion ple CO orig ma ons kD re. rma om to c their im boo Softwa nt teC info ed cre Clie the d age : Us d from nd Con () ente on, us ma r ns ct cute Ori Com ) ti uple atte s bje ( +exe low eo lana al P e deco is al p n rg cute ch x o la e . Th s su ati +exe ts. rm an b bject nship c c fo Cre je y an o tio e to ob d as ed rela ms, t th ed eate as rith tha arate : Us be tr ject b ts. m. r ns disp algo c r it to lly ob e te y e e je g s n tt g iv b a sy win ona Pa ana allo traditi s. Rece en o ral en m der uest to m betwe ctu twe nt or req ndled in n. sa sed s varia Stru s be . late catio e ha can s: U or in ilitie psu invo to b llbacks cture that the times Enca quest nsib ca ttern y. stru ips ling re and riant nalit l Pa d respo ing the nsh hand ra pose uing nctio led at va o ct ur cess be fu ue ti io n je P la ob pro av nd ack ,a as q to e the t re e ha eded. b callb nous nality c Beh nships b m ed n ro je ed to fro a ne d y ne ob ynch nctio tio You ne s need at c sts is couple ut an is e as the fu st rela with que s th it itho de e th ar Reque y of re litat pattern ssing w tation articul eals ld be ship or faci p d en ce Use shou tion e: D A hist e. n ed to mman for pro implem ents its ting. ker rela cop runtim co y us m type invo Whe s al pec S e el le e ue s to tu p ex th t id Th ue w ac cla Pro at d im jec ue is are utilizing a job q of the C ueue e que Ob ues with y ged enq dge th que s. B en to han eals me. c roxy Job orithm be giv knowle that is terface D P e : g ct b n ti e in S r le of al ed ca to have d obje of the er mp cop pile rato ut an Exa serv nes ss S at com exec e queue comm Deco Ob confi S Cla e th B d the n . Th for de nge king leto ithin invo hm w Faca cha Sing od tory Refcardz.com n n n .com n z w. d one DZone communities deliver over 6 million pages each month to C Fac ract Abst r pte Ada S C Meth tory Fac t eigh Flyw r rete rp Inte B tor Itera C algo State B rit y od Meth plate Tem Stra teg more than 3.3 million software developers, architects and decision ww S B S e ridg Build C er S B B B B r Visit or makers. DZone offers something for everyone, including news, B f in o ty Cha nsibili o Resp d man m o C B te si po Com Me B B diato Me men to Ob ject Beh ral avio Y tutorials, cheatsheets, blogs, feature articles, source code and more. ILIT NSIB S ES FR PO su ss cce or Upcoming Titles Most Popular JavaFX JSF 2.0 Maven Drupal Java Performance Tuning Eclipse RCP ASP.NET MVC Framework Spring Configuration jQuery Selectors Windows PowerShell Dependency Injection with EJB 3 NetBeans IDE JavaEditor Getting Started with Eclipse Very First Steps in Flex DZone, Inc. 2222 Sedwick Rd Suite 101 Durham, NC 27713 919.678.0300 ISBN-13: 978-1-934238-57-8 ISBN-10: 1-934238-57-0 50795 Refcardz Feedback Welcome [email protected] Sponsorship Opportunities [email protected] 9 781934 238578 O AIN “DZone is a developer’s dream,” says PC Magazine. CH >> ace terf r <<in andle H st ( ) que lere d n +ha s Copyright © 2009 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, r2 nt dle Clie Han ete publisher. photocopying, or otherwise, without prior written permission Cof the Reference: st ( ) oncr que ern a rd it ! V is arz re f c n n ity, Download Now n n ibil nd le a outc ay ha an tial hand sm hen oten ject le to . .W le p le ob tern ethod bject be ab tab pat ultip ecific o should cep n M this if the m up the s sp an ac ents ject ime. see passed d is be a plem ks to de to of ob at runt handle e im t co b Use ec se til ld ch ges t n A n ined being shou peats un paren ime ngua erm Whe not e la the runt or if it det ore s re uest som d tion proces e no m req g in metho cep n A e e ar a ndlin e ex ack th ther n ha rown in ndle th ll st until ptio th e ca Exce ion is sm to ha up th tered or ral pt ni ed un le ce ss avio co ex mp echa n pa Beh . is en am Exa he tion uest to has ack. W ject q cep st Ob e re e ex call le th nd th hand s to ha ct obje n n e of R ns spo $7.95 t to ugh Bro #8 A list of commonly used reporting plugins can be reviewed here http://maven.apache.org/plugins/ Con cre teH 1 ler and () uest +ha ndle re le a hand uest req ki by lin ng | ww z w.d one .c o m Version 1.0
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
advertisement