Rise of Automated Builds and Deployments Maven Introduction
Transcript
Rise of Automated Builds and Deployments
A build tool such as Ant is focused solely onpreprocessing,
compilation, packaging, testing, anddistribution.Maven is a project
management tool whichprovides a superset of features found in a
buildtool.Maven provides build capabilities, and can runreports,
generate a web site, and facilitatecommunication among members of a
workingteam.Maven is a project management tool whichencompasses a
project object model, a set ofstandards, a project lifecycle, a
dependencymanagement system, and logic for executing plugingoals at
defined phases in a lifecycle.
Maven incorporates convention over configurationconcept by
providing sensible default behavior forprojects.Source code is
assumed to be in${basedir}/src/main/javaResources are assumed to be
in${basedir}/src/main/resourcesTests are assumed to be in
${basedir}/src/testThe byte code is compiled
to${basedir}/target/classes and then a distributableJAR file is
created in ${basedir}/target.
Intelligence of Maven is implemented in theplugins which are
retrieved from the MavenRepository.The fact that Maven retrieves
bothdependencies and plugins from the remoterepository allows for
universal reuse of buildlogic.Maven has abstracted common build
tasks intoplugins which are maintained centrally andshared
universally.Maven maintains a model of a project withdescription of
the attributes of the project.
Dependency Management: A project is defined by aunique set of
coordinates consisting of a groupidentifier, an artifact
identifier, and a version, enablingthe coordinates to declare
dependencies.Remote Repositories: Coordinates defined in the
MavenProject Object Model (POM) can be used to createrepositories
of Maven artifacts.Universal Reuse of Build Logic: Plugins contain
logic thatworks with the descriptive data and
configurationparameters defined in Project Object Model (POM).Tool
Portability / Integration: Maven has standardizedthe Project
description maintained in the IDE, and whileeach IDE continues to
maintain custom projectfiles, they can be easily generated from the
model.Easy Searching and Filtering of Project Artifacts: Toolslike
Nexus allow you to index and search the contents ofa repository
using the information stored in the POM.
Create a simple pom.xml as
follows:4.0.0org.sonatype.mavenbookmy-project1.0Place your source
code in${basedir}/src/main/javaRun mvn install from the command
line.Run mvn site and then find an index.html file intarget/site
that contains links to JavaDoc and a fewreports about your source
code.
Ant doesnt have formal conventions like acommon project
directory structure or defaultbehavior.Ant is proceduralAnt doesnt
have a lifecycle, with goals andsequence of tasks defined for each
goal manually.Maven has conventions. It knows where yoursource code
is because you followed theconvention.Maven is declarative. A
pom.xml file is created andput into the source in the default
directory.Maven has a lifecycle which was invoked whenyou executed
mvn install. The command tellsMaven to execute a series of
sequential lifecyclephases until it reached the install lifecycle
phase.
Once Maven is unpacked to the installation directory, the
twoenvironment variables PATH and M2_HOME need to beset.To set
these environment variables from the command-line, type inthe
following Windows commands:set M2_HOME=c:Program
Filesapache-maven-2.2.1set PATH=%PATH%;%M2_HOME%binCorresponding
Linux Commands:cd /usr/localln -s apache-maven-2.2.1 mavenexport
M2_HOME=/usr/local/mavenexport PATH=${M2_HOME}/bin:${PATH}Check the
version by running mvn -v from the command-line.~/.m2/settings.xml
contains user-specific configuration forauthentication,
repositories and other information.~/.m2/repository/ contains the
local Maven repository.
To start a new Maven project, use the MavenArchetype plugin
from the command line.$ mvn archetype:generate
-DgroupId=org.sonatype.mavenbook.simple -DartifactId=simple
-DpackageName=org.sonatype.mavenbook
-Dversion=1.0-SNAPSHOTarchetype:generate is called a Maven goal.The
-Dname=value pairs are arguments that arepassed to the goal and
take the form of -Dproperties.The plugin is the prefix archetype,
and the goal isgenerate.The project is installed using the mvn
installcommand.
The Maven Archetype plugin creates a directory simple/that
matches the artifactId, known as the projects basedirectory.Every
Maven project has a Project Object Model (POM)in pom.xml which
describes the project, configuresplugins, and declares
dependencies.All the projects source code and resources are
placedunder src/main.In a Java project, Java classes are placed
insrc/main/java and classpath resources are placed
insrc/main/resources.The test cases for the project are located in
src/test.All tests are placed in src/test/java, and
classpathresources for tests are located in
src/test/resources.
The first few elements in POMgroupId, artifactId,
packaging,versionare known as the Maven coordinates which
uniquelyidentify a project.name and url are descriptive elements of
the POM providing ahuman readable name and associating the project
with a website.The dependencies element defines a single,
test-scopeddependency on a unit testing frameworkMaven always
executes against an effective POM, acombination of settings from
the projects pom.xml, all parentPOMs, a super-POM defined within
Maven, user-definedsettings, and active profiles.All projects
ultimately extend the super-POM, which defines aset of sensible
default configuration settings.The "effective" POM can be seen
(with the contents of theprojects POM interpolated with the
contents of all parentPOMs, user settings, and any active profiles)
using thecommand:$ mvn help:effective-pom
A Maven Plugin is a collection of one or moregoals.Maven also
provides for the ability to definecustom plugins.Maven plugins can
be simple core plugins likethe Jar plugin, which contains goals for
creatingJAR files, Compiler plugin, which contains goalsfor
compiling source code and unit tests, or theSurefire plugin, which
contains goals forexecuting unit tests and generating reports.
A goal is a specific task that may be executed as astandalone
goal or along with other goals as partof a larger build.A goal is a
unit of work in Maven.The compile goal in the Compiler plugin,
compilesall of the source code for a project.Goals are configured
via configuration propertiesthat can be used to customize
behavior.When referring to a plugin goal, we frequently usethe
shorthand notation, pluginId:goalId similar
toarchetype:generate.Goals define parameters that can define
sensibledefault values.
The command mvn install doesnt specify a plugingoal but
specifies a Maven lifecycle phase.A phase is a step in what Maven
calls the buildlifecycle which is an ordered sequence of
phasesinvolved in building a project.Maven can support a number of
differentlifecycles, but the one thats most often used is
thedefault Maven lifecycle, which begins with a phaseto validate
the basic integrity of the project andends with a phase that
involves deploying a projectto production.Plugin goals can be
attached to a lifecycle phase.As Maven moves through the phases in
a lifecycle, itwill execute the goals attached to each
particularphase.Each phase may have zero or more goals bound to
it
When mvn install reached the package phase, itexecuted the jar
goal in the Jar plugin.Since the simple Quickstart project has (by
default) a jarpackaging type, the jar:jar goal is bound to the
packagephase.The preceding goals are executed as Maven stepsthrough
the phases preceding package in the Mavenlifecycle; executing a
phase will first execute allpreceding phases in order, ending with
the phasespecified on the command line.Each phase corresponds to
zero or more goals, and asno plugin configuration or customization
is performed.
When Maven executes a goal, each goal has accessto the
information defined in a projects POM.Goals execute in the context
of a POM.Goals are actions we wish to take upon aproject, and a
project is defined by a POM.The POM names the project, provides a
set ofunique identifiers (coordinates) for a project, anddefines
the relationships between this project andothers through
dependencies, parents, andprerequisites.Maven coordinates define a
set of identifiers whichcan be used to uniquely identify a project,
adependency, or a plugin in a Maven POM.
The combined identifiers: thegroupId, artifactId, version and
packaging make up theprojects maven coordinates.Maven pinpoints a
project via its coordinates when oneproject relates to another,
either as a dependency, aplugin, or a parent project
reference.groupId: Thegroup, company, team, organization, project,
or othergroup. It begins with reverse domain name of
org.artifactId: A unique identifier under groupId thatrepresents a
single project.version: A specific release of a project.packaging:
The type of project, defaulting tojar, describing the packaged
output produced by aproject. This is not a part of a projects
unique identifier.
A repository is a collection of project artifactsstored in a
directory structure that closelymatches a projects Maven
coordinates.The standard for a Maven repository is to storean
artifact in the following directory relative tothe root of the
repository:////-..Maven always looks up for the artifact in
thelocal repository before downloading it from theremote Maven
repository.
Maven downloads POM files for dependency inaddition to
artifacts on order to support transitivedependencies.Maven adds all
the dependencies of the library tothe projects dependencies
implicitly resolvingconflicts with default behavior.The POM file
declares dependencies on otherartifacts which are called transitive
dependencies.Maven also provides for different dependencyscopes
limiting its availability for particular goals.The provided scope
tells Maven that a dependencyis needed for compilation, but should
not bebundled with the output of a build.
Create a basic skeleton of project using MavenArchetype using
mvn archetype:generate command.Configure the Maven Compiler plugin
to target Java 5using the POM.maven-compiler-plugin1.51.5
Add Organizational, Legal, and DeveloperInformation to the
pom.xml.Add project dependencieslog4jlog4j1.2.14The
http://repository.sonatype.org contains somedependency
libraries.
Add new packages (directories) in projectssource code location
stored in src/main/java.Add resources to the default package (or in
rootof the classpath) such as src/main/resources.The program is
executed using the Exec pluginfrom the Codehaus Mojo project.mvn
installmvn exec:java
-Dexec.mainClass=org.sonatype.mavenbook.weather.MainAdd unit tests
to the src/test/java folder.
The Exec plugin allows you to execute Java classes andother
scripts.It is not a core Maven plugin, but it is available from
theMojo project hosted by Codehaus.Description of the plugin can be
found by:mvn help:describe -Dplugin=exec DfullTo find out what is
on the classpath, the MavenDependency plugin can be used to print
out a list ofresolved dependencies.mvn dependency:resolvemvn
dependency:treeTo see the full dependency trail, including
rejectedartifacts:mvn install -X
A test-scoped dependency is a dependency that isavailable on
the classpath only during test compilationand test execution.If the
project has war or ear packaging, a test-scopeddependency would not
be included in the projectsoutput archive.To add a test-scoped
dependency, add the dependencyelement to the projects dependencies
section in thePOM file.run mvn dependency:resolve to see the
dependencyelement listed as a dependency with scope test.Add the
test resources in the src/test/resourcesdirectory.The test phase
run for the mvn package or mvn installcommands, along with mvn test
which runs all thelifecycle phases up test phase.
When Maven encounters a build failure, its default behavior is
tostop the current build.To continue building a project even when
the Surefire pluginencounters failed test cases, the
testFailureIgnore configurationproperty of the Surefire plugin
should be set to true.mvn test
-Dmaven.test.failure.ignore=trueorg.apache.maven.pluginsmaven-surefire-plugintruetrueTo
skip the unit tests, the maven.test.skip properties should be set
totrue.mvn install -Dmaven.test.skip=true
The Maven Assembly plugin is a plugin to create
arbitrarydistributions for applications.It can be used to assemble
the output of any project in any format bydefining a custom
assembly descriptor.
[...]maven-assembly-pluginjar-with-dependencies[...]Command to
build the assembly: mvn install assembly:assembly