Writing a Custom Plugin for Maven

Introduction

In this article, we will learn about Maven which is a project management framework that provides a configurable approach for managing software projects. Maven covers all the necessary phases that happen right from project creation, building, documentation, reporting, installation and deployment. This article begins with the basics of Maven along with the concepts like Project Object Model (aka POM), the various life-cycles in Maven etc. Then it continues with using Maven for creating a project till installation of the project in a local repository. The latter part of the article provides details about creating custom Maven plugins that can be executed in stand-alone mode as well as part of some Maven life-cycle.

Maven Custom Plug-In (Example Code)

Maven Concepts

In this section, we will see the basics of Maven concepts like Project Object Model, the standard lifecycles available in Maven as well as the dependency scope that comes up while dealing with dependency with projects.

Project Object Model

Project information, its dependencies and the artifacts that can be built are described in POM which is essentially a configuration file in XML. POM basically contains instructions on what needs to be done during the various life-cycles that happen during a build. Note that the POM is not coupled to java projects, in fact the project can be written in any language like C, C# etc. For example, consider the sample minimal POM,

 

<project>

    <modelVersion>4.0.0</modelVersion>

    <name>adder</name>
    <url>http://www.javabeat.net/adder</url>
    <groupId>net.javabeat.adder</groupId>
    <artifactId>adder</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

Have a look at the above POM. It defines the information about the project and its dependant projects. We will look into more details about the various POM elements.

 

  • modelVersion – This defines the version of the POM.
  • name – The name of the project.
  • groupId – This identifies the group (or the organization) that created the project. This property usually takes the domain address which represents the group or the organization so that uniqueness is maintained across the groups.
  • artifactId – This identifies the artifact (output component) name that comes from a project. Artifacts can be anything like a JAR, WAR, EAR etc
  • version – This property identifies the version of the artifact. Usually the version takes the format as “majorVersion.minorVersion-qualifier”. For example, “1.1-alpha”, “1.2-beta”, “1.3-SNAPSHOT”. packaging – Represents the type of artifact, for example – jar, war, ear etc.

In the next section in the POM, we have included the dependencies of the project. Note that this section is optional. If there are no dependencies for a project (which is unlikely the case), this can be omitted. However, in this example case, we have declared a dependency to junit and it is expected that the project will contain some test resources. It is always a good idea to define the version of the artifact while defining a dependency, so that during runtime, we are not facing any issues because of version match. We have mentioned the scope as test, more details about this element will follow in the forthcoming section.

Dependency Scope

A project can depend on a number of dependent projects and Maven provides a way for defining the dependencies among projects through configuration. One can control the level of dependency through scope and the default being ‘compile’. The following scopes are available.

 

  • Compile – This being the default scope will be available at the classpath during the compilation as well as during runtime.
  • Runtime – The presence of this scope ensures that the dependency will be available at the runtime and not during the compile-time. For example, one may use the Servlet API during the compilation phase, however the Servlet implementation (from Sun, Oracle, IBM etc) will be required during the runtime only.
  • Test – This scope ensures that the dependency is available during the compilation of the test resources as well as during the execution of the test resources.
  • Provided – This dependency is mostly used while developing J2EE applications where the dependency is available as part of the J2EE container (or any Container) and it is not necessary for the project to package the dependency as part of the artifact. For example, while developing Enterprise bean applications, as part of the project, we will be using EJB jar for compilation; however, we never package this jar as part of the project because the EJB container will provide this jar.

Build Life-cycle

life-cycle defines the execution for achieving a set of goals. Each life-cycle defines a sequence of phases for achieving the goals. The

Maven Custom Plug-In (Example Code)

Using Maven

In this section, we will see how to use maven for creating, compiling, building, packaging and installing a project. Download the latest version of Maven from here. Installation of maven will be as simple as un-zipping the downloaded file into a desired directory. In this example, we will be seeing the usage of various maven plugins and goals that contributes to the entire project life-cycle. Before proceeding with the sample, create an environment variable MAVEN_HOME that points to the Maven installation directory and ensure that the PATH variable contains %MAVEN_HOME/bin.

Creating a project

Execute the following command which is used to create the initial project structure.

 

mvn archetype:create -DgroupId=net.javabeat.emailservice -DartifactId=emailservice

Note that in archetype:createarchetype represents the plugin prefix and create represents the goal. This goalcreates a project with the name emailservice. As soon as this command is executed, one can see a directory called emailservice which has the src folder for holding the main java files, along with java files representing test-cases. The POM file with the name pom.file will also be created with the structure as follows,

pom.xml

<project>
    <modelVersion>4.0.0</modelVersion>

    <groupId>net.javabeat.emailservice</groupId>
    <artifactId>emailservice</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>emailservice</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

Importing the project in Eclipse

This step is optional for those who are not working with Eclipse being the IDE for developing the project. Change the current directory to emailservice and issue the following command. This goal eclipse creates the project metadata files that are complaint with Eclipse. As soon as the following goal is executed there will be two files generated in the current directory which are .project and .classpath. This is for Eclipse to understand so that the newly created project can be imported in Eclipse IDE to work with.

 

mvn eclipse:eclipse

Now, for importing the project into Eclipse, Open Eclipse, go to File -> Import -> Existing Projects into Workspace and navigate to the directory containing the .project and .classpath files and Click OK. Now this project gets imported into Eclipse workspace.

Adding files to project

To make the project meaningful, we will add the following files into the main source folder.

EMail.java

package net.javabeat.emailservice;

public class EMail {

    private String fromAddress;
    private String toAddress;
    private String subject;
    private String message;
    private String status;

    public String getFromAddress() {
        return fromAddress;
    }

    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }

    public String getToAddress() {
        return toAddress;
    }

    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }		
}

The above class represents the Email model object that will be used by EmailService class for sending email. Given below is the code listing for EMailService class.

EMailService.java

package net.javabeat.emailservice;

public class EMailService {

    public EMail sendEmail(String fromAddress, String toAddress, String subject, String message){

        EMail emailObject = new EMail();
        emailObject.setFromAddress(fromAddress);
        emailObject.setToAddress(toAddress);
        emailObject.setSubject(subject);
        emailObject.setMessage(message);
        emailObject.setStatus("SUCCESS");

        System.out.println("Sending email from " + fromAddress + " to " + toAddress + "with subject "
		    + subject + " having the message contents " + message);
        return emailObject;
    }

In this section we will see how to write custom maven plugins. It is possible that the custom maven can be made to run outside the standard life-cycle phase or it can be made to be executed as part of the standard life-cycle phase. We will see how to accomplish both of these items in the following sections.

Creating standalone plugins

In this section, we will write a custom plugin and will see how to write it in stand-alone mode – i.e running the plugin directly without establishing any dependencies on any of the standard life-cycles available in Maven.

Creating the project

The first step is to create the project containing the custom maven plugin. This project is quite different from the regular java project because it is not a regular java artifact like JAR, WAR etc. Instead it is going to be a maven plugin. Issue the following command to create the maven plugin project.

 

mvn archetype:create -DgroupId=net.javabeat.maven -DartifactId=environment-info -DarchetypeArtifactId=maven-archetype-mojo

The above command creates a project with the name environment-info with the standard directory layout containing the source and test resources. If you look into the POM file, the package type will be maven-plugin to indicate that this is a maven plugin project.

Importing the project into Eclipse

This step is optional and this is for someone who wishes to work with the project in Eclipse IDE. Issuing the following with the current directory being environment-info creates the Eclipse .project and .classpath files. Now, open Eclipse and go to File -> Import -> Existing Project into Workspace and specify the directory to <<path to environment-info>> directory.

 

mvn eclipse:eclipse

Creating the plugin

In Maven, the plugin that achieves a specific task is called by the name MOJO (Maven Old Java Object similar to POJO). A MOJO defines the goal which is nothing but the custom action which is executed upon user’s request. In this example, we will see a custom MOJO that will define the goal of storing all the environmental properties in a text file upon execution. Have a look at the following code,

EnvironmentInfoTask.java

package net.javabeat.maven; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Iterator; import java.util.Map; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** * @goal env-info */ public class EnvironmentInfoTask extends AbstractMojo{ /** * @parameter * default-value="log.txt" * expression="${environment.filename}" */ private String fileName; /** * @parameter * default-value="C:\\temp" * expression="${environment.base_dir}" */ private File baseDirectory; /** * @parameter * default-value="true" * expression="${environment.loggingRequired}" */ private boolean loggingRequired; public void execute() throws MojoExecutionException, MojoFailureException { StringBuilder fileContents = new StringBuilder(); if (baseDirectory.exists()){ baseDirectory.mkdirs(); log("Created base directory '" + baseDirectory.getAbsolutePath() + "'"); } Map<String, String> environment = System.getenv(); Iterator<Map.Entry<String, String>> entries = environment.entrySet().iterator(); fileContents.append("Environment Information:" + newLine()); fileContents.append("-----------------------------------------------------------" + newLine()); while (entries.hasNext()){ Map.Entry<String, String> entry = entries.next(); fileContents.append(entry.getKey() + "------------->" + entry.getValue() + newLine()); } fileContents.append("-----------------------------------------------------------" + newLine()); writeToFile(fileContents); log("File contents written"); } private void log(String message){ if (loggingRequired){ System.out.println(message); } } private static String newLine(){ return System.getProperty("line.separator"); } private void writeToFile(StringBuilder fileContents){ FileWriter fWriter = null; BufferedWriter bWriter = null; try{ fWriter = new FileWriter(baseDirectory + File.separator + fileName); bWriter = new BufferedWriter(fWriter); bWriter.write(fileContents.toString()); }catch (Exception e){ log("Error in writing the contents to file ->" + e.getMessage()); }finally{ try{ if (bWriter != null){ bWriter.close(); } if (fWriter != null){ fWriter.close(); } }catch (Exception e){ log("Error in closing the resources ->" + e.getMessage()); } } } }

The first thing to notice is the class EnvironmentInfoTask which is going to persist the environmental information into a file extends AbstractMojo class which in turn extends the Mojo interface. Note that the goal for this MOJO is annotated using XDoclet using goal attribute with the name env-info. The method that will be called during execution of the MOJO is execute(). This method does the job of persisting the environmental properties by taking information from the various properties .

 

  • Base Directory – the directory under which the log file name will be created which is of type ‘java.io.File’. Note that we have used XDoclet ‘parameter’ for annotating this property. This property has the default value ‘C:\\temp’ which means the this is the default location for the log file. However, this value can be overridden at runtime by specifying the property ‘environment.base_dir’ which is an expression and its value will be resolved at runtime
  • Filename – the name of the log file into which the environmental properties will be written. Note that the default value for the log file name is ‘log.txt’. However, during runtime, the value can be overridden through the property ‘environment.filename’
  • Logging Required – whether logging information on what this MOJO is doing has to be shown. The default value being true can be overridden by specifying the value false to the property ‘environment.loggingRequired’.

Compiling the project

Issue the following command for compiling the maven plugin project.

 

mvn compile

Packaging the project

The following command is used to package the plugin project.

 

mvn package

Installing the project

For installing the project into the local Maven repository, issue the following command.

 

mvn install

Usually, on Windows, the local repository is %USER_HOME%/.m2/repository. On Windows XP, USER_HOME will expand to "C:\\Document and Settings\\<<UserName>>", however in Windows Vista it is "C:\\Users\\<<UserName>>".

Running the project

There are several ways to run the maven plugin. We will see them one by one. Generally running a Maven plugin takes the following form,

 

mvn groupId:artifactId:version:goalName

In our case, the group id is net.javabeat.maven, artifact id is environment-info, version is 1.0-SNAPSHOT and goal name is env-info. So running the following command will run the custom plugin

 

mvn net.javabeat.maven:environment-info:1.0-SNAPSHOT:env-info

Running the above command will create a directory C:\\temp (if not present) and create a file name with log.txt with the environment information. Because logging is enabled by default, the text ‘Created base directory C:\temp‘ and ‘File contents are written’ will be displayed in the console.

It is also possible to configure the plugin by passing alternate input values. Have a look at the following command. This command specifies an alternate base directory C:\\temp-new for the log file newLog.txt with logging turned off. Note that for passing a property to a plugin the standard way is –DpropertyName=propertyValue.

 

mvn net.javabeat.maven:environment-info:1.0-SNAPSHOT:env-info -Denvironment.base_dir=C:\temp-new -Denvironment.filename=newLog.txt -Denvironment.loggingRequired=false

It is also possible to omit the version information while running the plugin in which case, Maven tries to find the recent version for the plugin by comparing the version strings. In our case, this wouldn’t happen, because we have only one version which is 1.0-SNAPSHOT. So the following command will also work.

 

mvn net.javabeat.maven:environment-info:env-info

Another approach to run the plugin is by omitting the group id and just specifying the artifact id along with the goal name. However, for this to happen, we have to add the group id to the default list of groups that Maven will look for. Open the file %MAVEN_HOME%/conf/settings.xml and add the following line under the element pluginsGroup.

 

<pluginGroup>net.javabeat.maven</pluginGroup>

This ensures that we have added the group net.javabeat.maven to the list of default groups that Maven will search for, because of which the following command will work.

 

mvn environment-info:env-info

Attaching plugins to existing life-cycle

So far, we have seen how to run a custom plugin in stand-alone mode. This is not of much-use and Maven provides a way for binding the goals of any custom plugin into existing build cycle. For example, let us consider that we have written a custom plugin which will simply print the current date and we want this plugin to be executed during the compilation phase and the installation phase of a project. We will see how to accomplish this goal in this section.

The following listing shows the custom plugin which will simply emit the date information.

DateInfo.java

package net.javabeat.maven; import java.util.Date; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** * @goal date-info */ public class DateInfo extends AbstractMojo { public void execute() throws MojoExecutionException, MojoFailureException { Date currentDate = new Date(); getLog().info("Current date is " + currentDate); } }

Follow the same process of creating the project, then creating the plugin, compilation, packaging and installation as we have discussed before. We will see how to attach this custom plugin during the compile and the install phase. Open POM.xml file and add the following after the project dependencies element,

 

<build> <plugins> <plugin> <groupId>net.javabeat.maven</groupId> <artifactId>environment-info</artifactId> <version>1.0-SNAPSHOT</version> <executions> <execution> <id>date-info-compile</id> <phase>compile</phase> <goals> <goal>date-info</goal> </goals> </execution> <execution> <id>date-info-install</id> <phase>install</phase> <goals> <goal>date-info</goal> </goals> </execution> </executions> </plugin> </plugins> </build>

Though the above XML fragment is big, it is fairly simple. First thing is, it defines the execution element where we can define goals for executions. We have defined two execution elements one for the compile phase and the other for the install phase and we have given appropriate id for each execution element. Have a note at the goals section. We have included our custom goal date-info which will display the current date information. Note that where to search for the goal’s group id and the artifact id along with optional version is defined just above the executions element.

After this whenever we run mvn compile and mvn install for any project that contains the above definition we will see that the goal date-info getting invoked during the phases.

Conclusion

In this article, we have seen how to use Maven for creating projects and to manage dependencies between projects. We have seen Maven simplifying the task of creating, compiling, packaging, installing projects thereby reducing the pain from developers and build managers. Also discussed in the article are the extension capabilities provided by Maven for pluging-in custom plugins in the form of MOJOs.

}

Note that there is no real functionality in the above, all it does is to accept the various user inputs and constructs an email object before returning it.

Compiling the project

The next step is to compile to project, by default the compilation process will create a folder called target and it will place the java class files along with any resource files, if present.

 

mvn compile

Note that the location of the target folder as well as the location of the target folder is also configurable.

Packaging the project

This step will package the project with the packaging type mentioned in POM, which is JAR. Before packaging it will also execute the test cases (if specified) in the test folder and the packaged jar will be placed in the target folder.

 

mvn package

Installing the project

The final step is to install the jar in a local repository so that other projects, if they are dependant on this project can make references to this project. The following command will install (i.e copy the jar) to the local repository.

 

mvn install

Note that, by default, the local repository path will be %USER_HOME%/.m2/repository.

Maven Custom Plug-In (Example Code)

Tagged : / / / / /

Recommended Books for Maven | Good books for Maven learning

maven-books-references

Recommended Books for Maven

http://www.maestrodev.com/wp-content/uploads/2012/03/betterbuildswithmaven-2008.pdf

Tagged : / / / / / / / / / / / / / / /

Maven CLI Options Reference – Command Line | Maven Command Line Cheatsheet

maven-cli-options-reference

Maven CLI Options Reference

Options Description
-am,--also-make If project list is specified, also build projects required by the list
-amd,--also-make-dependents If project list is specified, also build projects that depend on projects on the list
B,–batch-mode Run in non-interactive (batch) mode
-C,--strict-checksums Fail the build if checksums don’t match
-c,--lax-checksums Warn if checksums don’t match
-cpu,--check-plugin-updates Ineffective, only kept for backward compatibility
-D,--define <arg> Define a system property
-e,--errors Produce execution error messages
-emp,--encrypt-master-password <arg> Encrypt master security password
-ep,--encrypt-password <arg> Encrypt server password
-f,--file <arg> Force the use of an alternate POM file (or directory with pom.xml).
-fae,--fail-at-end Only fail the build afterwards; allow all non-impacted builds to continue
-ff,--fail-fast Stop at first failure in reactorized builds
-fn,--fail-never NEVER fail the build, regardless of project result
-gs,--global-settings <arg> Alternate path for the global settings file
-h,--help Display help information
-l,--log-file <arg> Log file to where all build output will go.
-llr,--legacy-local-repository Use Maven 2 Legacy Local Repository behaviour, ie no use of _maven.repositories. Can also be activated by using -Dmaven.legacyLocalRepo=true
-N,--non-recursive Do not recurse into sub-projects
-npr,--no-plugin-registry Ineffective, only kept for backward compatibility
-npu,--no-plugin-updates Ineffective, only kept for backward compatibility
-nsu,--no-snapshot-updates Suppress SNAPSHOT updates
-o,--offline Work offline
-P,--activate-profiles <arg> Comma-delimited list of profiles to activate
-pl,--projects <arg> Comma-delimited list of specified reactor projects to build instead of all projects. A project can be specified by [groupId]:artifactId or by its relative path.
-q,--quiet Quiet output – only show errors
-rf,--resume-from <arg> Resume reactor from specified project
-s,--settings <arg> Alternate path for the user settings file
-T,--threads <arg> Thread count, for instance 2.0C where C is core multiplied
-t,--toolchains <arg> Alternate path for the user toolchains file
-U,--update-snapshots Forces a check for updated releases and snapshots on remote repositories
-up,--update-plugins Ineffective, only kept for backward compatibility
-V,--show-version Display version information WITHOUT stopping build
-v,--version Display version information
-X,--debug Produce execution debug output
Tagged : / / / / / / / / / / / / / / / / / /

Introduction of Maven – Complete Guide

maven-introduction

Contents
What is Maven?
Philosophy of Maven
Benefits of Maven
High Level Features and Benefits of Maven
Download Maven
Installation Instructions
Windows 2000/XP
Unix-based Operating Systems (Linux, Solaris and Mac OS X)
Optional configuration
Settings
Settings Reference
First Maven project?

What is Maven?

Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central piece of information.
At first glance Maven can appear to be many things, but in a nutshell Maven is an attempt to apply patterns to a project’s build infrastructure in order to promote comprehension and productivity by providing a clear path in the use of best practices. Maven is essentially a project management and comprehension tool and as such provides a way to help with managing:

  • Builds
  • Documentation
  • Reporting
  • Dependencies
  • SCMs
  • Releases
  • Distribution

Philosophy of Maven

Maven is generally considered by many to be a build tool. Many people who come to Maven initially are familiar with Ant so it’s a natural association but Maven is not just a build tool, and not just a replacement for Ant. Maven is an entirely different creature from Ant. Ant is simply a toolbox whereas Maven is about the application of patterns in order to achieve an infrastructure which displays the characteristics of visibility, reusability, maintainability, and comprehensibility.
Maven was borne of the very practical desire to make several projects at Apache work in the same way. So that developers could freely move between these projects, knowing clearly how they all worked by understanding how one of them worked. If a developer spent time understanding how one project built it was intended that they would not have to go through this process again when they moved on to the next project. The same idea extends to testing, generating documentation, generating metrics and reports, testing and deploying.

Benefits of Maven

  • Standardized project layout and project structure generator.
  • Standardized dependency-management mechanism.
  • Multiple project support.
  • Instant downloads of new plugins and features as the developer needs them.
  • Website generation for up-to-date project information.
  • Integration with source control: CVS and Subversion.
  • Reusability
  • scalability (lower level of additional info/code to add a new step to the build process)
  • Build lifecycle management
  • Large existing repository
  • Eclipse aware
  • Well documented (hopefully soon)
  • One directory layout,
  • A single way to define dependencies,
  • Setting up a project is really fast,
  • 99% of my needs are available out of the box,
  • build best practices enforcement (shared build meme)
  • automated build of application, from source code to pre-production platform => fast time to market with reduced risks
  • Works well with distributed teams 😉 Location doesn’t matter.
  • All artifacts are versioned and store in a repository
  • Build process is standardized for all projects
  • A lot of goals are available so it isn’t necessary to develop some specific build process part contrary to ANT we can reuse existing ANT tasks in build process with ant run plug-in
  • it provide quality project information with generated site
  • Easy to learn and use
  • Makes the build process much easier at the project level (i.e. don’t have to create very much for each project for Maven to build it correctly, and those things you do create are more declarative than functional)
  • Automatic project web sites with consistent information about each project
  • Recommended standards and best practices for project layout and definition
  • Promotes modular design of code. by making it simple to manage mulitple projects it allows the design to be laid out into multiple logical parts, weaving these parts together through the use of dependency tracking in pom files.
  • Enforces modular design of code
  • Quick project setup, no complicated build.xml files, just a POM and go

 

High Level Features and Benefits of Maven

  • Encourages best practices
  • Provides a uniform build system and consistent usage across all projects
  • Provides dependency management including automatic updating, dependency closures (also known as transitive dependencies)
  • Provides reuse of build logic
  • Defines project standard directory layout
  • Helps to reduce the duplication of dependent software libraries (jars) required to build an application
  • Stores all the software libraries or artifacts in a remote stores called a Maven repositories

Download Maven

Maven is distributed in several formats for your convenience. Maven 2.2.1 is distributed under the Apache License, version 2.0.
Download link: http://maven.apache.org/download.html

Installation Instructions

System Requirements
JDK 1.5 or above (this is to execute Maven – it still allows you to build against 1.3 and prior JDK’s)
Memory No minimum requirement
Disk No minimum requirement. Approximately 100MB will be used for your local repository, however this will vary depending on usage and can be removed and redownloaded at any time.
Operating System No minimum requirement. On Windows, Windows NT and above or Cygwin is required for the startup scripts. Tested on Windows XP, Fedora Core and Mac OS X.
Maven is a Java tool, so you must have Java installed in order to proceed. More precisely, you need a Java Development Kit (JDK), the Java Runtime Environment (JRE) is not sufficient.
Additional optional installation steps are listed after the platform specific instructions.

Windows 2000/XP

  • Unzip the distribution archive, i.e. apache-maven-2.2.1-bin.zip to the directory you wish to install Maven 2.2.1. These instructions assume you chose C:\Program Files\Apache Software Foundation. The subdirectory apache-maven-2.2.1 will be created from the archive.
  • Add the M2_HOME environment variable by opening up the system properties (WinKey + Pause), selecting the “Advanced” tab, and the “Environment Variables” button, then adding the M2_HOME variable in the user variables with the value C:\Program Files\Apache Software Foundation\apache-maven-2.2.1. Be sure to omit any quotation marks around the path even if it contains spaces. Note: For Maven < 2.0.9, also be sure that the M2_HOME doesn’t have a ‘\’ as last character.
  • In the same dialog, add the M2 environment variable in the user variables with the value %M2_HOME%\bin.
  • Optional: In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.
  • In the same dialog, update/create the Path environment variable in the user variables and prepend the value %M2% to add Maven available in the command line.
  • In the same dialog, make sure that JAVA_HOME exists in your user variables or in the system variables and it is set to the location of your JDK, e.g. C:\Program Files\Java\jdk1.5.0_02 and that %JAVA_HOME%\bin is in your Path environment variable.
  • Open a new command prompt (Winkey + R then type cmd) and run mvn –version to verify that it is correctly installed.

Unix-based Operating Systems (Linux, Solaris and Mac OS X)

  • Extract the distribution archive, i.e. apache-maven-2.2.1-bin.tar.gz to the directory you wish to install Maven 2.2.1. These instructions assume you chose /usr/local/apache-maven. The subdirectory apache-maven-2.2.1 will be created from the archive.
  • In a command terminal, add the M2_HOME environment variable, e.g. export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1.
  • Add the M2 environment variable, e.g. export M2=$M2_HOME/bin.
  • Optional: Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS=”-Xms256m -Xmx512m”. This environment variable can be used to supply extra options to Maven.
  • Add M2 environment variable to your path, e.g. export PATH=$M2:$PATH.
  • Make sure that JAVA_HOME is set to the location of your JDK, e.g. export JAVA_HOME=/usr/java/jdk1.5.0_02 and that $JAVA_HOME/bin is in your PATH environment variable.
  • Run mvn –version to verify that it is correctly installed.

 

Optional configuration

Maven will work for most tasks with the above configuration, however if you have any environmental specific configuration outside of individual projects then you will need to configure settings. The following sections refer to what is available.

Settings

Maven has settings file located in the Maven installation and/or user home directory that configure environmental specifics such as:

  • HTTP proxy server
  • repository manager location
  • server authentication and passwords
  • other configuration properties

Settings Reference

The settings element in the settings.xml file contains elements used to define values which configure Maven execution in various ways, like the pom.xml, but 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:

    • The Maven install: $M2_HOME/conf/settings.xml
    • A user’s install: ${user.home}/.m2/settings.xml

Here is an overview of the top elements under settings:

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: This value is the path of this build system’s local repository. The default value is ${user.home}/.m2/repository. This element is especially useful for a main build server allowing all logged-in users to build from a common local 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.home}/.m2/plugin-registry.xml file to manage plugin versions, defaults to false. Note that for the current version of Maven 2.0, the plugin-registry.xml file should not be depended upon. Consider it dormant for now.

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 automatically contains org.apache.maven.plugins and org.codehaus.mojo. For example, given the above settings the Maven command line may execute org.mortbay.jetty:jetty-maven-plugin:run with the truncated command:

Servers
The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

Mirrors
epositories are declared inside a project, which means that if you have your own custom repositories, those sharing your project easily get the right settings out of the box. However, you may want to use an alternative mirror for a particular repository without changing the project files.

Some reasons to use a mirror are:

There is a synchronized mirror on the internet that is geographically closer and faster
You want to replace a particular repository with your own internal repository which you have greater control over
You want to run maven-proxy to provide a local cache to a mirror and need to use its URL instead

Proxies: This is basically used for proxies’ setup

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 concerns 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 equivalently ID’d profiles in a POM or profiles.xml file.

First Maven project?

To create our first Maven project we are going to use Maven’s archetype mechanism. An archetype is defined as an original pattern or model from which all other things of the same kind are made. In Maven, an archetype is a template of a project which is combined with some user input to produce a working Maven project that has been tailored to the user’s requirements.

On to creating your first project! In order to create the simplest of Maven projects, execute the following from the command line:

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.mycompany.app -DartifactId=my-app

Once you have executed this command, you will notice a few things have happened. First, you will notice that a directory named my-app has been created for the new project, and this directory contains a file named pom.xml that should look like this:

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.mycompany.app
my-app
jar 1.0-SNAPSHOT
Maven Quick Start Archetype
http://maven.apache.org

junit
junit
3.8.1
test

pom.xml contains the Project Object Model (POM) for this project. The POM is the basic unit of work in Maven. This is important to remember because Maven is inherently project-centric in that everything revolves around the notion of a project. In short, the POM contains every important piece of information about your project and is essentially one-stop-shopping for finding anything related to your project.

This is a very simple POM but still displays the key elements every POM contains, so let’s walk through each of them to familiarize you with the POM essentials:

project: This is the top-level element in all Maven pom.xml files.
modelVersion: This element indicates what version of the object model this POM is using. The version of the model itself changes very infrequently but it is mandatory in order to ensure stability of use if and when the Maven developers deem it necessary to change the model.

groupId: This element indicates the unique identifier of the organization or group that created the project. The groupId is one of the key identifiers of a project and is typically based on the fully qualified domain name of your organization. For example org.apache.maven.plugins is the designated groupId for all Maven plug-ins.

artifactId: This element indicates the unique base name of the primary artifact being generated by this project. The primary artifact for a project is typically a JAR file. Secondary artifacts like source bundles also use the artifactId as part of their final name. A typical artifact produced by Maven would have the form -. (for example, myapp-1.0.jar).

packaging: This element indicates the package type to be used by this artifact (e.g. JAR, WAR, EAR, etc.). This not only means if the artifact produced is JAR, WAR, or EAR but can also indicate a specific lifecycle to use as part of the build process. (The lifecycle is a topic we will deal with further on in the guide. For now, just keep in mind that the indicated packaging of a project can play a part in customizing the build lifecycle.) The default value for the packaging element is JAR so you do not have to specify this for most projects.

version: This element indicates the version of the artifact generated by the project. Maven goes a long way to help you with version management and you will often see the SNAPSHOT designator in a version, which indicates that a project is in a state of development. We will discuss the use of snapshots and how they work further on in this guide.

name: This element indicates the display name used for the project. This is often used in Maven’s generated documentation.

url: This element indicates where the project’s site can be found. This is often used in Maven’s generated documentation.

description: This element provides a basic description of your project. This is often used in Maven’s generated documentation.

 

Tagged : / / / / / / / / / / / / / /

EC2Deploy and the Cloud Tools Maven plugin are now available

ec2deploy-cloud-tools-maven-plugin

I’m pleased to announce that EC2Deploy – a Groovy-based framework for deploying Java EE applications to Amazon EC2 – is now available as part of the Cloud Tools open source project.

There are three main parts to Cloud Tools:

  • The EC2Deploy framework
  • Amazon Machine Images (AMIs) that are configured to run Tomcat and work with EC2Deploy
  • A Maven plugin that uses EC2Deploy to deploy a web application to EC2

I’m especially excited about the Maven plugin. Once you have configured the plugin for your web application you can use the following goals:

  • cloudtools:deploy – launch the EC2 instances and deploy the web application
  • cloudtools:redeploy – redeploy the web application (upload the changes and restart tomcat)
  • cloudtools:jmeter – run a Jmeter test
  • cloudtools:stop – stop the EC2 instances

Cloudtools is still work in progress but it let’s you deploy a web application on EC2 in just a few minutes.  To learn more go to Cloud Tools.

Tagged : / / / / / / / / / / / /