Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Apache Maven Cookbook
Apache Maven Cookbook

Apache Maven Cookbook: Over 90 hands-on recipes to successfully build and automate development life cycle tasks following Maven conventions and best practices

eBook
$9.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Apache Maven Cookbook

Chapter 1. Getting Started

In this chapter, we will cover the basic tasks related to getting started with Apache Maven:

  • Installing Maven on Microsoft Windows
  • Installing Maven on Mac OS X
  • Installing Maven on Linux
  • Changing the JDK used by Maven
  • Creating a simple project with Maven
  • Building a simple project with Maven
  • Changing the location of the Maven repository
  • Running Maven behind an HTTP proxy server
  • Understanding the standard directory layout

Introduction

Apache Maven is a popular tool for build automation, primarily Java projects. Maven addresses two aspects of building software. First, it describes how a software is built and, second, it describes its dependencies. It uses conventions for the build procedure. An XML file describes the software project being built, its dependencies on other external modules and components, the build order, directories, and required plugins. It comes with predefined targets to perform certain well-defined tasks, such as code compilation and its packaging. Maven dynamically downloads Java libraries and Maven plugins from one or more repositories, such as the Maven Central Repository, and stores them locally.

Ever since Maven 1.0 was released in 2004, it has gained popularity and is today the build tool for a large number of open source and commercial projects.

If you are reading this book, then you are not here to understand why Maven is required. You are here to explore Maven and unleash the potential that it offers. The objective of this book is to make the reader aware of Maven's various features, which include installation, configuration, and simple to complex usage by means of examples, illustrations, and working projects.

A brief comparison with other build automation tools

Let's briefly discuss some build automation tools:

  • Make: If you are from the C programming world, chances are you have used Make. Makefiles are not platform-independent. They are not natively compatible with Windows. Thus, they are unsuited to build Java projects.
  • Ant: This is modeled after Make and has targets and dependencies. Each target has a set of tasks. Ant doesn't have any conventions. It is procedural and does not have the concept of a build lifecycle. Maven has conventions, is declarative, and has a lifecycle.

In this chapter, we will cover the basics of Maven—installing the software, verifying the installation, and creating, implementing, and building a simple Java project. We will also cover a few advanced items, such as changing the location of the repository or running Maven behind an HTTP proxy server as it could be relevant to those who have issues with the way Maven works by default.

Let us start by setting up Maven. We will cover how to do this on the three popular operating systems, namely Microsoft Windows, Mac OS X, and Linux.

Installing Maven on Microsoft Windows

At the time of writing this book, Microsoft Windows 8.1 is the latest version of Microsoft Windows. While the screenshots and output will be for Microsoft Windows 8.1, the steps are similar for earlier (and possibly later) versions as well.

Getting ready

As Maven requires a Java platform, first ensure that you have installed the Java environment on your system, Java Development Kit (JDK) specifically; Java Runtime Environment (JRE) is not sufficient.

You can verify whether Java is installed on your system by opening Add or Remove Programs. If you see something similar to the following screenshot, JDK is installed on your system:

Getting ready

You can also verify the program folder structure from Microsoft Windows Explorer:

Getting ready

How to do it...

Let's start installing Java and Maven by performing the following steps:

  1. Set the variable JAVA_HOME to point to the Java installation that you want Maven to use; for example, you can do this by setting JAVA_HOME variable in the following way:
    C:\projects\apache_maven_cookbook>set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_20
    

    Note

    Note that this setting will not be persisted once the command prompt is closed. To persist this, set Environment Variables... using the Control Panel option, as described later for the M2_HOME variable.

  2. If JDK is not installed on your system, now is the time to download and install it from the Oracle Java SE download page at http://www.oracle.com/technetwork/java/javase/downloads/index.html.

    Once it is installed, ensure JAVA_HOME is set as described earlier.

    Now that we have set up Java, let us download and set up Maven.

  3. Go to http://maven.apache.org/ and click on the Download link.
  4. The links to the latest stable versions of Maven are displayed.
  5. The binaries are available in both, .zip and .tar.gz formats. Choose one of them.
  6. Extract the downloaded binary to a folder you want Maven to reside in. In this case I have chosen C:\software.

    Tip

    It is best to avoid folders with spaces as some features of Maven or its plugins might not work.

  7. Ensure the contents are similar to the following screenshot:
    How to do it...

The preceding screenshot displays a list of directories contained in Maven.

Now let's briefly discuss what these directories contain:

  • The bin folder contains the batch files and shell scripts to run Maven on various platforms.
  • The boot folder contains the jars required for Maven to start.
  • The conf folder contains the default settings.xml file used by Maven.
  • The lib folder contains the libraries used by Maven. It also contains an ext folder in which third-party extensions, which can extend or override the default Maven implementation, can be placed.

Now let us make sure we can run Maven from the command prompt by carrying out the following steps:

  1. Open Control Panel:
    How to do it...
  2. Choose Advanced system settings:
    How to do it...
  3. Click on Environment Variables.... Add the M2_HOME variable and set it to the folder where Maven was extracted.
    How to do it...
  4. Edit the PATH variable to include Maven's bin folder:
    How to do it...

How it works...

A Maven installation is essentially a set of JAR files, configuration files, and a Microsoft Windows batch file, mvn.bat.

The mvn command essentially runs this batch file. It first checks for JAVA_HOME. This file is present in the bin folder of the Maven installation and, hence, it needs to be in PATH.

If the batch file does not find JAVA_HOME, it looks for Java in its PATH. This can lead to unexpected results, as typically the Java in PATH is usually the JRE and not the JDK.

The batch file then looks for M2_HOME, which is the location of the Maven installation. It does this so that it can load the libraries that are present.

Additionally, it also reads values specified in MAVEN_OPTS. This variable allows you to run Maven with an additional heap size and other Java parameters.

Using the values for JAVA_HOME, M2_HOME, and Maven_OPTS, the batch file runs its main class org.codehaus.plexus.classworlds.launcher.Launcher.

There's more...

Verify your Maven installation using the following steps:

  1. Open a command prompt in Microsoft Windows and run the following command:
    C:\software\apache-maven-cookbook>mvn -version
    
  2. The following output should be displayed:
    Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T22:59:23+05:30)
    Maven home: C:\software\apache-maven-3.2.5
    Java version: 1.7.0_67, vendor: Oracle Corporation
    Java home: C:\Program Files\Java\jdk1.7.0_67\jre
    Default locale: en_IN, platform encoding: Cp1252
    OS name: "windows 8.1", version: "6.3", arch: "amd64", family: "windows"
    

See also

  • The Creating a simple project with Maven recipe in this chapter

Installing Maven on Mac OS X

Let us look at the steps to install Maven on Mac OS X. This applies to the latest version of Mac OS X, namely Yosemite.

Earlier, Apple provided Java for Mac, but stopped doing so from Java 7 onwards. Apple Java is not available on recent versions of Mac OS X.

Getting ready

Let us check if the Java environment is available on your Mac:

  1. Open the terminal and run the following command:
    /usr/libexec/java_home -v 1.7
    
  2. See if you get an output similar to the following:
    /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home
    
  3. Run the following command to check if you have Java 8:
    /usr/libexec/java_home -v 1.8
    
  4. This should give the following output if Java exists:
    /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home

    As you can see, my system has both Java 1.7 and 1.8.

  5. Set JAVA_HOME to the desired JDK. This can be done in two ways, depending on what you desire:

    If this is for the duration of the session, run the following command:

    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home
    

    If this is permanent, add the preceding line in .bash_profile in your HOME folder

Tip

Ensure you have the JDK installation and not JRE.

If Java is not present, download and install Java from the Oracle Java download page at http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Once installed, verify the Java installation by following the preceding steps.

Now, let us set up Maven on Mac OS X.

How to do it...

Let's download Maven from its official website by performing the following steps:

  1. Go to http://maven.apache.org/ and click on the Download link. Links to the latest stable versions of Maven will be displayed.
  2. The binaries are available in both .zip and .tar.gz formats. Choose one of them.
  3. Extract the downloaded binary to the folder you want Maven to reside in. The typical location for the Mac is /usr/local folder.
  4. You will need a super user (su) or administrator access to place the contents in the /usr/local folder. If you do not have access, you can place the contents in a subfolder of your HOME folder.
  5. Ensure the contents are similar to the following output by executing the following command:
    /usr/local/apache-maven-3.2.5$ ls -l
    

    The output is shown as:

    total 27
    -rw-r--r--    1 root    wheel    17464 Aug 12 02:29 LICENSE
    -rw-r--r--    1 root    wheel      182 Aug 12 02:29 NOTICE
    -rw-r--r--    1 root    wheel     2508 Aug 12 02:26 README.txt
    drwxr-xr-x    8 root    wheel     4096 Aug 19 13:41 bin
    drwxr-xr-x    3 root    wheel        0 Aug 19 13:41 boot
    drwxr-xr-x    4 root    wheel        0 Oct 14 17:39 conf
    drwxr-xr-x   67 root    wheel    28672 Aug 19 13:41 lib
    
  6. Set the M2_HOME variable as follows:
    export M2_HOME=/usr/local/apache-maven-3.2.5
    
  7. Update the PATH to include Maven's bin folder:
    export PATH=$PATH:$M2_HOME/bin
    

Tip

Like JAVA_HOME, the preceding settings can be persisted by updating .bash_profile with the preceding lines.

In the preceding steps, we discussed the steps to download Maven from its official website. We will now discuss installing Maven using brew. Brew is a popular application on Mac OS X to install open source software. If you have brew installed on your Mac OS X, run the following command to install Maven:

brew install maven

The output for the preceding command will be displayed as shown in the following screenshot:

How to do it...

How it works...

The Maven installation is essentially a set of JAR files, configuration files, and a Mac OS X shell script, namely mvn.

The mvn command essentially runs this script. It first checks for JAVA_HOME. This file is present in the bin folder of the Maven installation and, hence, it needs to be in PATH.

If the shell script does not find JAVA_HOME, it looks for Java in its PATH. This can lead to unexpected results, as typically the Java in PATH is usually the JRE installation and not JDK.

The shell script then looks for M2_HOME, which is the location for the Maven installation. It does this so that it can load the libraries that are present.

Additionally, it also reads values specified in MAVEN_OPTS. This variable allows you to run Maven with an additional heap size and other Java parameters.

Using the values for JAVA_HOME, M2_HOME, and MAVEN_OPTS, the shell script runs its main class org.codehaus.plexus.classworlds.launcher.Launcher.

There's more...

Verify your Maven installation using the following steps:

  1. Open a command prompt and run the following command:
    mvn –version
    
  2. The output for the preceding command should be displayed as shown in the following screenshot:
    There's more...

See also

  • The Creating a simple project with Maven recipe in this chapter

Installing Maven on Linux

Let us look at the steps to install Maven on Linux.

While there are many flavors of Linux (Ubuntu, Fedora, RHEL, SUSE, CentOS, and so on), the steps to set up Maven are similar.

Getting ready

Maven needs Java, specifically the Java Development Kit (JDK). Using the following steps, let us check if it is installed in your Linux system, which is a bit tricky:

  1. Open a terminal and run the following command:
    java -version
    
  2. See if you get an output similar to the following:
    java version "1.7.0_65"
    OpenJDK Runtime Environment (rhel-2.5.1.2.el6_5-x86_64 u65-b17)
    

    The preceding output will still not tell you where your Java is installed, which is required to set JAVA_HOME. You can get this information by performing the next set of steps.

  3. Check if javac works; it does only if JDK is installed, not JRE:
    $ javac -version
    

    The output for the preceding command is shown as:

    javac 1.7.0_65
    
  4. Find the location of the javac command:
    $ which javac
    

    The output for the preceding command is shown as:

    /usr/bin/javac
    
  5. In the preceding output, javac is a symbolic link to the actual location of the file. Try to determine this location in the following way:
    $ readlink /usr/bin/javac
    

    The output for the preceding command is shown as:

    /etc/alternatives/javac
    
  6. By executing the preceding command, we again got the symbolic link. To get the path to the location of javac, we execute the following command again:
    $ readlink /etc/alternatives/javac
    

    The output for the preceding command is shown as:

    /usr/lib/jvm/java-1.7.0-openjdk.x86_64/bin/javac
    
  7. We have now located the folder where JDK is installed:
    /usr/lib/jvm/java-1.7.0-openjdk.x86_64/
    
  8. Set JAVA_HOME to the preceding folder. This can be done in two ways, depending on what you desire:

    If it is for the duration of the session, run the following command:

    export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk.x86_64/
    

    If this is permanent, add the preceding line in .bash_profile in your HOME folder.

If Java is not present, download and install Java from the Oracle Java download page at http://www.oracle.com/technetwork/java/javase/downloads/index.html.

If you have an rpm-based Linux distribution, you can download and install rpm. Otherwise, you can download the .tar.gz format of the distribution and extract it to a folder of your choice.

In the earlier case, you know exactly where Java is installed and can set JAVA_HOME correspondingly. Once installed, verify the Java installation by following the preceding steps.

Now, let us set up Maven on Linux.

How to do it...

To set up Maven on Linux, perform the following steps:

  1. Go to http://maven.apache.org/ and click on the Download link. The links to latest stable versions of Maven will be displayed.
  2. The binaries are available in both .zip and .tar.gz formats. For Mac OS X and Linux, the preferred download format is .tar.gz.
  3. Extract the downloaded binary to a folder you want Maven to reside in. The typical location in Linux is the /usr/local folder.

    Tip

    You will need a super user (su) or administrator access to place contents in the /usr/local folder. If you do not have access, you can place this in a subfolder of your HOME folder.

  4. Execute the following command, and ensure the contents of the apache-maven-3.2.5 folder are similar to the following output:
    /usr/local/apache-maven-3.2.5$ ls -l
    

    The output for the preceding command is shown as:

    total 27
    -rw-r--r--    1 root    root    17464 Aug 12 02:29 LICENSE
    -rw-r--r--    1 root    root      182 Aug 12 02:29 NOTICE
    -rw-r--r--    1 root    root     2508 Aug 12 02:26 README.txt
    drwxr-xr-x    8 root    root     4096 Aug 19 13:41 bin
    drwxr-xr-x    3 root    root        0 Aug 19 13:41 boot
    drwxr-xr-x    4 root    root        0 Oct 14 17:39 conf
    drwxr-xr-x   67 root    root    28672 Aug 19 13:41 lib
    
  5. Set the M2_HOME variable as follows:
    export M2_HOME=/usr/local/apache-maven-3.2.5
    
  6. Update PATH to include Maven's bin folder:
    export PATH=$PATH:$M2_HOME/bin
    

Like JAVA_HOME, the preceding settings can be persisted by updating .bash_profile.

How it works...

The Maven installation is essentially a set of JAR files, configuration files, and a Linux shell script, namely mvn.

The mvn command essentially runs this script. It first checks for JAVA_HOME. This file is present in the bin folder of the Maven installation and hence needs to be in PATH.

If the shell script does not find JAVA_HOME, it looks for java in its PATH. This can lead to unexpected results, as typically, the Java in PATH is usually JRE and not JDK.

The shell script then looks for M2_HOME, which is the location of the Maven installation. It does this so that it can load the libraries that are present.

Additionally, it also reads values specified in MAVEN_OPTS. This variable allows you to run Maven with an additional heap size and other Java parameters.

Using the values for JAVA_HOME, M2_HOME, and MAVEN_OPTS, the shell script runs its org.codehaus.plexus.classworlds.launcher.Launcher main class.

There's more...

Using the following steps, let's confirm that Maven has been set up correctly, by running a Maven command:

  1. Open a command prompt and run the following command:
    mvn –version
    
  2. The following output should be displayed:
    Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T22:59:23+05:30)
    Maven home: /usr/local/maven
    Java version: 1.7.0_65, vendor: Oracle Corporation
    Java home: /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.65.x86_64/jre
    Default locale: en_US, platform encoding: ANSI_X3.4-1968
    OS name: "linux", version: "2.6.32-279.22.1.el6.x86_64", arch: "amd64", family: "unix"
    

If you get an error, recheck the installation steps and repeat them.

See also

  • The Creating a simple project with Maven recipe in this chapter

Changing the JDK used by Maven

It is possible to have more than one version of JDK installed on your system. By following some simple steps, you can specify and/or change the JDK to be used by Maven.

How to do it...

You will recall that, in the earlier section, we used Java SE 7. Let us now change to Java SE 8. To change the JDK version to Java SE 8 on Microsoft Windows, perform the following steps:

  1. From the command prompt, run the following command:
    set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_20
    
  2. For Linux or Mac, the command will be:
    export JAVA_HOME=<java-8-home-folder>
    
  3. Now, run the following command to check the version of Maven installed:
    mvn –version
    
  4. To check the version of Maven installed on Microsoft Windows, run the following command from the command prompt. You should get the following output. The output will be similar for Linux and Mac:
    C:\projects\apache-maven-cookbook>mvn -version
    

    The output for the preceding command is shown as:

    Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T22:59:23+05:30)
    Maven home: C:\software\apache-maven-3.2.5
    Java version: 1.8.0_20, vendor: Oracle Corporation
    Java home: C:\Program Files\Java\jdk1.8.0_20\jre
    Default locale: en_IN, platform encoding: Cp1252
    OS name: "windows 8.1", version: "6.3", arch: "amd64", family: "windows"
    

How it works...

Maven always uses the JDK specified by JAVA_HOME, no matter how many JDK installations are available on the system. This allows the user the flexibility to change JDKs as required or based on the project.

Hence, it is important to ensure JAVA_HOME is defined. In the absence of this variable, Maven attempts to detect the presence of Java from PATH. This is typically JRE and not JDK.

Creating a simple project with Maven

Now that we have set up Maven on our favorite operating system and verified that it works fine, it is time to create a simple Java project.

Maven makes it easy to bootstrap a new project by creating a bunch of files and folders following accepted conventions.

How to do it...

Let's start creating the first simple project using Maven, by performing the following steps:

  1. Open a command prompt and change the directory to the folder in which you want to create your first Maven project.
  2. Run the following command:
    mvn archetype:generate -DgroupId=com.packt.cookbook -DartifactId=simple-project -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    

    You can change the groupId and artifactId values in the preceding command as per your requirement.

  3. You will see Maven downloading a bunch of files:
    Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.5/maven-clean-plugin-2.5.pom
    Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.5/maven-clean-plugin-2.5.pom (4 KB at 1.4 KB/sec)
    
  4. Then it will start generating sources:
    [INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) > generate-sources
    @ standalone-pom >>>
    
  5. When Maven has completed generating sources, it will create the project that we want:
    [INFO] Using following parameters for creating project from Old (1.x) Archetype:
    maven-archetype-quickstart:1.0
    [INFO] ----------------------------------------------------------------------------
    [INFO] Parameter: groupId, Value: com.packt.cookbook
    [INFO] Parameter: packageName, Value: com.packt.cookbook
    [INFO] Parameter: package, Value: com.packt.cookbook
    [INFO] Parameter: artifactId, Value: simple-project
    [INFO] Parameter: basedir, Value: C:\projects\apache-maven-cookbook
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] project created from Old (1.x) Archetype in dir: C:\projects\apache-maven-cookbook\simple-project
    

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.

How it works...

Did you get an while error running the preceding command to create your simple project?

One possibility is that your Maven is behind an HTTP proxy server. If so, see the Running Maven behind an HTTP proxy server recipe in this chapter.

Let's look at the folder structure that is created:

How it works...

You will notice the following things:

  • The Maven project configuration file pom.xml is created in the root of the simple-project folder. We will explore this file in detail in subsequent sections.
  • A bunch of folders are created:
    • src\main\java: This is for Java source files
    • src\test\java: This is for Java test source files
    • src\main\resources: This is for resource files for the project
    • src\test\resources: This is for resource files for the test
  • Within each of the preceding folders, a folder structure corresponding to the groupId (org.packt.cookbook) is created.

The following are essentially Maven conventions at work:

  • Maven expects all Java source files to reside in src\main\java
  • Similarly, it expects all Java test files to reside in src\test\java
  • It expects all project resources to reside in src\main\resources and test resources to reside in src\test\resources
  • It expects that source files will typically have the same package structure as the groupId parameter (though this is not mandatory)
  • Two sample classes, namely App.java and AppTest.java, are also created and it is not expected that they will be used beyond testing how Maven works

The mvn command that we used in the Creating a simple project with Maven recipe in this chapter, tries to invoke the generate goal of the archetype plugin with the specified command-line parameters.

The default Maven installation has minimal features. All features of Maven are available as Maven plugins. When given a plugin name, Maven knows where to download it from and then run it.

In this case, Maven downloads the archetype plugin. This plugin, in turn, can depend on another plugin. In this case, the latter plugin gets downloaded. This happens in a recursive fashion and, at the end of the process, all the relevant plugins required to run the specified command are downloaded.

These plugins are placed in your local repository, which is a location in your system. Once downloaded, these are never downloaded again unless deleted.

See also

  • The Running Maven behind an HTTP proxy server recipe in this chapter

Building a simple project with Maven

Let us now build the project that was created in the preceding section.

How to do it...

To build the previously created simple project with Maven, perform the following steps:

  1. Open the command prompt and run the following command, changing the directory to the folder the project was created:
    mvn package
    
  2. Observe the following things in the output:

    Notice the following warning (we will see how to resolve this later in this book):

    [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ simple-project ---
    [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
    i.e. build is platform dependent!
    

    Check if the sources are compiled:

    [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ simple-project
    

    Check if the tests are run:

    [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ simple-project ---
    [INFO] Surefire report directory: C:\projects\apache-maven-cookbook\simple-project\target\surefire-reports
    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running com.packt.cookbook.AppTest
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
    
  3. A JAR file is now created.

How it works...

In the mvn package command, the package parameter is a phase in the build lifecycle. Maven has a default build lifecycle that has a number of phases. Each phase will execute every phase prior to it in order along with the specified phase. In this case, the package phase executes in the following order:

  • Validate
  • Compile
  • Test
  • Package

The validate phase makes sure that the project (specifically the pom.xml file that describes the project) is in order and all the necessary information to run the project is available.

The compile phase compiles the sources.

The test phase compiles the test sources and then runs the test using a suitable test framework. In the earlier example, the JUnit framework is used to run the tests.

The package phase packages the artifacts to the format specified in the pom.xml file.

Changing the location of the Maven repository

There are three types of Maven repositories:

  • Local: This is the repository in your computer filesystem
  • Remote: This is the repository from where the required Maven files get downloaded
  • Mirrors: These are repository managers, such as Nexus and Artifactory, that mirror various repositories

You will have seen Maven downloading a number of files (called poms and jars). Let us see where they are located in your computer:

  • Go to your HOME folder (C:\Users\username) in the case of Microsoft Windows, /Users/username for Mac, and, /home/username (or a similar location) for Linux
  • You will notice the .m2 folder and within that, a subfolder called repository

    Tip

    Any folder that starts with a dot (.) is typically hidden from view. You will need to change your folder viewer settings to see it.

  • You will see a number of folders and files that are used by Maven

You may want to change this location for the following reasons:

  • You may want to conserve space in the C drive and store these folders and files in the D drive on Microsoft Windows.
  • You may want to take a back up of the contents. Backup software usually backs up contents in specific folders of the filesystem.
  • Your organization may have a policy for all users to store a local repository in the same folder.

How to do it...

To change the location of the Maven repository, perform the following steps:

  1. Create a file called settings.xml in the .m2 folder.
  2. Add the following contents to the settings.xml file that you just created:
    <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>C:/software/maven</localRepository>
    </settings>

    Notice the highlighted part of the preceding code. We have changed the location of the repository contents to C:\software\maven. You can change it to any valid folder name.

  3. Delete the repository subfolder and run the mvn package command again.

    You will now notice that the repository folder is not created in the .m2 folder. Instead, it is created in C:\software\maven.

How it works...

Maven determines the location of the local repository in the following way:

  • If settings.xml exists in the user's .m2 folder, which contains the <localRepository> tag, then Maven uses its contents to determine the location
  • If not, Maven will check if localRepository is explicitly defined in the default settings.xml, present in the conf folder of the Maven installation
  • If it is not present there, Maven will use the default value for the local repository, which is the user's .m2 folder

Running Maven behind an HTTP proxy server

Most organizations do not allow devices in their network to access the Internet directly for security and other reasons. In such cases, typically, a proxy server comes into picture. The proxy server details are specified in the browser or any other location where access to the Internet is required.

How to do it...

Let's start running Maven behind an HTTP proxy server, by performing the following steps:

  1. Create a settings.xml file in the .m2 folder in your HOME directory, if it does not exist already.
  2. Add the following code within the settings tag:
      <proxies>
        <proxy>
          <id>myproxy</id>
          <active>true</active>
          <protocol>http</protocol>
          <host>proxy.myorg.com</host>
          <port>8080</port>
          <username>proxyuser</username>
          <password>somepassword</password>
          <nonProxyHosts>*.myorg.com </nonProxyHosts>
        </proxy>
      </proxies>

If the proxy server does not need authentication, the username and password tags can be omitted.

The nonProxyHosts tag allows you to specify locations that can be accessed directly (for instance, your intranet). This can be skipped if not relevant.

How it works...

Maven needs Internet access to download plugins and dependencies. When Maven runs, it reads the user's settings.xml file, if it exists. It checks for any active proxy settings and applies the same.

Maven uses the values in the proxy settings to download any artifacts from the repository. If there are no artifacts to be downloaded, then these values are not used.

Note

The HTTP proxy server may work only in your organization's network. If you are running Maven from a different network, you may want to turn off the HTTP proxy server. This can be done by setting the active tag to false in the preceding code.

Understanding the standard directory layout

When we built our sample Java project earlier, we saw files being compiled, tests being run, and a JAR being generated. We do not know where these artifacts were created.

How to do it...

Let's find where the artifacts were created by performing the following steps:

  1. Go to the folder that has the sample Maven project.
  2. Open the target subfolder that was created:
    How to do it...

How it works...

When Maven runs, it puts all the contents that it generates into a separate folder. This is to distinguish it from any user-generated content. Let us examine the contents of this folder:

  • The classes folder: Compiled source files are placed in this folder. This folder will also contain resources, such as XML and property files that are part of the source, placed in src/main/resources.
  • The test-classes folder: Compiled test source files are available in this folder. In addition, it also contains test resources, which are files required for the purpose of testing, but not for running the project.
  • The surefire-reports folder: Test reports are separately placed in this folder. Typically, both XML and HTML report formats are available. The latter can be opened in the browser, while the former can be integrated with a code coverage tool.
  • The output .jar file: The generated project artifact is also present in this folder.
  • Two other folders—maven-archiver and maven-status—hold information used by Maven during the build.
Left arrow icon Right arrow icon
Download code icon Download Code

Description

If you are a Java developer or a manager who has experience with Apache Maven and want to extend your knowledge, then this is the ideal book for you. Apache Maven Cookbook is for those who want to learn how Apache Maven can be used for build automation. It is also meant for those familiar with Apache Maven, but want to understand the finer nuances of Maven and solve specific problems.

Who is this book for?

If you are a Java developer or a manager who has experience with Apache Maven and want to extend your knowledge, then this is the ideal book for you.

What you will learn

  • Install Apache Maven successfully on your preferred OS
  • Explore the various features of Apache Maven to build efficient automation tools
  • Discover when and how to use the various Apache Maven plugins
  • Generate and publish your project documentation using Apache Maven
  • Analyze and control code quality and code coverage using Apache Maven
  • Build various types of Java projects as well as other binaries
  • Set up complex projects using the concept of inheritance
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 28, 2015
Length: 272 pages
Edition : 1st
Language : English
ISBN-13 : 9781785286124
Vendor :
Apache
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Apr 28, 2015
Length: 272 pages
Edition : 1st
Language : English
ISBN-13 : 9781785286124
Vendor :
Apache
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 130.97
Apache Maven Cookbook
$54.99
Mastering Apache Maven 3
$48.99
Maven Essentials
$26.99
Total $ 130.97 Stars icon
Banner background image

Table of Contents

12 Chapters
1. Getting Started Chevron down icon Chevron up icon
2. IDE Integration with Maven Chevron down icon Chevron up icon
3. Maven Lifecycle Chevron down icon Chevron up icon
4. Essential Maven Plugins Chevron down icon Chevron up icon
5. Dependency Management Chevron down icon Chevron up icon
6. Code Quality Plugins Chevron down icon Chevron up icon
7. Reporting and Documentation Chevron down icon Chevron up icon
8. Handling Typical Build Requirements Chevron down icon Chevron up icon
9. Multi-module Projects Chevron down icon Chevron up icon
10. Java Development with Maven Chevron down icon Chevron up icon
11. Advanced Maven Usage Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(5 Ratings)
5 star 60%
4 star 0%
3 star 40%
2 star 0%
1 star 0%
Jackie Oct 31, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book for those new or experienced to Maven. I wish I had a book like this 5 years ago when I started using Maven. Although I did skim though most of the beginning I did get a lot of good example of best practices and plugin implementations. I highly recommend the book to anybody from developers to configuration management, and would go so far to call the Maven Bible for all practitioners.
Amazon Verified review Amazon
Phani Krishna May 20, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
When I got the opportunity to review this book, I thought the book would mostly be focused for beginners. Surprised the book has in it for everyone unlike the books released in market earlier. It begins at the very start, with the basics including installation screenshots, explains the concepts of everything you learn. It has got various scenarios of usage, and includes the code in the book. The book provides with best examples and explains how the object oriented approach of maven is used for re usability and flexibility.The book explains about the implementation of different plugins for java code with code and examples viz FindBugs(static analysis tool to bug tracking),PMD(source code analyzer),CheckStyle(Coding standard),Cobertura(Code Coverage),Sonar(Code Quality). All the examples are thoroughly tested and they work the way described in the book.Best of luck !! Go on buy it now :)
Amazon Verified review Amazon
Ludek Jun 04, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book covers all aspects of development using Maven on major OS platforms and IDEs. In great details explains how to start using Maven in any Enterprise environment, including Enterprise networks with the proxy servers. I believe this is great book for beginners’ as well as senior developers.
Amazon Verified review Amazon
J. West Jun 12, 2017
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
This book is a good start, but for me, it left several unanswered questions. The strengths are chapter 3 (Maven Lifecycle), chapter 4 (Essential Maven Plugins) and chapter 5 (Dependency Management). After that, several chapters were devoted to broad-brush descriptions of many Maven Plugins. These chapters weren't really useful. They took space, but didn't provide enough detail. This could have been compressed into a single chapter along the lines of "Maven Plugins you might want to understand/use".The book lacks coverage of profiles and how you pull code from one repo to a push to a local repo (which I believe is vital information that most people will want to cover).
Amazon Verified review Amazon
JamesK Jan 06, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Average book in my opinion. Too many topics brought up without a good explanation. Not sure how this bookreceived 5 stars overall. I must have missed something.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela