Maven Quick Guide

download Maven Quick Guide

of 26

Transcript of Maven Quick Guide

  • 7/23/2019 Maven Quick Guide

    1/26

    http://www.tutorialspoint.com/maven/maven_quick_guide.htm Copyright tutorialspoint.com

    MAVEN - QUICK GUIDEMAVEN - QUICK GUIDE

    What is Maven?

    Maven is a project management and comprehension tool. Maven provides developers a completebuild lifecycle framework. Development team can automate the project's build infrastructure in

    almost no time as Maven uses a standard directory layout and a default build lifecycle.

    In case of multiple development teams enviroment, Maven can set-up the way to work as perstandards in a very short time. As most of the project setups are simple and reusable, Mavenmakes life of developer easy while creating reports, checks, build and testing automation setups.

    Maven provides developers ways to manage following:

    Builds

    Documentation

    Reporting

    Dependencies

    SCMs

    Releases

    Distribution

    mailing list

    To summarize, Maven simplifies and standardizes the project build process. It handles compilation,distribution, documentation, team collaboration and other tasks seamlessly. Maven increases

    reusablity and takes care of most of build related tasks.

    Maven History

    Maven was originally designed to simplify building processes in Jakarta Turbine project. Therewere several projects and each project contained slightly different ANT build files. JARs werechecked into CVS.

    Apache group then developed Mavenwhich can build multiple projects together, publish projectsinformation, deploy projects, share JARs across several projects and help in collaboration of teams.

    Maven Objective

    Maven primary goal is to provide developer

    A comprehensive model for projects which is reusable, maintainable, and easier tocomprehend.

    plugins or tools that interact with this declarative model.

    Maven project structure and contents are declared in an xml file, pom.xml referred as ProjectObject Model (POM), which is the fundamental unit of the entire Maven system. Refer to MavenPOMsection for more detail.

    Convention over Configuration

    Maven uses Conventionover Configurationwhich means developers are not required to createbuild process themselves.

    Developers do not have to mention each and every configuration detail. Maven provides sensibledefault behavior for projects. When a Maven project is created, Maven creates default project

    http://localhost/var/www/apps/conversion/tmp/scratch_2/maven/maven_pom.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_2/maven/maven_pom.htmhttp://www.tutorialspoint.com/maven/maven_quick_guide.htm
  • 7/23/2019 Maven Quick Guide

    2/26

    strcture. Developer is only required to place files accordingly and he/she need not to define anyconfiguration in pom.xml.

    As an example, following table shows the default values for project source code files, resource filesand other configurations. Assuming, ${basedir}denotes the project location:

    Item Default

    source code ${basedir}/src/main/java

    resources ${basedir}/src/main/resources

    Tests ${basedir}/src/test

    Complied byte code ${basedir}/target

    distributable JAR ${basedir}/target/classes

    MAVEN ENVIRONMENT SETUPMAVEN ENVIRONMENT SETUP

    Maven is Java based tool, so the very first requirement is to have JDK installed in your machine.

    System Requirement

    JDK 1.5 or above.

    Memory no minimum requirement.

    Disk Space no minimum requirement.

    Operating System no minimum requirement.

    Step 1 - verify Java installation in your machine

    Now open console and execute the followingjavacommand.

    OS Task Command

    Windows Open Command Console c:\> java -version

    Linux Open Command Terminal $ java -version

    Mac Open Terminal machine:~ joseph$ java -version

    Let's verify the output for all the operating systems:

    OS Output

    Windows java version "1.6.0_21"

    Java(TM) SE Runtime Environment (build 1.6.0_21-b07)

    Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)

    Linux java version "1.6.0_21"

    Java(TM) SE Runtime Environment (build 1.6.0_21-b07)

  • 7/23/2019 Maven Quick Guide

    3/26

    Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)

    Mac java version "1.6.0_21"

    Java(TM) SE Runtime Environment (build 1.6.0_21-b07)

    Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing)

    If you do not have Java installed, install the Java Software Development Kit (SDK) fromhttp://www.oracle.com/technetwork/java/javase/downloads/index.html . We are assuming Java1.6.0_21 as installed version for this tutorial.

    Step 2: Set JAVA environment

    Set theJAVA_HOMEenvironment variable to point to the base directory location where Java isinstalled on your machine. For example

    OS Output

    Windows Set the environment variable JAVA_HOME to C:\ProgramFiles\Java\jdk1.6.0_21

    Linux export JAVA_HOME=/usr/local/java-current

    Mac export JAVA_HOME=/Library/Java/Home

    Append Java compiler location to System Path.

    OS Output

    Windows Append the string ;C:\Program Files\Java\jdk1.6.0_21\bin to the end of thesystem variable, Path.

    Linux export PATH=$PATH:$JAVA_HOME/bin/

    Mac not required

    Verify Java Installation usingjava -versioncommand explained above.

    Step 3: Download Maven archiveDownload Maven 2.2.1 from http://maven.apache.org/download.html

    OS Archive name

    Windows apache-maven-2.0.11-bin.zip

    Linux apache-maven-2.0.11-bin.tar.gz

    Mac apache-maven-2.0.11-bin.tar.gz

    Step 4: Extract the Maven archive

    Extract the archive, to the directory you wish to install Maven 2.2.1. The subdirectory apache-maven-2.2.1 will be created from the archive.

    http://maven.apache.org/download.htmlhttp://www.oracle.com/technetwork/java/javase/downloads/index.html
  • 7/23/2019 Maven Quick Guide

    4/26

    OS Location (can be different based on your installation)

    Windows C:\Program Files\Apache Software Foundation\apache-maven-2.2.1

    Linux /usr/local/apache-maven

    Mac /usr/local/apache-maven

    Step 5: Set Maven enviroment variables

    Add M2_HOME, M2, MAVEN_OPTS to environment variables.

    OS Output

    Windows Set the environment variables using system properties.

    M2_HOME=C:\Program Files\Apache Software Foundation\apache-maven-2.2.1

    M2=%M2_HOME%\bin

    MAVEN_OPTS=-Xms256m -Xmx512m

    Linux Open command terminal and set environment variables.

    export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1

    export M2=%M2_HOME%\bin

    export MAVEN_OPTS=-Xms256m -Xmx512m

    Mac Open command terminal and set environment variables.

    export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1

    export M2=%M2_HOME%\bin

    export MAVEN_OPTS=-Xms256m -Xmx512m

    Step 6: Add Maven bin directory location to system path

    Now append M2 variable to System Path

    OS Output

    Windows Append the string ;%M2% to the end of the system variable, Path.

    Linux export PATH=$M2:$PATH

    Mac export PATH=$M2:$PATH

    Step 8: Verify Maven installationNow open console, execute the following mvncommand.

    OS Task Command

  • 7/23/2019 Maven Quick Guide

    5/26

    Windows Open Command Console c:\> mvn --version

    Linux Open Command Terminal $ mvn --version

    Mac Open Terminal machine:~ joseph$ mvn --version

    Finally, verify the output of the above commands, which should be something as follows:

    OS Output

    Windows Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)

    Java version: 1.6.0_21

    Java home: C:\Program Files\Java\jdk1.6.0_21\jre

    Linux Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)

    Java version: 1.6.0_21

    Java home: C:\Program Files\Java\jdk1.6.0_21\jre

    Mac Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)

    Java version: 1.6.0_21

    Java home: C:\Program Files\Java\jdk1.6.0_21\jre

    MAVEN POMMAVEN POM

    POM stands for Project Object Model. It is fundamental Unit of Work in Maven. It is an XML file. Italways resides in the base directory of the project as pom.xml.

    The POM contains information about the project and various configuration detail used by Maven tobuild the project(s).

    POM also contains the goals and plugins. While executing a task or goal, Maven looks for the POMin the current directory. It reads the POM, gets the needed configuration information, thenexecutes the goal. Some of the configuration that can be specified in the POM are following:

    project dependencies

    plugins

    goals

    build profiles

    project version

    developers

    mailing list

    Before creating a POM, we should first decide the project group(groupId), its name(artifactId) andits version as these attributes help in uniquely identifying the project in repository.

    Example POM

  • 7/23/2019 Maven Quick Guide

    6/26

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0

    com.companyname.project-group

  • 7/23/2019 Maven Quick Guide

    7/26

    goals which are registered with each phase. Maven has following three standard lifecycles:

    clean

    default(or build)

    site

    A goalrepresents a specific task which contributes to the building and managing of a project. Itmay be bound to zero or more build phases. A goal not bound to any build phase could be

    executed outside of the build lifecycle by direct invocation.

    The order of execution depends on the order in which the goal(s) and the build phase(s) areinvoked. For example, consider the command below. The clean and package arguments are buildphases while the dependency:copy-dependenciesis a goal.

    mvn clean dependency:copy-dependencies package

    Here the cleanphase will be executed first, and then the dependency:copy-dependencies goalwillbe executed, and finallypackagephase will be executed.

    Clean Lifecycle

    When we execute mvn post-cleancommand, Maven invokes the clean lifecycle consisting of thefollowing phases.

    pre-clean

    clean

    post-clean

    Maven clean goal (clean:clean) is bound to the cleanphase in the clean lifecycle. Its clean:cleangoal deletes the output of a build by deleting the build directory. Thus when mvn cleancommandexecutes, Maven deletes the build directory.

    We can customize this behavior by mentioning goals in any of the above phases of clean life cycle.

    In the following example, We'll attach maven-antrun-plugin:run goal to the pre-clean, clean, andpost-clean phases. This will allow us to echo text messages displaying the phases of the cleanlifecycle.

    We've created a pom.xml in C:\MVN\project folder.

    4.0.0com.companyname.projectgroupproject1.0 org.apache.maven.plugins maven-antrun-plugin 1.1 id.pre-clean

    pre-clean run

  • 7/23/2019 Maven Quick Guide

    8/26

    pre-clean phase id.clean clean run

    clean phase id.post-clean post-clean run

    post-clean phase

    Now open command console, go to the folder containing pom.xml and execute the following mvncommand.

    C:\MVN\project>mvn post-clean

    Maven will start processing and display all the phases of clean life cycle

    [INFO]Scanningforprojects...[INFO]------------------------------------------------------------------[INFO]BuildingUnnamed-com.companyname.projectgroup:project:jar:1.0[INFO] task-segment:[post-clean][INFO]------------------------------------------------------------------[INFO][antrun:run {execution:id.pre-clean}][INFO]Executingtasks

    [echo]pre-clean phase[INFO]Executedtasks[INFO][clean:clean {execution:default-clean}][INFO][antrun:run {execution:id.clean}][INFO]Executingtasks [echo]clean phase[INFO]Executedtasks[INFO][antrun:run {execution:id.post-clean}][INFO]Executingtasks [echo]post-clean phase[INFO]Executedtasks[INFO]------------------------------------------------------------------[INFO]BUILD SUCCESSFUL[INFO]------------------------------------------------------------------[INFO]Totaltime:

  • 7/23/2019 Maven Quick Guide

    9/26

    You can try tuning mvn cleancommand which will displaypre-cleanand clean, nothing will beexecuted forpost-cleanphase.

    Default (or Build) Lifecycle

    This is the primary life cycle of Maven and is used to build the application. It has following 23phases.

    Lifecycle Phase Description

    validate Validates whether project is correct and all necessary informationis available to complete the build process.

    initialize Initializes build state, for example set properties

    generate-sources Generate any source code to be included in compilation phase.

    process-sources Process the source code, for example, filter any value.

    generate-resources Generate resources to be included in the package.

    process-resources Copy and process the resources into the destination directory,ready for packaging phase.

    compile Compile the source code of the project.

    process-classes Post-process the generated files from compilation, for example todo bytecode enhancement/optimization on Java classes.

    generate-test-sources Generate any test source code to be included in compilationphase.

    process-test-sources Process the test source code, for example, filter any values.

    test-compile Compile the test source code into the test destination directory.process-test-classes Process the generated files from test code file compilation.

    test Run tests using a suitable unit testing framework(Junit is one).

    prepare-package Perform any operations necessary to prepare a package beforethe actual packaging.

    package Take the compiled code and package it in its distributable format,such as a JAR, WAR, or EAR file.

    pre-integration-test Perform actions required before integration tests are executed.

    For example, setting up the required environment.integration-test Process and deploy the package if necessary into an environment

    where integration tests can be run.

    post-integration-test Perform actions required after integration tests have beenexecuted. For example, cleaning up the environment.

    verify Run any check-ups to verify the package is valid and meets qualitycriterias.

    install Install the package into the local repository, which can be used asa dependency in other projects locally.

    deploy Copies the final package to the remote repository for sharing withother developers and projects

    There are few important concepts related to Maven Lifecycles which are wroth to mention:

  • 7/23/2019 Maven Quick Guide

    10/26

    When a phase is called via Maven command, for example mvn compile, only phases uptoand including that phase will execute.

    Different maven goals will be bound to different phases of Maven lifecycle depending uponthe type of packaging (JAR / WAR / EAR).

    In the following example, We'll attach maven-antrun-plugin:run goal to few of the phases of Buildlifecycle. This will allow us to echo text messages displaying the phases of the lifecycle.

    We've updated pom.xml in C:\MVN\project folder.

    4.0.0com.companyname.projectgroupproject1.0org.apache.maven.pluginsmaven-antrun-plugin1.1 id.validate validate run validate phase

    id.compile compile run compile phase

    id.test test run test phase

    id.package package run

  • 7/23/2019 Maven Quick Guide

    11/26

    package phase id.deploy deploy

    run deploy phase

    Now open command console, go the folder containing pom.xml and execute the following mvncommand.

    C:\MVN\project>mvn compile

    Maven will start processing and display phases of build life cycle upto compile phase.

    [INFO]Scanningforprojects...[INFO]------------------------------------------------------------------[INFO]BuildingUnnamed-com.companyname.projectgroup:project:jar:1.0[INFO] task-segment:[compile]

    [INFO]------------------------------------------------------------------[INFO][antrun:run {execution:id.validate}][INFO]Executingtasks [echo]validate phase[INFO]Executedtasks[INFO][resources:resources {execution:default-resources}][WARNING]Usingplatform encoding (Cp1252actually)to copy filtered resources,i.e.build isplatform dependent![INFO]skip non existing resourceDirectory C:\MVN\project\src\main\resources[INFO][compiler:compile {execution:default-compile}][INFO]Nothingto compile -all classes are up to date[INFO][antrun:run {execution:id.compile}][INFO]Executingtasks

    [echo]compile phase[INFO]Executedtasks[INFO]------------------------------------------------------------------[INFO]BUILD SUCCESSFUL[INFO]------------------------------------------------------------------[INFO]Totaltime:2seconds[INFO]Finishedat:SatJul0720:18:25IST 2012[INFO]FinalMemory:7M/64M[INFO]------------------------------------------------------------------

    Site Lifecycle

    Maven Site plugin is generally used to create fresh documentation to create reports, deploy site

    etc.

    Phases

    pre-site

  • 7/23/2019 Maven Quick Guide

    12/26

    site

    post-site

    site-deploy

    In the following example, We'll attach maven-antrun-plugin:run goal to all the phases of Sitelifecycle. This will allow us to echo text messages displaying the phases of the lifecycle.

    We've updated pom.xml in C:\MVN\project folder.

    4.0.0com.companyname.projectgroupproject1.0org.apache.maven.plugins

    maven-antrun-plugin1.1 id.pre-site pre-site run pre-site phase

    id.site site run site phase

    id.post-site post-site run post-site phase id.site-deploy site-deploy run

  • 7/23/2019 Maven Quick Guide

    13/26

    site-deploy phase

    Now open command console, go the folder containing pom.xml and execute the following mvncommand.

    C:\MVN\project>mvn site

    Maven will start processing and display phases of site life cycle upto site phase.

    [INFO]Scanningforprojects...[INFO]------------------------------------------------------------------[INFO]BuildingUnnamed-com.companyname.projectgroup:project:jar:1.0[INFO] task-segment:[site]

    [INFO]------------------------------------------------------------------[INFO][antrun:run {execution:id.pre-site}][INFO]Executingtasks [echo]pre-site phase[INFO]Executedtasks[INFO][site:site {execution:default-site}][INFO]Generating"About"report.[INFO]Generating"Issue Tracking"report.[INFO]Generating"Project Team"report.[INFO]Generating"Dependencies"report.[INFO]Generating"Project Plugins"report.[INFO]Generating"Continuous Integration"report.[INFO]Generating"Source Repository"report.

    [INFO]Generating"Project License"report.[INFO]Generating"Mailing Lists"report.[INFO]Generating"Plugin Management"report.[INFO]Generating"Project Summary"report.[INFO][antrun:run {execution:id.site}][INFO]Executingtasks [echo]site phase[INFO]Executedtasks[INFO]------------------------------------------------------------------[INFO]BUILD SUCCESSFUL[INFO]------------------------------------------------------------------[INFO]Totaltime:3seconds[INFO]Finishedat:SatJul0715:25:10IST 2012

    [INFO]FinalMemory:24M/149M[INFO]------------------------------------------------------------------

    MAVEN BUILD PROFILESMAVEN BUILD PROFILES

    A Build profileis a set of configuration values which can be used to set or override default valuesof Maven build. Using a build profile, you can customize build for different environments such asProductionv/s Developementenvironments.

    Profiles are specified in pom.xml file using its activeProfiles / profiles elements and are triggered invariety of ways. Profiles modify the POM at build time, and are used to give parameters differenttarget environments (for example, the path of the database server in the development, testing,

    and production environments).

    Types of Build Profile

    Build profiles are majorly of three types

  • 7/23/2019 Maven Quick Guide

    14/26

    Type Where it is defined

    Per Project Defined in the project POM file, pom.xml

    Per User Defined in Maven settings xml file (%USER_HOME%/.m2/settings.xml)

    Global Defined in Maven global settings xml file (%M2_HOME%/conf/settings.xml)

    Profile Activation

    A Maven Build Profile can be activated in various ways.

    Explicitly using command console input.

    Through maven settings.

    Based on environment variables (User/System variables).

    OS Settings (for example, Windows family).

    Present/missing files.

    Profile Activation Examples

    Let us assume following directory structure of your project:

    Now, under src/main/resourcesthere are three environment specific files:

    File Name Description

    env.properties default configuration used if no profile is mentioned.

    env.test.properties test configuration when test profile is used.

    env.prod.properties production configuration when prod profile is used.

    Explicit Profile Activation

    In the following example, We'll attach maven-antrun-plugin:run goal to test phase. This will allow

  • 7/23/2019 Maven Quick Guide

    15/26

    us to echo text messages for different profiles. We will be using pom.xml to define differentprofiles and will activate profile at command console using maven command.

    Assume, we've created following pom.xml in C:\MVN\project folder.

    4.0.0

    com.companyname.projectgroup project 1.0 test org.apache.maven.plugins maven-antrun-plugin 1.1

    test run Using env.test.properties

    Now open command console, go to the folder containing pom.xml and execute the following mvncommand. Pass the profile name as argument using -P option.

    C:\MVN\project>mvn test -Ptest

    Maven will start processing and display the result of test build profile.

    [INFO]Scanningforprojects...[INFO]------------------------------------------------------------------[INFO]BuildingUnnamed-com.companyname.projectgroup:project:jar:1.0[INFO] task-segment:[test][INFO]------------------------------------------------------------------[INFO][resources:resources {execution:default-resources}][WARNING]Usingplatform encoding (Cp1252actually)to copy filtered resources,i.e.build isplatform dependent![INFO]Copying3resources

    [INFO][compiler:compile {execution:default-compile}][INFO]Nothingto compile -all classes are up to date[INFO][resources:testResources {execution:default-testResources}][WARNING]Usingplatform encoding (Cp1252actually)to copy filtered resources,i.e.build isplatform dependent![INFO]skip non existing resourceDirectory C:\MVN\project\src\test\resources

  • 7/23/2019 Maven Quick Guide

    16/26

    [INFO][compiler:testCompile {execution:default-testCompile}][INFO]Nothingto compile -all classes are up to date[INFO][surefire:test {execution:default-test}][INFO]Surefirereport directory:C:\MVN\project\target\surefire-reports

    -------------------------------------------------------T E S T S-------------------------------------------------------Thereare notests to run.

    Results:

    Testsrun:0,Failures:0,Errors:0,Skipped:0

    [INFO][antrun:run {execution:default}][INFO]Executingtasks [echo]Usingenv.test.properties[INFO]Executedtasks[INFO]------------------------------------------------------------------[INFO]BUILD SUCCESSFUL[INFO]------------------------------------------------------------------[INFO]Totaltime:1second[INFO]Finishedat:SunJul0814:55:41IST 2012

    [INFO]FinalMemory:8M/64M[INFO]------------------------------------------------------------------

    Now as an exercise, you can do the following steps

    Add another profile element to profiles element of pom.xml (copy existing profile elementand paste it where profile elements ends).

    Update id of this profile element from test to normal.

    Update task section to echo env.properties and copy env.properties to target directory

    Again repeat above three steps, update id to prod and task section for env.prod.properties

    That's all. Now you've three build profiles ready (normal / test / prod).

    Now open command console, go to the folder containing pom.xml and execute the following mvncommands. Pass the profile names as argument using -P option.

    C:\MVN\project>mvn test -Pnormal

    C:\MVN\project>mvn test -Pprod

    Check the output of build to see the difference.

    Profile Activation via Maven Settings

    Open Maven settings.xmlfile available in %USER_HOME%/.m2 directory where %USER_HOME%represents user home directory. If settings.xml file is not there then create a new one.

    Add test profile as an active profile using activeProfiles node as shown below in example

    maven.dev.snaponglobal.com Internal Artifactory Maven repository http://repo1.maven.org/maven2/ *

  • 7/23/2019 Maven Quick Guide

    17/26

    test

    Now open command console, go to the folder containing pom.xml and execute the following mvncommand. Do not pass the profile name using -P option.Maven will display result of test profilebeing an active profile.

    C:\MVN\project>mvn test

    Profile Activation via Environment Variables

    Now remove active profile from maven settings.xml and update the test profile mentioned inpom.xml. Add activation element to profile element as shown below.

    The test profile will trigger when the system property "env" is specified with the value "test". Createa environment variable "env" and set its value as "test".

    test env test

    Let's open command console, go to the folder containing pom.xml and execute the following mvncommand.

    C:\MVN\project>mvn test

    Profile Activation via Operating System

    Activation element to include os detail as shown below. This test profile will trigger when thesystem is windows XP.

    test Windows XP Windows x86

    5.1.2600

    Now open command console, go to the folder containing pom.xml and execute the following mvncommands. Do not pass the profile name using -P option.Maven will display result of test profilebeing an active profile.

    C:\MVN\project>mvn test

    Profile Activation via Present/Missing File

    Now activation element to include os detail as shown below.

    Now test profile will trigger when target/generated-sources/axistools/wsdl2java/com/companyname/groupis missing.

  • 7/23/2019 Maven Quick Guide

    18/26

    test target/generated-sources/axistools/wsdl2java/com/ companyname/group

    Now open command console, go to the folder containing pom.xml and execute the following mvncommands. Do not pass the profile name using -P option.Maven will display result of test profilebeing an active profile.

    C:\MVN\project>mvn test

    MAVEN REPOSITORIESMAVEN REPOSITORIES

    In Maven terminology, a repository is a place i.e. directory where all the project jars, library jar,plugins or any other project specific artifacts are stored and can be used by Maven easily.

    Maven repository are of three types

    local

    central

    remote

    Local Repository

    Maven local repository is a folder location on your machine. It gets created when you run anymaven command for the first time.

    Maven local repository keeps your project's all dependencies (library jars, plugin jars etc). Whenyou run a Maven build, then Maven automatically downloads all the dependency jars into the localrepository.It helps to avoid references to dependencies stored on remote machine every time aproject is build.

    Maven local repository by default get created by Maven in %USER_HOME% directory. To overridethe default location, mention another path in Maven settings.xml file available at%M2_HOME%\conf directory.

    C:/MyLocalRepository

    When you run Maven command, Maven will download dependencies to your custom path.

    Central Repository

    Maven central repository is repository provided by Maven community. It contains a large numberof commonly used libraries.

    When Maven does not find any dependency in local repository, it starts searching in centralrepository using following URL: http://repo1.maven.org/maven2/

    Key concepts of Central repository

    This repository is managed by Maven community.

    It is not required to be configured.

    http://repo1.maven.org/maven2/
  • 7/23/2019 Maven Quick Guide

    19/26

    It requires internet access to be searched.

    To browse the content of central maven repository, maven community has provided a URL:http://search.maven.org/#browse. Using this library, a developer can search all the availablelibraries in central repository.

    Remote Repository

    Sometime, Maven does not find a mentioned dependency in central repository as well then itstopped build process and output error message to console. To prevent such situation, Mavenprovides concept of Remote Repositorywhich is developer's own custom repository containingrequired libraries or other project jars.

    For example, using below mentioned POM.xml,Maven will download dependency (not available incentral repository) from Remote Repositories mentioned in the same pom.xml.

    4.0.0 com.companyname.projectgroup

    project 1.0 com.companyname.common-lib common-lib 1.0.0 companyname.lib1 http://download.companyname.org/maven2/lib1 companyname.lib2 http://download.companyname.org/maven2/lib2

    Maven Dependency Search Sequence

    When we execute Maven build commands, Maven starts looking for dependency libraries in thefollowing sequence:

    Step 1 - Search dependency in local repository, if not found, move to step 2 else if foundthen do the further processing.

    Step 2 - Search dependency in central repository, if not found and remoterepository/repositories is/are mentioned then move to step 4 else if found, then it isdownloaded to local repository for future reference.

    Step 3 - If a remote repository has not been mentioned, Maven simply stops the processingand throws error (Unable to find dependency).

    Step 4 - Search dependency in remote repository or repositories, if found then it isdownloaded to local repository for future reference otherwise Maven as expected stopprocessing and throws error (Unable to find dependency).

    MAVEN PLUGINSMAVEN PLUGINS

    Maven is actually a plugin execution framework where every task is actually done by plugins.Maven Plugins are generally used to :

    http://search.maven.org/#browse
  • 7/23/2019 Maven Quick Guide

    20/26

    create jar file

    create war file

    compile code files

    unit testing of code

    create project documentation

    create project reports

    A plugin generally provides a set of goals and which can be executed using following syntax:

    mvn [plugin-name]:[goal-name]

    For example, a Java project can be compiled with the maven-compiler-plugin's compile-goal byrunning following command

    mvn compiler:compile

    Plugin TypesMaven provided following two types of Plugins:

    Type Description

    Build plugins They execute during the build and should be configured in the element of pom.xml

    Reportingplugins

    They execute during the site generation and they should be configured inthe element of the pom.xml

    Following is the list of few common plugins:

    Plugin Description

    clean Clean up target after the build. Deletes the target directory.

    compiler Compiles Java source files.

    surefile Run the JUnit unit tests. Creates test reports.

    jar Builds a JAR file from the current project.

    war Builds a WAR file from the current project.

    javadoc Generates Javadoc for the project.

    antrun Runs a set of ant tasks from any phase mentioned of the build.

    Example

    We've used maven-antrun-pluginextensively in our examples to print data on console. SeeMaven Build Profileschapter. Let to understand it in a better way let's create a pom.xml in

    C:\MVN\project folder.

    http://localhost/var/www/apps/conversion/tmp/scratch_2/maven/maven_build_profiles.htm
  • 7/23/2019 Maven Quick Guide

    21/26

    4.0.0com.companyname.projectgroupproject1.0 org.apache.maven.plugins maven-antrun-plugin 1.1

    id.clean clean run clean phase

    Next, open command console and go to the folder containing pom.xml and execute the followingmvncommand.

    C:\MVN\project>mvn clean

    Maven will start processing and display clean phase of clean life cycle

    [INFO]Scanningforprojects...[INFO]------------------------------------------------------------------[INFO]BuildingUnnamed-com.companyname.projectgroup:project:jar:1.0[INFO] task-segment:[post-clean][INFO]------------------------------------------------------------------[INFO][clean:clean {execution:default-clean}][INFO][antrun:run {execution:id.clean}][INFO]Executingtasks [echo]clean phase[INFO]Executedtasks[INFO]------------------------------------------------------------------[INFO]BUILD SUCCESSFUL

    [INFO]------------------------------------------------------------------[INFO]Totaltime:

  • 7/23/2019 Maven Quick Guide

    22/26

    repository and starts its processing.

    CREATING JAVA PROJECT USING MAVENCREATING JAVA PROJECT USING MAVEN

    Maven uses archetypeplugins to create projects. To create a simple java application, we'll usemaven-archetype-quickstart plugin. In example below, We'll create a maven based javaapplication project in C:\MVN folder.

    Let's open command console, go the C:\MVN directory and execute the following mvncommand.

    C:\MVN>mvn archetype:generate-DgroupId=com.companyname.bank-DartifactId=consumerBanking-DarchetypeArtifactId=maven-archetype-quickstart-DinteractiveMode=false

    Maven will start processing and will create the complete java application project structure.

    INFO]Scanningforprojects...[INFO]Searchingrepository forplugin withprefix:'archetype'.[INFO]-------------------------------------------------------------------

    [INFO]BuildingMavenDefaultProject[INFO] task-segment:[archetype:generate](aggregator-style)[INFO]-------------------------------------------------------------------[INFO]Preparingarchetype:generate[INFO]Nogoals needed forproject -skipping[INFO][archetype:generate {execution:default-cli}][INFO]Generatingproject inBatchmode[INFO]-------------------------------------------------------------------[INFO]Usingfollowing parameters forcreating projectfromOld(1.x)Archetype:maven-archetype-quickstart:1.0

    [INFO]-------------------------------------------------------------------[INFO]Parameter:groupId,Value:com.companyname.bank[INFO]Parameter:packageName,Value:com.companyname.bank

    [INFO]Parameter:package,Value:com.companyname.bank[INFO]Parameter:artifactId,Value:consumerBanking[INFO]Parameter:basedir,Value:C:\MVN[INFO]Parameter:version,Value:1.0-SNAPSHOT[INFO]project created fromOld(1.x)Archetypeindir:C:\MVN\consumerBanking[INFO]------------------------------------------------------------------[INFO]BUILD SUCCESSFUL[INFO]------------------------------------------------------------------[INFO]Totaltime:14seconds[INFO]Finishedat:TueJul1015:38:58IST 2012[INFO]FinalMemory:21M/124M[INFO]------------------------------------------------------------------

    Now go to C:/MVN directory. You'll see a java application project created named consumerBanking(as specified in artifactId). Maven uses a standard directory layout as shown below:

  • 7/23/2019 Maven Quick Guide

    23/26

    Using above example, we can understand following key concepts

    Folder Structure Description

    consumerBanking contains src folder and pom.xml

    src/main/java contains java code files under the package structure(com/companyName/bank).

    src/main/test contains test java code files under the package structure(com/companyName/bank).

    src/main/resources it contains images/properties files (In above example, we need to createthis structure manually).

    If you see, Maven also created a sample Java Source file and Java Test file. OpenC:\MVN\consumerBanking\src\main\java\com\companyname\bank folder, you will see App.java.

    packagecom.companyname.bank;

    /*** Hello world!**/publicclassApp{

    publicstaticvoidmain(String[]args ) { System.out.println("Hello World!"); }}

    Open C:\MVN\consumerBanking\src\test\java\com\companyname\bank folder, you will seeAppTest.java.

    packagecom.companyname.bank;

    importjunit.framework.Test;

    importjunit.framework.TestCase;importjunit.framework.TestSuite;

    /*** Unit test for simple App.*/publicclassAppTestextendsTestCase{ /** * Create the test case * * @param testName name of the test case */ publicAppTest(StringtestName ) { super(testName ); }

    /** * @return the suite of tests being tested

  • 7/23/2019 Maven Quick Guide

    24/26

    */ publicstaticTestsuite() { returnnewTestSuite(AppTest.class); }

    /** * Rigourous Test :-) */ publicvoidtestApp()

    { assertTrue(true); }}

    Developers are required to place their files as mentioned in table above and Maven handles the allthe build related complexities.

    BUILD & TEST JAVA PROJECT USING MAVENBUILD & TEST JAVA PROJECT USING MAVEN

    What we learnt in Project Creation chapter is how to create a Java application using Maven. Nowwe'll see how to build and test the application.

    Go to C:/MVN directory where you've created your java application. Open consumerBankingfolder.You will see the POM.xmlfile with following contents.

    4.0.0 com.companyname.projectgroup project 1.0

    junit junit 3.8.1

    Here you can see, Maven already added Junit as test framework. By default Maven adds a sourcefile App.javaand a test file AppTest.javain its default directory structure discussed in previouschapter.

    Let's open command console, go the C:\MVN\consumerBanking directory and execute thefollowing mvncommand.

    C:\MVN\consumerBanking>mvn clean package

    Maven will start building the project.

    [INFO]Scanningforprojects...[INFO]-------------------------------------------------------------------[INFO]BuildingconsumerBanking[INFO] task-segment:[clean,package][INFO]-------------------------------------------------------------------

    [INFO][clean:clean {execution:default-clean}][INFO]Deletingdirectory C:\MVN\consumerBanking\target[INFO][resources:resources {execution:default-resources}][WARNING]Usingplatform encoding (Cp1252actually)to copy filtered resources,i.e.build isplatform dependent![INFO]skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\resources

  • 7/23/2019 Maven Quick Guide

    25/26

    [INFO][compiler:compile {execution:default-compile}][INFO]Compiling1source file to C:\MVN\consumerBanking\target\classes[INFO][resources:testResources {execution:default-testResources}][WARNING]Usingplatform encoding (Cp1252actually)to copy filtered resources,i.e.build isplatform dependent![INFO]skip non existing resourceDirectory C:\MVN\consumerBanking\src\test\resources[INFO][compiler:testCompile {execution:default-testCompile}][INFO]Compiling1source file to C:\MVN\consumerBanking\target\test-classes[INFO][surefire:test {execution:default-test}]

    [INFO]Surefirereport directory:C:\MVN\consumerBanking\target\surefire-reports-------------------------------------------------------T E S T S-------------------------------------------------------Runningcom.companyname.bank.AppTestTestsrun:1,Failures:0,Errors:0,Skipped:0,Timeelapsed:0.027sec

    Results:

    Testsrun:1,Failures:0,Errors:0,Skipped:0

    [INFO][jar:jar {execution:default-jar}]

    [INFO]Buildingjar:C:\MVN\consumerBanking\target\consumerBanking-1.0-SNAPSHOT.jar[INFO]------------------------------------------------------------------------[INFO]BUILD SUCCESSFUL[INFO]------------------------------------------------------------------------[INFO]Totaltime:2seconds[INFO]Finishedat:TueJul1016:52:18IST 2012[INFO]FinalMemory:16M/89M[INFO]------------------------------------------------------------------------

    You've built your project and created final jar file, following are the key learning concepts

    We give maven two goals, first to clean the target directory (clean) and then package the

    project build output as jar(package).

    Packaged jar is available in consumerBanking\target folder as consumerBanking-1.0-SNAPSHOT.jar.

    Test reports are available in consumerBanking\target\surefire-reports folder.

    Maven compiled source code file(s) and then test source code file(s).

    Then Maven run the test cases.

    Finally Maven created the package.

    Now open command console, go the C:\MVN\consumerBanking\target\classes directory andexecute the following java command.

    C:\MVN\consumerBanking\target\classes>java com.companyname.bank.App

    You will see the result

    HelloWorld!

    Adding Java Source Files

    Let's see how we can add additional Java files in our project. OpenC:\MVN\consumerBanking\src\main\java\com\companyname\bank folder, create Util class in it asUtil.java.

    packagecom.companyname.bank;

    publicclassUtil

  • 7/23/2019 Maven Quick Guide

    26/26

    { publicstaticvoidprintMessage(Stringmessage){ System.out.println(message); }}

    Update App class to use Util class.

    packagecom.companyname.bank;

    /*** Hello world!**/publicclassApp{ publicstaticvoidmain(String[]args ) { Util.printMessage("Hello World!"); }}

    Now open command console, go the C:\MVN\consumerBanking directory and execute thefollowing mvncommand.

    C:\MVN\consumerBanking>mvn clean compile

    After Maven build is successful, go the C:\MVN\consumerBanking\target\classes directory andexecute the following java command.

    C:\MVN\consumerBanking\target\classes>java com.companyname.bank.App

    You will see the result

    HelloWorld!