Apache Maven 3 Cookbook

By Srirangan
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Basics of Apache Maven

About this book

Apache Maven is more than just build automation. When positioned at the very heart of your development strategy, Apache Maven can become a force multiplier not just for individual developers but for agile teams and managers. This book covers implementation of Apache Maven with popular enterprise technologies/frameworks and introduces agile collaboration techniques and software engineering best practices integrated with Apache Maven.

The Apache 3 Maven Cookbook is a real-world collection of step-by-step solutions for individual programmers, teams, and managers to explore and implement Apache Maven and the engineering benefits it brings into their development processes.

This book helps with the basics of Apache Maven and with using it to implement software engineering best practices and agile team collaboration techniques. It covers a broad range of emergent and enterprise technologies in the context of Apache Maven, and concludes with recipes on extending Apache Maven with custom plugins.

We look at specific technology implementations through Apache Maven including Java Web Applications, Enterprise Java Frameworks, Cloud Computing, Mobile / Device development, and more. We also look at Maven integration with popular IDEs including Eclipse, NetBeans, and IntelliJIDEA.

The book is rounded off by exploring extending the Apache Maven platform by building custom plugins, integrating them with existing projects, and executing them through explicit command-line calls or with Maven Build Phases.

Publication date:
August 2011
Publisher
Packt
Pages
224
ISBN
9781849512442

 

Chapter 1. Basics of Apache Maven

In this chapter, we will cover:

  • Setting up Apache Maven on Windows

  • Setting up Apache Maven on Linux

  • Setting up Apache Maven on Mac

  • Verifying the Apache Maven installation

  • Creating a new project

  • Compiling and testing a project

  • Understanding the Project Object Model

  • Understanding the build lifecycle

  • Understanding build profiles

Apache Maven originated as an attempt to simplify the build process for the now defunct Apache Jakarta Alexandria project. Its formative years were then spent in the Apache Turbine project where it eventually came to replace a brittle and fragile build system based on Apache ANT.

Given Maven’s tremendous potency and effectiveness in solving a majority of our day-to-day challenges, it has become hugely popular and is now widely used not only by developers but by other roles in a team including scrum masters, product owners, and project managers.

In recent years, Maven has clearly emerged as an important force-multiplier for Agile teams and organizations.

On its official website, http://maven.apache.org, Apache Maven’s objectives are listed as:

  • Making the build process easy

  • Providing a uniform build system

  • Providing quality project information

  • Providing guidelines for best practices in development

  • Allowing transparent migration to new features

Whatever the reasons that made you choose Maven (be it build automation, dependency management, standardization, testability, lifecycle management, continuous integration, or any other industry best practice), the recipes in this book will get you up and running in the shortest time possible.

In the upcoming recipes, we will set up Maven on various platforms and host environments followed by selectively exploring the core concepts of the Project Object Model and the Maven build lifecycle.

 

Setting up Apache Maven on Windows


We will look at installing and setting up Apache Maven on the Windows operating system. Maven is a command-line tool and needs to be integrated with the Windows environment variables. The process is quite simple and Java dependent.

There is a chance Apache Maven may have been pre-installed on your machine. Verify that Maven isn’t already installed before proceeding.

Note

See the recipe Verifying the Maven installation in this chapter

Getting ready

As mentioned, a prerequisite for working with Maven is the availability of the Java Development Kit. Make sure that the JDK is available before proceeding. This can be verified by running the following command line:

Java -version

It will give the following output:

java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b06)
Java HotSpot(TM) Client VM (build 17.0-b16, mixed mode, sharing)

If you do not have JDK installed, you can download it at http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Got JDK? Next you need to get your hands on Maven. You can download it from:

http://maven.apache.org/download.html

After downloading Maven, extract the archive into any folder. For Windows, it is advised that the path doesn’t contain any white-space characters. I extracted Maven in the D drive.

D:\apache-maven-3.0.2\

How to do it...

To start using Maven, we need to configure Windows environment variables. The M2_HOME variable needs to be set and the PATH variable needs to be modified to include the Maven binaries folder.

You can set the environment variables by accessing the System settings in the Control Panel.

Select Environment Variables and then the New button to create a new environment variable.

Create a new environment variable for M2_HOME pointing to the Maven base directory. For me, the value of M2_HOME will be D:\apache-maven-3.0.2\.

The PATH environment variable will already exist. Select it and click Edit to modify. It must be modified by appending the following text at the end:

;%M2_HOME%\bin

Apache Maven is now ready and available for use in the command line. It is also available for integration with IDEs and other development tools, but more on that in upcoming chapters.

See also

  • Setting up Apache Maven on Linux in this chapter

  • Setting up Apache Maven on Mac in this chapter

  • Verifying your Apache Maven installation in this chapter

  • Working with Eclipse and Maven in Chapter 8, IDE Integration

  • Working with NetBeans and Maven in Chapter 8, IDE Integration

  • Working with IntelliJ and Maven in Chapter 8, IDE Integration

 

Setting up Apache Maven on Linux


The Linux distribution used in this book is Ubuntu 10.04. If you use any other Linux distribution, the steps should nevertheless remain similar. Apache Maven is a command-line tool; it just needs to be extracted and configured with the operating system’s environment.

There is a chance Apache Maven may have been pre-installed on your machine. Verify that Maven isn’t already installed before proceeding.

Note

See the recipe Verifying the Maven installation in this chapter

Getting ready

A prerequisite for working with Maven is the availability of the Java Development Kit. Make sure the JDK is available before proceeding. This can be verified by running the command line:

java -version

It should give the following output:

java version "1.6.0_18"
OpenJDK Runtime Environment (IcedTea6 1.8.1) (6b18-1.8.1-0ubuntu1)
OpenJDK Client VM (build 16.0-b13, mixed mode, sharing)

If you do not have JDK installed, you can download it at: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Got JDK? Next you need to get your hands on Maven. You can download it from: http://maven.apache.org/download.html.

After downloading Maven, extract the archive into a folder. For example, I extracted Maven into my home folder, /home/srirangan/apache-maven-3.0.2/. This will be an installation for a single user.

How to do it...

The next step is to add commands for exporting the PATH and M2_HOME environment variables in the .bashrc file. This file can be found in the user’s home folder, which for me is /home/srirangan/.bashrc.

export M2_HOME=/home/srirangan/apache-maven-3.0.2
export PATH=${PATH}:${M2_HOME}/bin

Apache Maven is now ready and available for use in the command line. It is also available for integration with IDEs and other development tools, but more on that in upcoming chapters.

See also

  • Setting up Apache Maven on Windows in this chapter

  • Setting up Apache Maven on Mac in this chapter

  • Verifying your Apache Maven installation in this chapter

  • Working with Eclipse and Maven in Chapter 8, IDE Integration

  • Working with NetBeans and Maven in Chapter 8, IDE Integration

  • Working with IntelliJ and Maven in Chapter 8, IDE Integration

 

Setting up Apache Maven on Mac


Installing Maven on the Mac OS X isn’t very different from the installation and setup on Linux. This really shouldn’t be a surprise because OS X is built on top of BSD Linux in the first place. Apache Maven is a command-line tool; it just needs to be extracted and configured with the operating system’s environment.

There is a chance Apache Maven may have been pre-installed on your machine. Verify that Maven isn’t already installed before proceeding.

Note

See the recipe Verifying the Maven installation in this chapter

Getting ready

A pre-requisite for working with Maven is the availability of the Java Development Kit. Make sure the JDK is available before proceeding. This can be verified by running the following command line:

java -version

It should give the following output:

java version "1.5.0_19"Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_19-b02-306)Java HotSpot(TM) Client VM (build 1.5.0_19-138, mixed mode, sharing)

If you do not have JDK installed, you can download it at:

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Got JDK? Next you need to get your hands on Maven. You can download it from:

http://maven.apache.org/download.html

After download, extract the archive into a folder. For example, you can extract the archive in /usr/local/maven/. This can, of course, be any directory of your choice and not /usr/local/maven in particular.

How to do it...

The next step is to add commands to export the PATH and M2_HOME environment variables in the .bash_login file.

export M2_HOME=/usr/local/maven
export PATH=${PATH}:${M2_HOME}/bin

Apache Maven is now ready and available for use in the command line. It is also available for integration with IDEs and other development tools, but more on that in upcoming chapters.

See also

  • Setting up Apache Maven on Windows in this chapter

  • Setting up Apache Maven on Linux in this chapter

  • Verifying your Apache Maven installation in this chapter

  • Working with Eclipse and Maven in Chapter 8, IDE Integration

  • Working with NetBeans and Maven in Chapter 8, IDE Integration

  • Working with IntelliJ and Maven in Chapter 8, IDE Integration

 

Verifying the Apache Maven installation


Did you just try and install Apache Maven? It’s time to verify it. Alternatively, your operating system may have Apache Maven pre-installed.

Whether user installed or pre-installed, here’s how to verify that your workstation has Apache Maven extracted and the operating system configured correctly.

How to do it...

  • You have installed Maven on your system, or so you think? Before you start using it, the setup and availability of Maven needs to be verified. This is done by executing the following command line:

    mvn -version
    
  • If Maven has been correctly installed, you will see something resembling the following output:

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

    If the output you get is similar, then you know Maven is available and ready to be used.

  • If your operating system cannot find the mvn command, make sure that your PATH environment variable and M2_HOME environment variable have been properly set.

See also

  • Creating a new project in this chapter

 

Creating a new project


All done with downloads, setups, configurations, installations, and verifications? Great! Let’s get down to business. If not, refer to the first few recipes of this chapter.

In this recipe, we will create our first Apache Maven project. To be more specific, we will use the Maven archetype:generate goal to generate our first Maven Java project.

Then we take a look at the Maven project structure to get an idea of what constitutes a Maven project and what goes where by convention.

How to do it...

  • Start the command-line terminal and run the following command:

    $ mvn archetype:generate
    
  • If this is the first time you are running this command, you will see that downloads are taking place in the command line.

  • Then you will see a rather large list of archetypes, each having a number, a name, and a short description explaining what they are. We’ll look at what archetypes are a little later. For now, select the default archetype. Here we have considered that it is archetype number 101 named maven-archetype-quickstart.

    [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
    Choose archetype:
    1: remote -> docbkx-quickstart-archetype (-)
    ….
    100: remote -> maven-archetype-profiles (-)
    101: remote -> maven-archetype-quickstart (An archetype which contains a sample Maven project.)
    …
    375: remote -> javg-minima
    Choose a number: 101:
  • You will be asked to select a version of the archetype. The default is the latest stable version of the archetype; let’s choose that.

  • Next, you will have to enter the Maven "project co-ordinates" such as groupId, artifactId, version, and package.

    GroupId co-ordinates are used to specify the hierarchical location of a project within a Maven repository. In this case, the repository is the local Maven repository present in your filesystem. GroupId co-ordinates are typically the root package and thus can be shared by multiple projects within an organization.

    The artifactId is an identifier for your project and version here refers to the project version. Packages refer to the reverse dns root package name that is commonly used in Java and a host of other programming languages. artifactID identifiers will be used when artifacts are deployed in repositories and used as dependencies for other projects; more on that later, as it’s not important right now.

  • Upon completion you should see the following:

    [INFO] -------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] -------------------------------------------

How it works...

We just asked Maven, actually a Maven plugin, to create or rather generate a new project for us. A new project for Apache Maven can either be "hand-crafted" with manual pom.xml and folder creations or generated through Maven project archetypes.

So what exactly has Maven created for us? Simple answer—the following:

|-- pom.xml
`-- src
    |-- main
    |   `-- java
    |       `-- net
    |           `-- srirangan,oackt
    |               `-- maven
    |                   `-- App.java
    `-- test
        `-- java
            `-- net
                `-- srirangan,oackt
                    `-- maven
                        `-- AppTest.java

11 directories, 3 files

It created a folder for the project which contains the main pom.xml file and the source folder which contains subfolders for the application and test sources. These then contain the complete package structure and a sample application with a unit test case.

 

Compiling and testing a project


Let’s hope that you’ve read the previous recipe titled Creating a new project or that you have a Maven project available because now we’re entering the interesting part; compiling and testing the project using Maven.

If you’re new to Apache Maven, which is probably why you have this book in your hands, this will be your first introduction to the Apache Maven build lifecycle.

Getting ready

  • Start your command-line terminal window

  • Navigate to the project folder that contains the pom.xml file

  • Run the following command:

    mvn compile
    

How to do it...

Now Apache Maven begins to download dependencies, if they aren’t available in your local repository, and then proceeds to compile the project.

[INFO] -------------------------------------------
[INFO] BUILD SUCCESS
[INFO] -------------------------------------------

If the terminal shows BUILD SUCCESS, it means Maven has finished compilation and build of the application.

Test Driven Development (TDD) is a popular practice that is advocated for and followed religiously by some of the very best software craftsmen in the industry. Maven, having recognized this, makes testing part of the default build lifecycle. This makes TDD easier for teams who are trying to implement it in their development process.

When the default conventions are being used in a Maven project, they have the src/test directory that contains all the tests for the code. Run the following command to run the tests:

    mvn test

This command triggers Maven to run the tests present in the .../src/test folder. When this is completed, you’ll see a brief report echoed on the terminal.

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running net.srirangan.packt.maven.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.037 sec

Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

How it works...

Run the following command:

    $ mvn compile 

It will trigger the Java compiler associated with the project. By default, it is set to JDK1.5, but the project pom.xml can be modified to use other versions.

The compiled code is placed in the "target" directory. The target directory will contain the compiled artifact (that is, a JAR file for a Java project by default) along with directories for compiled classes and tests. It will further contain the pom.properties file along with test reports and temporary files.

├───TestSimpleApp-1.0-SNAPSHOT.jar
├───classes
│   └───net
│       └───srirangan
│           └───packt
│               └───maven
│                   └───App.class
├───maven-archiver
│   └───pom.properties
├───surefire
│   └─── ...temp files...
├───surefire-reports
│   └───net.srirangan.packt.maven.AppTest.txt
│   └───TEST-net.srirangan.packt.maven.AppTest.xml
└───test-classes
    └───net
        └───srirangan
            └───packt
                └───maven
│                   └───AppTest.class

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

See also

  • Understanding the Project Object Model in this chapter

  • Understanding the build lifecycle in this chapter

  • Understanding build profiles in this chapter

 

Understanding the Project Object Model


Every Apache Maven project contains a pom.xml file. The pom.xml file is the XML representation of the project and thus contains all metadata pertaining to the project.

This includes project configuration, defect tracking system details, project organization and licenses, project paths, dependencies, and so on.

The structure of a typical Apache Maven Project POM file is described as follows:

<project … >
  <modelVersion>4.0.0</modelVersion>

  <!-- The Basics -->
  <groupId>...</groupId>
  <artifactId>...</artifactId>
  <version>...</version>
  <packaging>...</packaging>
  <dependencies>...</dependencies>
  <parent>...</parent>
  <dependencyManagement>...</dependencyManagement>
  <modules>...</modules>
  <properties>...</properties>

  <!-- Build Settings -->
  <build>...</build>
  <reporting>...</reporting>

  <!-- Project Meta Data -->
  <name>...</name>
  <description>...</description>
  <url>...</url>
  <inceptionYear>...</inceptionYear>
  <licenses>...</licenses>
  <organization>...</organization>
  <developers>...</developers>
  <contributors>...</contributors>

  <!-- Environment -->
  <issueManagement>...</issueManagement>
  <ciManagement>...</ciManagement>
  <mailingLists>...</mailingLists>
  <scm>...</scm>
  <prerequisites>...</prerequisites>
  <repositories>...</repositories>
  <pluginRepositories>...</pluginRepositories>
  <distributionManagement>...</distributionManagement>
  <profiles>...</profiles>
</project>

Project co-ordinates are the minimal basic fields that a POM definition must contain. The three co-ordinate fields are groupId, artifactId, and version.

These three fields mark a specific location within the repository, hence the term co-ordinates.

The previously displayed sample POM contains four major sections. They are explained as follows:

  • The basics: This section contains project co-ordinates, dependency management, and inheritance details. Additionally, it also contains modules and project level properties.

  • Build settings: This section contains the build details.

  • Project metadata: This section contains project-specific details such as name, organization, developers, URL, inception year, and so on.

  • Environment: This section contains all information regarding the environment including details of the version control being, issue management, continuous integration, mailing lists, repositories, and so on.

See also

  • Understanding the build lifecycle in this chapter

  • Understanding build profiles in this chapter

 

Understanding the build lifecycle


The build lifecycle explicitly defines the process of building, testing, distributing an artifact, and is at the heart of every Maven project.

There are three inbuilt build lifecycles: default, clean, and site.

Default lifecycle

The default lifecycle handles the project compilation, test, and deployment. While it contains over 20 build phases, the following are the most important phases:

  • Validate: validates that all project information is available and is correct

  • Compile: compiles the source code

  • Test: runs unit tests within a suitable framework

  • Package: packages the compiled code in its distribution format

  • Integration-test: processes the package in the integration-test environment

  • Verify: runs checks to verify that the package is valid

  • Install: installs the package in the local repository

  • Deploy: installs the final package in a remote repository

Whenever you execute a build phase, all prior build phases are executed sequentially. Hence, executing mvn integration-test will execute the validate, compile, test, and package build phases before executing the integration-test build phase.

Clean lifecycle

The clean lifecycle handles the project cleaning and contains the following build phases:

  • Pre-clean: executes processes required before project cleaning

  • Clean: removes all files generated by previous builds

  • Post-clean: executes processes required to finalize project cleaning

Site lifecycle

The site lifecycle handles the generation and deployment of the project’s site documentation:

  • Pre-site: executes processes required before generation of the site

  • Site: generates the project’s site documentation

  • Post-site: executes processes required to finalize the site generation and prepares the site for deployment

  • Site-deploy: deploys the site documentation to the specified web server

See also

  • Understanding the Project Object Model in this chapter

  • Understanding build profiles in this chapter

 

Understanding build profiles


Projects in Maven are generally portable. This is done by allowing configuration within the POM, avoiding all filesystem references, and depending extensively on the local repository to store the required metadata.

However, this isn’t always possible as under some circumstances configuration with filesystem references become unavoidable. For these cases, Maven introduces the concept of build profiles.

Build profiles are specifications made in the POM and can be triggered as and when required. Some ways to trigger profiles are:

  • Explicit command-line trigger

  • Maven settings trigger

  • Environment specific trigger

Explicit command-line trigger

Profiles can be directly triggered through the command line using the -P option. The list of profiles, separated by commas, that are to be activated should be mentioned after the -P flag:

mvn install -P profile-1,profile-2

In this case, only the profiles explicitly mentioned in the command will be activated and all other profiles stay dormant for this build.

The reverse is possible as well. You can explicitly specify which profiles should not be activated through the command line:

mvn install -P !profile-1,!profile-2

Maven settings trigger

Maven settings can also directly activate profiles if they are specified in the <activeProfiles> section of the settings file.

<settings>
  ...
  <activeProfiles>
    <activeProfile>profile-1</activeProfile>
    <activeProfile>profile-2</activeProfile>
  </activeProfiles>
  ...
</settings>

Profiles listed in the Maven settings get activated by default every time and they don’t need any explicit specification in the command line.

Environment specific trigger

Profiles can also be triggered based on the current build environment. The environment in which the profile is to be activated is directly defined within the POM profile declarations.

<profiles>
  <profile>
    <activation>
      <property>
        <name>environment</name>
        <value>dev</value>
      </property>
    </activation>
  </profile>
</profiles>

In the code just written, the profile is only activated in the dev build environment. A template of a typical Apache Maven command, wherein the environment is specified explicitly in the command, is given as follows:

mvn groupId:artifactId:goal -Denvironment=dev

See also

  • Understanding the Project Object Model in this chapter

  • Understanding the build lifecycle in this chapter

About the Author

  • Srirangan

    Srirangan is a passionate programmer with three years of freelance and five years of industry experience. He has been involved with projects in a wide array of technologies including Google App Engine, Python, Java, Adobe Flex, and PHP. He brings a unique approach to problem solving, design, and architecture with a focus on simplicity and effectiveness. Supplemented with a keen understanding of business, he brings an added perspective to his work. He specializes in the Defense, Aerospace, and Strategic sectors and has a never-ending passion for product innovation and development. He is a speaker at various technology events and is a keen follower of industry and technology.

    Browse publications by this author
Apache Maven 3 Cookbook
Unlock this book and the full library for FREE
Start free trial