maven introduction

34
MAVEN INTRODUCTION

Upload: ozgen-gunay

Post on 14-Aug-2015

105 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: MAVEN INTRODUCTION

MAVEN INTRODUCTION

Page 2: MAVEN INTRODUCTION

A Sample Ant Build File To Compile and Generate Jar<project name="my-project" default="dist" basedir=".">

<description>simple example build file</description><!-- set global properties for this build --><property name="src" location="src/main/java"/><property name="build" location="target/classes"/><property name="dist" location="target"/> <target name="init"><!-- Create the time stamp --><tstamp/><!-- Create the build directory structure used by compile --><mkdir dir="${build}"/></target> <target name="compile" depends="init"description="compile the source " ><!-- Compile the java code from ${src} into ${build} --><javac srcdir="${src}" destdir="${build}"/></target> <target name="dist" depends="compile"description="generate the distribution" ><!-- Create the distribution directory --><mkdir dir="${dist}/lib"/><!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar -file --><jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${ -build}"/></target> <target name="clean"description="clean up" ><!-- Delete the ${build} and ${dist} directory trees --><delete dir="${build}"/><delete dir="${dist}"/></target></project>

Page 3: MAVEN INTRODUCTION

Maven Equivalent<project><modelVersion>4.0.0</modelVersion><groupId>org.sonatype.mavenbook</groupId><artifactId>my-project</artifactId><version>1.0-SNAPSHOT</version></project>

Page 4: MAVEN INTRODUCTION

What is MavenMaven, a Yiddish word meaning accumulator of knowledge, was originally started as an attempt to simplify the build processes in the Jakarta Turbine project. There were several projects each with their own Ant build files that were all slightly different and JARs were checked into CVS. We wanted a standard way to build the projects, a clear definition of what the project consisted of, an easy way to publish project information and a way to share JARs across several projects.

Page 5: MAVEN INTRODUCTION

Maven’s ObjectivesMaven's primary goal is to allow a developer to comprehend the complete state of a development effort in the shortest period of time. In order to attain this goal there are several areas of concern that Maven attempts to deal with:

• Making the build process easy• Providing a uniform build system• Providing quality project information• Providing guidelines for best practices development• Allowing transparent migration to new features

Page 6: MAVEN INTRODUCTION

Ant vs MavenApache Ant • Ant doesn’t have formal conventions like a common project directory structure or default behavior. You have

to tell Ant exactly where to find the source and where to put the output. Informal conventions have emerged over time, but they haven’t been codified into the product.

• Ant is procedural. You have to tell Ant exactly what to do and when to do it. You have to tell it to compile, then copy, then compress.

• Ant doesn’t have a lifecycle. You have to define goals and goal dependencies. You have to attach a sequence of tasks to each goal manually.

Apache Maven • Maven has conventions. It knows where your source code is because you followed the convention. Maven’s

Compiler plugin put the bytecode in target/classes, and it produces a JAR file in target.• Maven is declarative. All you had to do was create a pom.xml file and put your source in the default

directory. Maven took care of the rest.• Maven has a lifecycle which was invoked when you executed mvn install. This command told Maven to

execute a series of sequential lifecycle phases until it reached the install lifecycle phase. As a side-effect of this journey through the lifecycle, Maven executed a number of default plugin goals which did things like compile and create a JAR.

Page 7: MAVEN INTRODUCTION

Installing Maven1. Download maven2. Extract maven to /usr/local/apache-maven-3.2.13. $ cd /usr/local4. /usr/local $ ln -s apache-maven-3.2.1 maven5. /usr/local $ export M2_HOME=/usr/local/maven6. /usr/local $ export PATH=${M2_HOME}/bin:${PATH}

Page 8: MAVEN INTRODUCTION

Installation Details/usr/local/maven $ ls

LICENSE.txtNOTICE.txtREADME.txtbin/boot/conf/lib/

/usr/local/maven $ mvn –version

Apache Maven 3.0.2 Java version: 1.6.0_18 Java home: /usr/lib/jvm/java-6-openjdk/jre Default locale: en_IN, platform encoding: UTF-8 OS name: "linux" version: "2.6.32-24-generic" arch: "i386" Family: "unix"

Page 9: MAVEN INTRODUCTION

settings.xmlUnless you are working in a shared Unix environment, you should avoid customizing the settings.xml inM2_HOME/conf. Altering the global settings.xml file in the Maven installation itself is usually unnecessaryand it tends to complicate the upgrade procedure for Maven as you’ll have to remember to copy thecustomized settings.xml from the old Maven installation to the new installation. If you need to customizesettings.xml, you should be editing your own settings.xml in ~/.m2/settings.xml.

~/.m2/settings.xmlA file containing user-specific configuration for authentication, repositories, and other informationto customize the behavior of Maven. ~/.m2/repository/This directory contains your local Maven repository. When you download a dependency from aremote Maven repository, Maven stores a copy of the dependency in your local repository

Page 10: MAVEN INTRODUCTION

Creating a Maven ProjectTo start a new Maven project, use the Maven Archetype plugin from the command line. Run the archetype:generate goal, select default archetype suggested by pressing "Enter". This will use the archetype org.apache.maven.archetypes:Press "Enter" again to confirm the latest version of the archetype and then "Enter" to confirm the supplied parameters. $ mvn archetype:generate -DgroupId=org.sonatype.mavenbook -DartifactId=simple -Dpackage=org.sonatype.mavenbook -Dversion=1.0-SNAPSHOT

src/main/java Application/Library sources

src/main/resources Application/Library resources

src/main/filters Resource filter files

src/main/config Configuration files

src/main/scripts Application/Library scripts

src/main/webapp Web application sources

src/test/java Test sources

src/test/resources Test resources

src/test/filters Test resource filter files

src/it Integration Tests (primarily for plugins)

src/assembly Assembly descriptors

src/site Site

LICENSE.txt Project's license

NOTICE.txt Notices and attributions required by libraries that the project depends on

README.txt Project's readme

Page 11: MAVEN INTRODUCTION

LIFECYCLES

Clean Lifecycle

pre-clean executes processes needed prior to the actual project cleaning

clean remove all files generated by the previous build

post-clean executes processes needed to finalize the project cleaning

Page 12: MAVEN INTRODUCTION

LIFECYCLESDefault Lifecycle

validate validate the project is correct and all necessary information is available.

initialize initialize build state, e.g. set properties or create directories.

generate-sources generate any source code for inclusion in compilation.

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

generate-resources generate resources for inclusion in the package.

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

compile compile the source code of the project.

process-classes post-process the generated files from compilation, for example to do bytecode enhancement on Java classes.

generate-test-sources generate any test source code for inclusion in compilation.

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

generate-test-resources create resources for testing.

process-test-resources copy and process the resources into the test destination directory.

test-compile compile the test source code into the test destination directory

process-test-classes post-process the generated files from test compilation, for example to do bytecode enhancement on Java classes. For Maven 2.0.5 and above.

test run tests using a suitable unit testing framework. These tests should not require the code be packaged or deployed.

prepare-package perform any operations necessary to prepare a package before the actual packaging. This often results in an unpacked, processed version of the package. (Maven 2.1 and above)

package take the compiled code and package it in its distributable format, such as a JAR.

pre-integration-test perform actions required before integration tests are executed. This may involve things such as 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 been executed. This may including cleaning up the environment.

verify run any checks to verify the package is valid and meets quality criteria.

install install the package into the local repository, for use as a dependency in other projects locally.

deploy done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

Page 13: MAVEN INTRODUCTION

LIFECYCLES

Site Lifecycle

pre-site executes processes needed prior to the actual project site generation

site generates the project's site documentation

post-site executes processes needed to finalize the site generation, and to prepare for site deployment

site-deploy deploys the generated site documentation to the specified web server

Page 14: MAVEN INTRODUCTION

LIFECYCLE BINDINGS

Clean Lifecycle Bindings

clean clean:clean

Page 15: MAVEN INTRODUCTION

LIFECYCLE BINDINGS

Default Lifecycle Bindings - Packaging ejb / ejb3 / jar / par / rar / war

process-resources resources:resources

compile compiler:compile

process-test-resources resources:testResources

test-compile compiler:testCompile

test surefire:test

package ejb:ejb or ejb3:ejb3 or jar:jar or par:par or rar:rar or war:war

install install:install

deploy deploy:deploy

Page 16: MAVEN INTRODUCTION

LIFECYCLE BINDINGS

Default Lifecycle Bindings - Packaging ear

generate-resources ear:generate-application-xml

process-resources resources:resources

package ear:ear

install install:install

deploy deploy:deploy

Page 17: MAVEN INTRODUCTION

LIFECYCLE BINDINGS

Default Lifecycle Bindings - Packaging maven-plugin

generate-resources plugin:descriptor

process-resources resources:resources

compile compiler:compile

process-test-resources resources:testResources

test-compile compiler:testCompile

test surefire:test

package jar:jar and plugin:addPluginArtifactMetadata

install install:install

deploy deploy:deploy

Page 18: MAVEN INTRODUCTION

LIFECYCLE BINDINGS

Default Lifecycle Bindings - Packaging pom

package

install

deploy

Page 19: MAVEN INTRODUCTION

LIFECYCLE BINDINGS

Site Lifecycle Bindings

site site:site

site-deploy site:deploy

Page 20: MAVEN INTRODUCTION

Can you translate this?

$mvn clean eclipse:eclipse install

Page 21: MAVEN INTRODUCTION

Dependency MechanismTransitive Dependencies

Transitive dependencies are a new feature in Maven 2.0. This allows you to avoid needing to discover and specify the libraries that your own dependencies require, and including them automatically.

This feature is facilitated by reading the project files of your dependencies from the remote repositories specified. In general, all dependencies of those projects are used in your project, as are any that the project inherits from its parents, or from its dependencies, and so on.

Page 22: MAVEN INTRODUCTION

Dependency MechanismTransitive Dependencies

• Dependency mediation - this determines what version of a dependency will be used when multiple versions of an artifact are encountered. Currently, Maven 2.0 only supports using the "nearest definition" which means that it will use the version of the closest dependency to your project in the tree of dependencies. You can always guarantee a version by declaring it explicitly in your project's POM. Note that if two dependency versions are at the same depth in the dependency tree, until Maven 2.0.8 it was not defined which one would win, but since Maven 2.0.9 it's the order in the declaration that counts: the first declaration wins.– "nearest definition" means that the version used will be the closest one to your project in the tree of dependencies, eg. if

dependencies for A, B, and C are defined as A -> B -> C -> D 2.0 and A -> E -> D 1.0, then D 1.0 will be used when building A because the path from A to D through E is shorter. You could explicitly add a dependency to D 2.0 in A to force the use of D 2.0

• Dependency management - this allows project authors to directly specify the versions of artifacts to be used when they are encountered in transitive dependencies or in dependencies where no version has been specified. In the example in the preceding section a dependency was directly added to A even though it is not directly used by A. Instead, A can include D as a dependency in its dependencyManagement section and directly control which version of D is used when, or if, it is ever referenced.

• Dependency scope - this allows you to only include dependencies appropriate for the current stage of the build. This is described in more detail below.

• Excluded dependencies - If project X depends on project Y, and project Y depends on project Z, the owner of project X can explicitly exclude project Z as a dependency, using the "exclusion" element.

• Optional dependencies - If project Y depends on project Z, the owner of project Y can mark project Z as an optional dependency, using the "optional" element. When project X depends on project Y, X will depend only on Y and not on Y's optional dependency Z. The owner of project X may then explicitly add a dependency on Z, at her option. (It may be helpful to think of optional dependencies as "excluded by default.")

Page 23: MAVEN INTRODUCTION

Dependency MechanismDependency Scope

• compileThis is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.

• providedThis is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

• runtimeThis scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.

• testThis scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

• systemThis scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.

• import (only available in Maven 2.0.9 or later)This scope is only used on a dependency of type pom in the <dependencyManagement> section. It indicates that the specified POM should be replaced with the dependencies in that POM's <dependencyManagement> section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

Page 24: MAVEN INTRODUCTION

Dependency MechanismExample :

Project A:

<project> ... <dependencies> <dependency> <groupId>group-a</groupId> <artifactId>artifact-a</artifactId> <version>1.0</version> <exclusions> <exclusion> <groupId>group-c</groupId> <artifactId>excluded-artifact</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>group-a</groupId> <artifactId>artifact-b</artifactId> <version>1.0</version> <type>bar</type> <scope>runtime</scope> </dependency> </dependencies></project>

Page 25: MAVEN INTRODUCTION

Dependency MechanismExample :

Project B:<project> ... <dependencies> <dependency> <groupId>group-c</groupId> <artifactId>artifact-b</artifactId> <version>1.0</version> <type>war</type> <scope>runtime</scope> </dependency> <dependency> <groupId>group-a</groupId> <artifactId>artifact-b</artifactId> <version>1.0</version> <type>bar</type> <scope>runtime</scope> </dependency> </dependencies></project>

Page 26: MAVEN INTRODUCTION

Dependency MechanismExample :

These two example POMs share a common dependency and each has one non-trivial dependency. This information can be put in the parent POM like this:<project> ... <dependencyManagement> <dependencies> <dependency> <groupId>group-a</groupId> <artifactId>artifact-a</artifactId> <version>1.0</version>

<exclusions> <exclusion> <groupId>group-c</groupId> <artifactId>excluded-artifact</artifactId> </exclusion> </exclusions>

</dependency>

<dependency> <groupId>group-c</groupId> <artifactId>artifact-b</artifactId> <version>1.0</version> <type>war</type> <scope>runtime</scope> </dependency>

<dependency> <groupId>group-a</groupId> <artifactId>artifact-b</artifactId> <version>1.0</version> <type>bar</type> <scope>runtime</scope> </dependency> </dependencies> </dependencyManagement></project>

Page 27: MAVEN INTRODUCTION

Dependency MechanismExample :

And then the two child poms would become much simpler:Project A:<project> ... <dependencies> <dependency> <groupId>group-a</groupId> <artifactId>artifact-a</artifactId> </dependency>

<dependency> <groupId>group-a</groupId> <artifactId>artifact-b</artifactId> <!-- This is not a jar dependency, so we must specify type. --> <type>bar</type> </dependency> </dependencies></project>

Project B: <project> ... <dependencies> <dependency> <groupId>group-c</groupId> <artifactId>artifact-b</artifactId> <!-- This is not a jar dependency, so we must specify type. --> <type>war</type> </dependency>

<dependency> <groupId>group-a</groupId> <artifactId>artifact-b</artifactId> <!-- This is not a jar dependency, so we must specify type. --> <type>bar</type> </dependency> </dependencies></project>

Page 28: MAVEN INTRODUCTION

PluginsIn Maven, there are the build and the reporting plugins:

Build plugins will be executed during the build and then, they should be configured in the <build/> element.

Reporting plugins will be executed during the site generation and they should be configured in the <reporting/>element.

All plugins should have minimal required informations : groupId, artifactId and version.

<project> ... <build> <plugins> <plugin> <artifactId>maven-myquery-plugin</artifactId> <version>1.0</version> <configuration> <url>http://www.foobar.com/query</url> <timeout>10</timeout> <options> <option>one</option> <option>two</option> <option>three</option> </options> </configuration> </plugin> </plugins> </build> ...</project>

Page 29: MAVEN INTRODUCTION

Plugins -ParametersMapping Simple Objects:<configuration> <myString>a string</myString> <myBoolean>true</myBoolean></configuration>

Mapping Complex Objects:<configuration> <person> <firstName>Jason</firstName> <lastName>van Zyl</lastName> </person></configuration>

Mapping Lists:<configuration> <animals> <animal>cat</animal> <animal>dog</animal> </animals></configuration>

Mapping Maps:<configuration> <myMap> <key1>value1</key1> <key2>value2</key2> </myMap></configuration>

Mapping Properties:<property> <name>propertyName2</name> <value>propertyValue2</value> <property>

Page 30: MAVEN INTRODUCTION

Plugins –Build PluginsThe first execution with id "execution1" binds this configuration to the test phase. The second execution does not have a <phase> tag, how do you think will this execution behave? Well, goals can have a default phase binding as discussed further below. If the goal has a default phase binding then it will execute in that phase. But if the goal is not bound to any lifecycle phase then it simply won't be executed during the build lifecycle.

<project> ... <build> <plugins> <plugin> <artifactId>maven-myquery-plugin</artifactId> <version>1.0</version> <executions> <execution> <id>execution1</id> <phase>test</phase> <configuration> <url>http://www.foo.com/query</url> <timeout>10</timeout> <options> <option>one</option> <option>two</option> <option>three</option> </options> </configuration> <goals> <goal>query</goal> </goals> </execution> <execution> <id>execution2</id> <configuration> <url>http://www.bar.com/query</url> <timeout>15</timeout> <options> <option>four</option> <option>five</option> <option>six</option> </options> </configuration> <goals> <goal>query</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ...</project>

Page 31: MAVEN INTRODUCTION

Plugins –Build PluginsIf there are multiple executions bound to different phases, then the mojo is executed once for each phase indicated.

<project> ... <build> <plugins> <plugin> ... <executions> <execution> <id>execution1</id> <phase>test</phase> ... </execution> <execution> <id>execution2</id> <phase>install</phase> <configuration> <url>http://www.bar.com/query</url> <timeout>15</timeout> <options> <option>four</option> <option>five</option> <option>six</option> </options> </configuration> <goals> <goal>query</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ...</project>

Page 32: MAVEN INTRODUCTION

Plugins –Build PluginsDefault phase which is package has been overrided by install phase.

<project> ... <build> <plugins> <plugin> <artifactId>maven-myquery-plugin</artifactId> <version>1.0</version> <executions> <execution> <id>execution1</id> <phase>install</phase> <configuration> <url>http://www.bar.com/query</url> <timeout>15</timeout> <options> <option>four</option> <option>five</option> <option>six</option> </options> </configuration> <goals> <goal>query</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ...</project>

Page 33: MAVEN INTRODUCTION

Useful Commands$ mvn help:describe -Dplugin=help$ mvn help:effective-pom

$ mvn help:describe -DgroupId=org.somewhere -DartifactId=some-plugin -Dversion=0.0.0$ mvn help:describe -Dplugin=org.somewhere:some-plugin:0.0.0$ mvn help:describe -Dplugin=org.apache.maven.plugins:maven-help-plugin$ mvn help:describe -Dplugin=help

$ mvn help:describe -Dmojo=describe -DgroupId=org.apache.maven.plugins -DartifactId=maven-help-plugin

The cmd ParameterYou could also ask for a single Maven command, i.e. a goal or a phase or a lifecycle. It is the command when you call Maven, i.e.:$ mvn help:describe -Dcmd=clean$ mvn help:describe -Dcmd=compile$ mvn help:describe -Dcmd=compiler:compile

Page 34: MAVEN INTRODUCTION

Apache Maven PMD Plugin

The Apache Maven PMD plugin automatically runs the PMD code analysis tool on the source code and generates a site report with results. In a typical configuration, the build fails if PMD detects quality issues in the source.

<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>2.5</version> <executions> <execution> <goals> <goal>check</goal> <goal>cpd-check</goal> </goals> </execution> </executions> </plugin> </plugins> </build>