Friday, 15 November 2013

Maven Core Concept



Apache Maven

Introducing

 

The great majority of Maven users are going to call Maven a “build tool”: a tool used to build deployable artifacts from source code. Build engineers and project managers might refer to Maven as something more comprehensive: a project management tool.
What is the difference? A build tool such as Ant is focused solely on preprocessing, compilation, packaging, testing, and distribution. A project management tool such as Maven provides a superset of features found in a build tool. In addition to providing build capabilities, Maven can also run reports, generate a web site, and facilitate communication among members of a working team.

                A more formal definition of Apache Maven: Maven is a project management tool which encompasses a project object model, a set of standards, a project lifecycle, a dependency management system, and logic for executing plugin goals at defined phases in a lifecycle. When you use Maven, you describe your project using a well-defined project object model, Maven can then apply cross-cutting logic from a set of shared (or custom) plugins.

Common Interface

              While Maven provides an array of benefits including dependency management and reuse of common build logic through plugins, the core reason why it has succeeded is that it has defined a common interface for building software. When you see that a project like Apache ActiveMQ uses Maven, you can assume that you’ll be able to check it out from source and build it with mvn install without much hassle. You know where the ignition keys goes, you know that the gas pedal is on the right-side, and the brake is on the left.

Universal  Reuse through Maven Plugin

             It is this mechanism that affects much more than the Surefire plugin. Maven has plugins for everything from compiling Java code, to generating reports, to deploying to an application server. Maven has abstracted common build tasks into plugins which are maintained centrally and shared universally. If the state-of-the-art changes in any area of the build, if some new unit testing framework is released or if some new tool is made available, you don’t have to be the one to hack your project’s custom build system to support it. You benefit from the fact that plugins are downloaded from a remote repository and maintained centrally. This is what is meant by universal reuse through Maven plugins.


Conceptual Model Of a “Project”

Dependency Management

Because a project is defined by a unique set of coordinates consisting of a group identifier, an artifact identifier, and a version, projects can now use these coordinates to declare dependencies.

Remote Repositories


Related to dependency management, we can use the coordinates defined in the Maven Project Object Model (POM) to create repositories of Maven artifacts.

Universal Reuse of Build Logic


Plugins contain logic that works with the descriptive data and configuration parameters defined in Project Object Model (POM); they are not designed to operate upon specific files in known locations.

Tool Portability / Integration


Tools like Eclipse, NetBeans, and IntelliJ now have a common place to find information about a project. Before the advent of Maven, every IDE had a different way to store what was essentially a custom Project Object Model (POM). Maven has standardized this description, and while each IDE continues to maintain custom project files, they can be easily generated from the model.

Easy Searching and Filtering of Project Artifacts


Tools like Nexus allow you to index and search the contents of a repository using the information stored in the POM

A Simple Ant Build.xml

--------------------------------------------------------------------------------------------------------------------------------------
<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>
--------------------------------------------------------------------------------------------------------------------------------------
                     In this simple Ant example, you can see how you have to tell Ant exactly what to do. There is a compile goal which includes the javac task that compiles the source in the src/main/java directory to the target/classes directory. You have to tell Ant exactly where your source is, where you want the resulting bytecode to be stored, and how to package this all into a JAR file. While there are some recent developments that help make Ant less procedural, a developer’s experience with Ant is in coding a procedural language written in XML.

                 Contrast the previous Ant example with a Maven example. In Maven, to create a JAR file from some Java source, all you need to do is create a simple pom.xml, place your source code in ${basedir}/src/main/java and then run mvn install from the command line. The example Maven pom.xml that achieves the same results as the simple Ant file listed in A Simple Ant build.xml file is shown in A Sample Maven pom.xml.

A Sample Maven pom.xml. 


<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.sonatype.mavenbook</groupId>
    <artifactId>my-project</artifactId>
    <version>1.0</version>
</project>
The differences between Ant and Maven in this example are:

Apache 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.
                          The decision to use Maven or Ant isn’t a binary one, and Ant still has a place in a complex build. If your current build contains some highly customized process, or if you’ve written some Ant scripts to complete a specific process in a specific way that cannot be adapted to the Maven standards, you can still use these scripts with Maven. Ant is made available as a core Maven plugin. Custom Maven plugins can be implemented in Ant, and Maven projects can be configured to execute Ant scripts within the Maven project lifecycle.

Installing Maven on Microsoft Windows



             Once you’ve unpacked Maven to the installation directory, you will need to set two environment variables—PATH and M2_HOME. To set these environment variables from the command-line, type in the following commands:
C:\Users\tobrien > +set M2_HOME=c:\Program Files\apache-maven-3.0.3+
C:\Users\tobrien > +set PATH=%PATH%;%M2_HOME%\bin+
Setting these environment variables on the command-line will allow you to run Maven in your current session, but unless you add them to the System environment variables through the control panel, you’ll have to execute these two lines every time you log into your system. You should modify both of these variables through the Control Panel in Microsoft Windows.
Once Maven is installed, you can check the version by running mvn -v from the command-line. If Maven has been installed, you should see something resembling the following output.
$ mvn -v
Apache Maven 2.2.0 (r788681; 2009-06-26 08:04:01-0500)
Java version: 1.5.0_19
Java home: /System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home
Default locale: en_US, platform encoding: MacRoman
OS name: "mac os x" version: "10.5.7" arch: "i386" Family: "unix"
If you see this output, you know that Maven is available and ready to be used. If you do not see this output, and your operating system cannot find the mvn command, make sure that your PATH environment variable and M2_HOME environment variable have been properly set.

User-specific Configuration and Repository

Once you start using Maven extensively, you’ll notice that Maven has created some local user-specific configuration files and a local repository in your home directory. In ~/.m2 there will be:
~/.m2/settings.xml
A file containing user-specific configuration for authentication, repositories, and other information to customize the behavior of Maven.
~/.m2/repository/

The Project Model



             This chapter covers the central concept of Maven—the Project Object Model. The POM is where a project’s identity and structure are declared, builds are configured, and projects are related to one another. The presence of a pom.xml file defines a Maven project

            Maven projects, dependencies, builds, artifacts: all of these are objects to be modeled and described. These objects are described by an XML file called a Project Object Model. The POM tells Maven what sort of project it is dealing with and how to modify default behavior to generate output from source. In the same way a Java web application has a web.xml that describes, configures, and customizes the application, a Maven project is defined by the presence of a pom.xml. It is a descriptive declaration of a project for Maven; it is the figurative “map” that Maven needs to understand what it is looking at when it builds your project.

         We’ve established that the POM describes and declares, it is unlike Ant or Make in that it doesn’t provide explicit instructions, and we’ve noted that POM concepts are not specific to Java.

General project information

This includes a project’s name, the URL for a project, the sponsoring organization, and a list of developers and contributors along with the license for a project.

Build settings

In this section, we customize the behavior of the default Maven build. We can change the location of source and tests, we can add new plugins, we can attach plugin goals to the lifecycle, and we can customize the site generation parameters.

Build environment

The build environment consists of profiles that can be activated for use in different environments. For example, during development you may want to deploy to a development server, whereas in production you want to deploy to a production server. The build environment customizes the build settings for specific environments and is often supplemented by a custom settings.xml in ~/.m2. 

POM relationships

A project rarely stands alone; it depends on other projects, inherits POM settings from parent projects, defines its own coordinates, and may include submodules.

The Super POM

               
                Before we dive into some examples of POMs, let’s take a quick look at the Super POM. All Maven project POMs extend the Super POM, which defines a set of defaults shared by all projects. This Super POM is a part of the Maven installation and can be found in the maven-3.0.3-uber.jar file in ${M2_HOME}/lib. If you look in this JAR file, you will find a file named pom-4.0.0.xml under the org.apache.maven.project package.

The Super POM defines some standard configuration variables that are inherited by all projects. Those values are captured in the annotated sections:
(1)
The default Super POM defines a single remote Maven repository with an ID of central. This is the central Maven repository that all Maven clients are configured to read from by default. This setting can be overridden by a custom settings.xml file. Note that the default Super POM has disabled snapshot artifacts on the central Maven repository. If you need to use a snapshot repository, you will need to customize repository settings in your pom.xml or in your settings.xml. 
(2)
The central Maven repository also contains Maven plugins. The default plugin repository is the central Maven repository. Snapshots are disabled, and the update policy is set to “never,” which means that Maven will never automatically update a plugin if a new version is released.
(3)
The build element sets the default values for directories in the Maven Standard Directory layout.
(4)
Starting in Maven 2.0.9, default versions of core plugins have been provided in the Super POM. This was done to provide some stability for users that are not specifying versions in their POMs.

The Simplest POM

All Maven POMs inherit defaults from the Super POM (introduced earlier in the section Section 3.2.1, “The Super POM”). If you are just writing a simple project that produces a JAR from some source in src/main/java, want to run your JUnit tests in src/test/java, and want to build a project site using mvn site, you don’t have to customize anything. All you would need, in this case, is the simplest possible POM shown in The Simplest POM. This POM defines a groupId, artifactId, and version: the three required coordinates for every project.

The Effective POM

Executing the effective-pom goal should print out an XML document capturing the merge between the Super POM and the POM from The Simplest POM.

POM Syntex



Project Version :

       A project’s version number is used to group and order releases. Maven versions contain the following parts: major version, minor version, incremental version, and qualifier. In a version, these parts correspond to the following format:
<major version>.<minor version>.<incremental version>-<qualifier>
For example, the version "1.3.5" has a major version of 1, a minor version of 3, and an incremental version of 5. The version "5" has a major version of 5 and no minor or incremental version. The qualifier exists to capture milestone builds: alpha and beta releases, and the qualifier is separated from the major, minor, and incremental versions by a hyphen. For example, the version "1.3-beta-01" has a major version of 1, a minor version of 3, and a qualifier of "beta-01".
Keeping your version numbers aligned with this standard will become very important when you want to start using version ranges in your POMs. Version ranges allow you to specify a dependency on a range of versions, and they are only supported because Maven has the ability to sort versions based on the version release number format introduced in this section.
If your version release number matches the format <major>.<minor>.<incremental>-<qualifier> then your versions will be compared properly; "1.2.3" will be evaluated as a more recent build than "1.0.2", and the comparison will be made using the numeric values of the major, minor, and incremental versions. If your version release number does not fit the standard introduced in this section, then your versions will be compared as strings; "1.0.1b" will be compared to "1.2.0b" using a String comparison.

Project Depenedancy

         Maven can manage both internal and external dependencies. An external dependency for a Java project might be a library such as Plexus, the Spring Framework, or Log4J. An internal dependency is illustrated by a web application project depending on another project that contains service classes, model objects, or persistence logic. Project Dependencies shows some examples of project dependencies.

<project>
    ...
    <dependencies>
        <dependency>
            <groupId>org.codehaus.xfire</groupId>
            <artifactId>xfire-java5</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    ...
</project>
                   The first dependency is a compile dependency on the XFire SOAP library from Codehaus. You would use this type of dependency if your project depended on this library for compilation, testing, and during execution. The second dependency is a test-scoped dependency on JUnit. You would use a test-scoped dependency when you need to reference this library only during testing. The last dependency in Project Dependencies is a dependency on the Servlet 2.4 API. The last dependency is scoped as a provided dependency. You would use a provided scope when the application you are developing needs a library for compilation and testing, but this library is supplied by a container at runtime.

Dependancy Scope

Project Dependencies briefly introduced three of the five dependency scopes: compile, test, and provided. Scope controls which dependencies are available in which classpath, and which dependencies are included with an application. Let’s explore each scope in detail:

compile

compile+ is the default scope; all dependencies are compile-scoped if a scope is not supplied. compile dependencies are available in all classpaths, and they are packaged.

provided

provided+ dependencies are used when you expect the JDK or a container to provide them. For example, if you were developing a web application, you would need the Servlet API available on the compile classpath to compile a servlet, but you wouldn’t want to include the Servlet API in the packaged WAR; the Servlet API JAR is supplied by your application server or servlet container. provided dependencies are available on the compilation classpath (not runtime). They are not transitive, nor are they packaged.

runtime

runtime+ dependencies are required to execute and test the system, but they are not required for compilation. For example, you may need a JDBC API JAR at compile time and the JDBC driver implementation only at runtime.

test

test+-scoped dependencies are not required during the normal operation of an application, and they are available only during test compilation and execution phases.

system

The system scope is similar to provided except that you have to provide an explicit path to the JAR on the local file system. This is intended to allow compilation against native objects that may be part of the system libraries. The artifact is assumed to always be available and is not looked up in a repository. If you declare the scope to be system, you must also provide the systemPath element. Note that this scope is not recommended (you should always try to reference dependencies in a public or custom Maven repository).

Optional Dependancy

Assume that you are working on a library that provides caching behavior. Instead of writing a caching system from scratch, you want to use some of the existing libraries that provide caching on the file system and distributed caches. Also assume that you want to give the end user an option to cache on the file system or to use an in-memory distributed cache. To cache on the file system, you’ll want to use a freely available library called EHCache (http://ehcache.sourceforge.net/), and to cache in a distributed in-memory cache, you want to use another freely available caching library named SwarmCache ( http://swarmcache.sourceforge.net/ ). You’ll code an interface and create a library that can be configured to use either EHCache or SwarmCache, but you want to avoid adding a dependency on both caching libraries to any project that depends on your library.
In other words, you need both libraries to compile this library project, but you don’t want both libraries to show up as transitive runtime dependencies for the project that uses your library. You can accomplish this by using optional dependencies as shown in Declaring Optional Dependencies.

Dependancy Version Ranges

dependency; you can specify a range of versions that would satisfy a given dependency. For example, you can specify that your project depends on version 3.8 or greater of JUnit, or anything between versions 1.2.10 and 1.2.14 of JUnit. You do this by surrounding one or more version numbers with the following characters:
(, )
Exclusive quantifiers
[, ]
Inclusive quantifiers
For example, if you wished to access any JUnit version greater than or equal to 3.8 but less than 4.0, your dependency would be as shown in Specifying a Dependency Range: JUnit 3.8 - JUnit 4.0.

Note

When declaring a "normal" version such as 3.8.2 for Junit, internally this is represented as "allow anything, but prefer 3.8.2." This means that when a conflict is detected, Maven is allowed to use the conflict algorithms to choose the best version. If you specify [3.8.2], it means that only 3.8.2 will be used and nothing else. If somewhere else there is a dependency that specifies [3.8.1], you would get a build failure telling you of the conflict. We point this out to make you aware of the option, but use it sparingly and only when really needed. The preferred way to resolve this is via dependencyManagement.
Project Relationship and POM best practices


The Build Lifecycle



Clean life Cycle

The first lifecycle you’ll be interested in is the simplest lifecycle in Maven. Running mvn clean invokes the clean lifecycle which consists of three lifecycle phases:
  • pre-clean
  • clean
  • post-clean

Site LifeCycle

Maven does more than build software artifacts from project, it can also generate project documentation and reports about the project, or a collection of projects. Project documentation and site generation have a dedicated lifecycle which contains four phases:
  1. pre-site
  2. site
  3. post-site
  4. site-deploy
The default goals bound to the site lifecycle is:
  1. site - site:site
  2. site-deploy -site:deploy
The packaging type does not usually alter this lifecycle since packaging types are concerned primarily with artifact creation, not with the type of site generated. The Site plugin kicks off the execution of Doxia document generation and other report generation plugins. You can generate a site from a Maven project by running the following command:
$ mvn site

Package Specific Lifecycle


The specific goals bound to each phase default to a set of goals specific to a project’s packaging. A project with packaging jar has a different set of default goals from a project with a packaging of war. The packaging element affects the steps required to build a project. For an example of how the packaging affects the build, consider two projects: one with pom packaging and the other with jar packaging. The project with pom packaging will run the site:attach-descriptor goal during the package phase, and the project with jar packaging will run the jar:jar goal instead.

The following sections describe the lifecycle for all built-in packaging types in Maven. Use these sections to find out what default goals are mapped to default lifecycle phases.

JAR



Lifecycle Phase
Goal
process-resources
resources:resources
Compile
compiler:compile
process-test-resources
resources:testResources
test-compile
compiler:testCompile
Test
surefire:test
Package
jar:jar
Install
install:install
Deploy
deploy:deploy


POM

POM is the simplest packaging type. The artifact that it generates is itself only, rather than a JAR, SAR, or EAR. There is no code to test or compile, and there are no resources the process. The default goals for projects with POM packaging are shown in Table 4.3, “Default Goals for POM Packaging”.
Lifecycle Phase
Goal
Package
site:attach-descriptor
Install
install:install
Deploy
deploy:deploy

WAR

The WAR packaging type is similar to the JAR and EJB types. The exception being the package goal of war:war. Note that the war:war goal requires a web.xml configuration in your src/main/webapp/WEB-INF directory.
Lifecycle Phase
Goal
process-resources
resources:resources
Compile
compiler:compile
process-test-resources
resources:testResources
test-compile
compiler:testCompile
Test
surefire:test
Package
war:war
Install
install:install
Deploy
deploy:deploy



Running Maven


To run Maven just type mvn plus particular command for some specific task in command prompt. Like:
To define a property use the following option on the command line:
-D, --define <arg>                Defines a system property
Ex. mvn install -Dmaven.test.skip=true
 
-p is used to activate profiles: mvn –p test

To list the available command line parameters, use the following command line option:
mvn --help

To activate one or more build profiles from the command line, use the following option:
- P, --activate-profiles <arg>  
Comma-delimited list of profiles to activate
To display Maven version information, use one of the following options on the command line:
mvn -v, --version
                Display version information
-V, --show-version
Display version information WITHOUT stopping build

Both of these options produce the same version information output, but the -v option will terminate the Maven process after printing out the version. You would use the -V option if you wanted to have the Maven version information present at the beginning of your build’s output.

Making Project Dependents

While the -am command makes all of the projects required by a particular project in a multi-module build, the -amd or --also-make-dependents option configures Maven to build a project and any project that depends on that project. When using --also-make-dependents, Maven will examine all of the projects in our reactor to find projects that depend on a particular project. It will automatically build those projects and nothing else.

Resuming a "make" build

When using --also-make, Maven will execute a subset of the larger build . Combining --project, --also-make, and --resume-from provides you with the ability to refine your build even further. The -rf or --resume-from resumes the build from a specific point in the Reactor build order.
$ mvn --projects sample-webapp --also-make \
      --resume-from sample-services install
[INFO] Scanning for projects...
[INFO] Reactor build order:
[INFO]   sample-services
[INFO]   sample-util
[INFO]   sample-security
[INFO]   sample-webapp




SETTING DETAILS


The settings element in the settings.xml file contains elements used to define values which configure Maven execution. Settings in this file are settings which apply to many projects and which should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information. There are two locations where a settings.xml file may live:
  • Maven Installation Directory: $M2_HOME/conf/settings.xml
  • User-specific Settings File: ~/.m2/settings.xml
Here is an overview of the top elements under settings:

Overview of top-level elements in settings.xml.

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              http://maven.apache.org/xsd/settings-1.0.0.xsd">

    <localRepository/>
    <interactiveMode/>
    <usePluginRegistry/>
    <offline/>
    <pluginGroups/>
    <servers/>
    <mirrors/>
    <proxies/>
    <profiles/>
    <activeProfiles/>
</settings>

 Simple Values

Half of the top-level settings elements are simple values, representing a range of values which configure the core behavior of Maven:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <localRepository>${user.dir}/.m2/repository</localRepository>
    <interactiveMode>true</interactiveMode>
    <usePluginRegistry>false</usePluginRegistry>
    <offline>false</offline>
    <pluginGroups>
        <pluginGroup>org.codehaus.mojo</pluginGroup>
    </pluginGroups>
    ...
</settings>
localRepository
This value is the path of this build system’s local repository. The default value is ${user.dir}/.m2/repository.
interactiveMode
true if Maven should attempt to interact with the user for input, false if not. Defaults to true.
usePluginRegistry
true if Maven should use the ${user.dir}/.m2/plugin-registry.xml file to manage plugin versions, defaults to false.
offline
true if this build system should operate in offline mode, defaults to false. This element is useful for build servers which cannot connect to a remote repository, either because of network setup or security reasons.
pluginGroups
This element contains a list of pluginGroup elements, each contains a groupId. The list is searched when a plugin is used and the groupId is not provided in the command line. This list contains org.apache.maven.plugins by default.

Servers

The distributionManagement element of the POM defines the repositories for deployment. However, certain settings such as security credentials should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml
Server configuration in settings.xml.    <servers>
        <server>
            <id>server001</id>
            <username>my_login</username>
            <password>my_password</password>
            <privateKey>${user.home}/.ssh/id_dsa</privateKey>
            <passphrase>some_passphrase</passphrase>
            <filePermissions>664</filePermissions>
            <directoryPermissions>775</directoryPermissions>
            <configuration></configuration>
        </server>
    </servers>
id
This is the id of the server (not of the user to login as) that matches the distributionManagement repository element’s id.
username, password
These elements appear as a pair denoting the login and password required to authenticate to this server.
privateKey, passphrase
Like the previous two elements, this pair specifies a path to a private key (default is ${user.home}/.ssh/id_dsa) and a passphrase, if required. The passphrase and password elements may be externalized in the future, but for now they must be set plain-text in the settings.xml file.
filePermissions, directoryPermissions
When a repository file or directory is created on deployment, these are the permissions to use. The legal values of each is a three digit number corresponding to *nix file permissions, i.e. 664, or 775.

Mirrors

<mirror>
            <id>planetmirror.com</id>
            <name>PlanetMirror Australia</name>
            <url>http://downloads.planetmirror.com/pub/maven2</url>
            <mirrorOf>central</mirrorOf>
        </mirror>
id, name
The unique identifier of this mirror. The id is used to differentiate between mirror elements.
url
The base URL of this mirror. The build system will use prepend this URL to connect to a repository rather than the default server URL.
mirrorOf
The id of the server that this is a mirror of. For example, to point to a mirror of the Maven central server (http://repo1.maven.org/maven2), set this element to central. This must not match the mirror id.

Proxies

<proxies>
        <proxy>
            <id>myproxy</id>
            <active>true</active>
            <protocol>http</protocol>
            <host>proxy.somewhere.com</host>
            <port>8080</port>
            <username>proxyuser</username>
            <password>somepassword</password>
            <nonProxyHosts>*.google.com|ibiblio.org</nonProxyHosts>
        </proxy>
    </proxies>

Profiles

The profile element in the settings.xml is a truncated version of the pom.xml profile element. It consists of the activation, repositories, pluginRepositories and properties elements. The profile elements only include these four elements because they concern themselves with the build system as a whole (which is the role of the settings.xml file), not about individual project object model settings.
If a profile is active from settings, its values will override any equivalent profiles which matching identifiers in a POM or profiles.xml file.

Activation

Activations are the key of a profile. Like the POM’s profiles, the power of a profile comes from its ability to modify some values only under certain circumstances; those circumstances are specified via an activation element.
<profile>
            <id>test</id>
            <activation>
                <activeByDefault>false</activeByDefault>
                <jdk>1.5</jdk>
                <os>
                    <name>Windows XP</name>
                    <family>Windows</family>
                    <arch>x86</arch>
                    <version>5.1.2600</version>
                </os>
                <property>
                    <name>mavenVersion</name>
                    <value>2.0.3</value>
                </property>
                <file>
                    <exists>${basedir}/file2.properties</exists>
                    <missing>${basedir}/file1.properties</missing>
                </file>
            </activation>
            ...
        </profile>
Activation occurs when all specified criteria have been met, though not all are required at once.
property
The profile will activate if Maven detects a property (a value which can be dereferenced within the POM by ${name}) of the corresponding name=value pair.
file
Finally, a given filename may activate the profile by the existence of a file, or if it is missing.
The activation element is not the only way that a profile may be activated. The settings.xml file’s activeProfile element may contain the profile’s id. They may also be activated explicitly through the command line via a comma separated list after the P flag (e.g. -P test).
To see which profile will activate in a certain build, use the maven-help-plugin.
mvn help:active-profiles

 

 

Properties

Maven properties are value placeholder. Their values are accessible anywhere within a POM by using the notation ${X}, where X is the property. They come in five different styles, all accessible from the settings.xml file:

Repositories

Repositories are remote collections of projects from which Maven uses to populate the local repository of the build system. It is from this local repository that Maven calls it plugins and dependencies. Different remote repositories may contain different projects, and under the active profile they may be searched for a matching release or snapshot artifact.

            <repositories>
                <repository>
                    <id>codehausSnapshots</id>
                    <name>Codehaus Snapshots</name>
                    <releases>
                        <enabled>false</enabled>
                        <updatePolicy>always</updatePolicy>
                        <checksumPolicy>warn</checksumPolicy>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                        <updatePolicy>never</updatePolicy>
                        <checksumPolicy>fail</checksumPolicy>
                    </snapshots>
                    <url>http://snapshots.maven.codehaus.org/maven2</url>
                    <layout>default</layout>
                </repository>
            </repositories>

Plugin Repositories

The structure of the pluginRepositories element block is similar to the repositories element. The pluginRepository elements each specify a remote location of where Maven can find plugins artifacts.

            <pluginRepositories>
                <pluginRepository>
                    <id>codehausSnapshots</id>
                    <name>Codehaus Snapshots</name>
                    <releases>
                        <enabled>false</enabled>
                        <updatePolicy>always</updatePolicy>
                        <checksumPolicy>warn</checksumPolicy>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                        <updatePolicy>never</updatePolicy>
                        <checksumPolicy>fail</checksumPolicy>
                    </snapshots>
                    <url>http://snapshots.maven.codehaus.org/maven2</url>
                    <layout>default</layout>
                </pluginRepository>
            </pluginRepositories>

Active Profiles

Setting active profiles in settings.xml. 

<activeProfiles>
        <activeProfile>env-test</activeProfile>
</activeProfiles>

No comments:

Post a Comment