Introduction to Maven by Balaji Varnasi and Sudha Belida (translation)

  • Tutorial
From the translator: A few years ago, I set myself the goal to quickly, but rather tightly, get acquainted with such a widely used framework as Apache Maven. Almost instantly, I managed to find relevant literature, but I was slightly surprised by the fact that all the complex materials were exclusively in English, there were a lot of isolated articles in Russian, but I could not find a complete book that could be read from cover to cover. succeeded. As a result, I chose a small book “Introducing Maven”, written by Balaji Varnasi and Sudha Belida and published by Apress in 2014, for reading. As all the tasks were resolved, I gradually had a translation of this publication, which, though I had been in my desk for a couple of years, may still be useful to the community.

Here I give a translation of only one of the chapters of this book, and you can download it entirely here from these links in English , orRussian language (PDF).

Chapter 6: The Maven Archetypes


Up to this point, you created the Maven project manually, creating folders and pom.xml files from scratch. This can be tedious, especially if you often have to create projects. To solve this problem, Maven provides archetypes. Maven archetypes are project templates that allow users to easily create new projects.

The Maven archetypes also provide a convenient base for exchanging experiences and ensure the consistency of the standard Maven directory structure. For example, an enterprise can create an archetype with a corporate cascading style sheet ( CSS ) approved by JavaScript libraries.and reusable components. Developers using these archetypes to create projects will automatically follow company standards.

Embedded archetypes


Maven out of the box provides developers with hundreds of archetypes. In addition, there are many open source projects that provide additional archetypes that can be downloaded and used. Maven also provides plug-in archetypes with targets for creating archetypes and generating projects from archetypes.

The archetypes plug-in has the goal of generate , which allows you to view and select the desired archetype. Listing 6-1 displays the results of running the goal of generate with the command line. As you can see, 491 archetypes were provided for selection (by 2018 there were already more than 2 thousand - comment. Trans.) . The use of several of them is discussed in this chapter.

Listing 6-1. Calling the goal to generate a Maven archetype plugin

$mvn archetype:generate
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] -----------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone- pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<<
[INFO]
[INFO] ---maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom
[INFO] GeneratingprojectinInteractivemode
[INFO] Noarchetypedefined.Usingmaven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
......................................................1176:remote-> ru.yandex.qatools.camelot:camelot-plugin (-)
1177: remote -> se.vgregion.javg.maven.archetypes:javg-minimal-archetype (-)
1178: remote -> sk.seges.sesam:sesam-annotation-archetype (-)
1179: remote -> tk.skuro:clojure-maven-archetype (A simple Maven archetype for Clojure)
1180: remote -> tr.com .lucidcode:kite-archetype (A Maven Archetype that allows users to create a Fresh Kite project)
1181: remote -> uk.ac.rdg.resc:edal-ncwms-based-webapp (-)
1182: local -> com.inflinx.book.ldap:practical-ldap-empty-archetype (-)
1183: local -> com.inflinx.book.ldap:practical-ldap-archetype (-) Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 491:

Creating a Web Project


Maven provides the maven-archetype-webapp archetype for generating a web application. Let's create such an application by calling the following command in the C: \ apress \ gswm-book \ chapter6 folder :

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp

This command is executed interactively. For incoming questions, enter the following information:

Define value for property 'groupId': : com.apress.gswmbook
Define value for property 'artifactId': : gswm-web
Define value for property 'version': 1.0-SNAPSHOT: : <<HitEnter>>
Define value for property 'package': com.apress.gswmbook: : war 
Confirm the properties configuration:
groupId: com.apress.gswmbook
artifactId: gswm-web
version: 1.0-SNAPSHOT
package: war
Y: <<HitEnter>> 

The generated folder structure should be similar to the one shown in Figure 6-1 :

Figure 6-1. The structure of the Maven web project



The pom.xml file is minimal and contains a single dependency - JUnit . Maven can simplify your web application launch using embedded web servers such as Tomcat or Jetty . Listing 6-2 displays a modified pom.xml file with the added Tomcat plugin .

Listing 6-2. Modified pom.xml file with Tomcat plugin embedded

<projectxmlns=" http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.apress.gswmbook</groupId><artifactId>gswm-web</artifactId><packaging>war</packaging><version>1.0-SNAPSHOT</version><name>gswm-web Maven Webapp</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><build><finalName>gswm-web</finalName><plugins><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.2</version></plugin></plugins></build></project>

To run this web application on Tomcat, call the following command in the project root directory:

mvn tomcat7:run

You will see a detailed project and output similar to that shown in Listing 6-3 .

Listing 6-3. Tomcat run command output

Oct 11, 2014 12:08:43 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Tomcat
Oct 11, 2014 12:08:43 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
Oct 11, 2014 12:08:45 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using
[SHA1PRNG] took [334] milliseconds.
Oct 11, 2014 12:08:45 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]

Now launch your browser and go to localhost : 8080 / gswm-web / . You should see a webpage similar to Figure 6-2 .

Figure 6-2. Web project launched in browser



Multi-module project


Java Enterpise Edition (JEE) projects are often divided into several modules to facilitate development and support. Each of these modules produces artifacts such as Enterprise JavaBeans (EJBs) , web services, web projects, and client JARs . Maven supports the development of such large JEE projects, allowing you to host several Maven projects within another Maven project. The structure of such a multi-module project is shown in Figure 6-3 . The parent project has a pom.xml file and several Maven projects inside.

Figure 6-3. The structure of the multimodular project



Before the end of this chapter, we will explain how to build a multi-module project for a task in which you need to divide a large project into a web application ( WAR- artifact), providing a user interface, a service project ( JAR- artifact) containing the code for the service layer, and a project persistence ( persistence ), the repository containing the level code. On Figure 6-4 displays a visual representation of this scenario.

Figure 6-4. Maven Multi-Module Project



Let's start the process by creating a parent project. To do this, run the following command at the command prompt in the C: \ apress \ gswm-book \ chapter6 folder:

mvn archetype:generate -DgroupId=com.apress.gswmbook -DartifactId=gswm-parent         -Dversion=1.0.0-SNAPSHOT -DarchetypeGroupId=org.codehaus.mojo.archetypes               -DarchetypeArtifactId=pom-root

The pom-root archetype creates the gswm-parent folder and in it the pom.xml file .

As follows from Listing 6-4 , the pom.xml file created has minimal content. Notice that in the packaging tag of the parent project, the type pom is specified .

Listing 6-4. Parent pom.xml file

<projectxmlns="http://maven.apache.org/POM/4.0.0"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"><modelVersion>4.0.0</modelVersion><groupId>com.apress.gswmbook</groupId><artifactId>gswm-parent</artifactId><version>1.0.0-SNAPSHOT</version><packaging>pom</packaging><name>gswm-parent</name></project>

Now create a web project by running the following command in the C: \ apress \ gswm-book \ chapter6 \ gswm-parent folder :

mvn archetype:generate -DgroupId=com.apress.gswmbook -DartifactId=gswm-web           -Dversion=1.0.0-SNAPSHOT -Dpackage=war -DarchetypeArtifactId=maven-archetype-webapp

In the process of generating this web project, you provided Maven with coordinates such as groupId , version, and others in the form of parameters passed to the generating target, which created the gswm-web project .

The next step is to create a service project. From the C: \ apress \ gswm-book \ chapter6 \ gswm-parent folder, run the following command:

mvn archetype:generate -DgroupId=com.apress.gswmbook -DartifactId=gswm-service        -Dversion=1.0.0-SNAPSHOT -DarchetypeArtifactId=maven-archetype-quickstart             -DinteractiveMode=false

Note that you did not specify the package parameter , because maven-archetype-quickstart creates a default JAR project. Also note the use of the interactiveMode parameter . It simply tells Maven to execute the command, without prompting the user for any information.

Similar to the previous step, create the following gswm-repository Java project by running the following command in the C: \ apress \ gswm-book \ chapter6 \ gswm-parent folder :

mvn archetype:generate -DgroupId=com.apress.gswmbook -DartifactId=gswm-repository      -Dversion=1.0.0-SNAPSHOT -DarchetypeArtifactId=maven-archetype-quickstart              -DinteractiveMode=false

Now that all your projects have been generated, take a look at the pom.xml file in the gswm-parent folder . Listing 6-5 displays its contents.

Listing 6-5. Parent pom.xml file with modules

<?xml version="1.0" encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"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"><modelVersion>4.0.0</modelVersion><groupId>com.apress.gswmbook</groupId><artifactId>gswm-parent</artifactId><version>1.0.0-SNAPSHOT</version><packaging>pom</packaging><name>gswm-parent</name><modules><module>gswm-web</module><module>gswm-service</module><module>gswm-repository</module></modules></project>

The modules element allows you to declare child modules in a multi-module project. As each module is generated, Maven registers them as children. In addition, it modifies the pom.xml files of the modules themselves, adding in them information about the parent pom.xml . Listing 6-6 displays the pom.xml file of the gswm-web project , in which the parent pom element is specified .

Listing 6-6. Web module pom.xml file

<?xml version="1.0"?><projectxsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><modelVersion>4.0.0</modelVersion><parent><groupId>com.apress.gswmbook</groupId><artifactId>gswm-parent</artifactId><version>1.0.0-SNAPSHOT</version></parent><groupId>com.apress.gswmbook</groupId><artifactId>gswm-web</artifactId><version>1.0.0-SNAPSHOT</version><packaging>war</packaging><name>gswm-web Maven Webapp</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><build><finalName>gswm-web</finalName></build></project>

Now that the entire infrastructure is installed, you can build the next project. Just run the mvn package command from the gswm-project folder , as shown in Listing 6-7 .

Listing 6-7. Maven package command launched in the parent project directory

C:\apress\gswm-book\chapter6\gswm-parent>mvn package
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] gswm-parent
[INFO] gswm-web Maven Webapp
[INFO] gswm-service
[INFO] gswm-repository
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] gswm-parent ....................................... SUCCESS [0.001s]
[INFO] gswm-web Maven Webapp ............................. SUCCESS [1.033s]
[INFO] gswm-service ...................................... SUCCESS [0.552s]
[INFO] gswm-repository ................................... SUCCESS [0.261s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.949s
[INFO] Finished at: Mon Oct 13 23:09:21 MDT 2014
[INFO] Final Memory: 6M/15M
[INFO] ------------------------------------------------------------------------

Creation of archetypes


Maven provides several ways to create a new archetype. Here we will use an existing project for this.

Start by creating a prototype project that will be used as the basis for generating the archetype. This project will be a Servlet 3.0 compliant and contains a Status Servlet that returns the HTTP status code 200 (“OK” is a successful request). Instead of creating a web project from scratch, copy the previously generated project gswm-web and create gswm-web-prototype in the folder C: \ apress \ gswm-book \ chapter6 . Make the following changes to the newly copied project:

1. Delete all other resources, such as files specific toIntegrated Development Environment (IDE) ( .project , .classpath , etc.) that you do not want to include in the archetype.

2. Replace the contents of the web.xml file from the webapp / WEB-INF folder . This will configure the web application to use Servlet 3.0 :

<web-appxmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0"><display-name>Archetype Created Web Application</display-name></web-app>

3. Add the dependency of Servlet 3.0 to the pom.xml file . Updated pom.xml content is shown in Listing 6-8 .

Listing 6-8. Pom.xml file with Servlet Dependency

<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.apress.gswmbook</groupId><artifactId>gswm-web</artifactId><packaging>war</packaging><version>1.0-SNAPSHOT</version><name>gswm-web Maven Webapp</name><url>http://maven.apache.org</url><dependencies><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.0.1</version><scope>provided</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency></dependencies><build><finalName>gswm-web</finalName><plugins><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.2</version></plugin></plugins></build></project>

4. Because we will develop a web project in Java, then create a folder called java in the src / main directory . Similarly, create the test / java and test / resources folders in the src directory .

5. Create the AppStatusServlet.java file belonging to the com.apress.gswmbook.web.servlet package in the src / main / java directory . The com.apress.gswmbook.web.servlet package is converted into the com \ apress \ gswmbook \ web \ servlet folder structure . The source code for the AppStatusServelet.java file is shown in Listing 6-9 .

Listing 6-9. Java class source code AppStatusServlet

package com.apress.gswmbook.web.servlet; 
import javax.servlet.annotation.WebServlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*; 
@WebServlet("/status")
public class AppStatusServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
writer.println("OK");
response.setStatus(response.SC_OK);
}
}

The prototype project on the structure will be a hike to the one shown in Figure 6-5 .

Fig. 6-5. Generated prototype project



Using the command line, go to the project gswm-web-prototype folder from the following command:

mvn archetype:create-from-project

Upon completion of the command, you will see the message Archetype created in target / generated-sources / archetype . The generated archetype is located in the gswm-web-prototype / target / generated-sources / archetype folder .

The next step is to transfer the newly generated artifact to a separate folder gswm-web-archetype to configure it before publishing. To do this, follow these steps:

1. Create a folder gswm-web-archetype in the directory C: \ apress \ gswm-book \ chapter6 .

2. Copy the subdirectories and files from the C: \ apress \ gswm-book \ chapter6 \ gswm-web-prototype \ target \ generated-sources \ archetype folder to the gswm-web-archetype folder .

3. Remove the target subdirectory from the C: \ apress \ gswm-book \ chapter6 \ gswm-web-archetype folder .

The folder structure for gswm-web-archetype should be similar to that shown in Figure 6-6 .

Fig. 6-6. Web archetype project structure



Let's start the modification process with the pom.xml file located in the gswm-web-archetype \ src \ main \ resources \ archetype-resources folder . Modify finalName in pom.xml from gswm-web to $ {artifactId}. In the process of creating a project, Maven will replace the expression with $ {artifactId} with the value that was provided by the user.

When a project is created from an archetype, Maven prompts the user for the package name. Maven creates a folder structure corresponding to the package located in the src / main / java directory of the created project. Then Maven moves all content from the archetype-resources / src / main / java folder of the archetype to this package . Since If you want AppStatusServlet to be in the nested web.servlet package , then create a web / servlet folder and move AppStatusServlet there. The new location of AppStatusServlet.java is shown in Figure 6-7 .

Fig.6-7. AppStatusServlet in the web.servlet package



Open AppStatusServlet.javaand change the package name to package $ {package}; on package $ {package} .web.servlet;
The final step in creating an archetype is to execute the following command from the command line, being in the gswm-web-archetype folder:

mvn clean install

Use of archetypes


Once the archetype has been installed, the easiest way to create a project from it is, being in the folder C: \ apress \ gswm-book \ chapter6 , run the following command:
mvn archetype:generate -DarchetypeCatalog=local


In response to Maven requests, enter the values ​​listed in Listing 6-10 , and you will see the project created.

Listing 6-10. Creating a new project using the archetype

C:\apress\gswm-book\chapter6>mvn archetype:generate -DarchetypeCatalog=local
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO] Generating project in Interactive mode
[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.
maven.archetypes:maven-archetype-quickstart:1.0)
Choose archetype:1: local -> com.apress.gswmbook:gswm-web-archetype
(gswm-web-archetype)
Choose a number or apply filter (format: [groupId:]artifactId, case
sensitive contains): : 1
Define value for property 'groupId': : com.apress.gswmbook
Define value for property 'artifactId': : test-project
Define value for property 'version': 1.0-SNAPSHOT: :
Define value for property 'package': com.apress.gswmbook: :
Confirm properties configuration:
groupId: com.apress.gswmbook
artifactId: test-project
version: 1.0-SNAPSHOT
package: com.apress.gswmbook
Y: :
------------------------------------------------------------------------------
project
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:27.635s
[INFO] Finished at: Mon Oct 13 23:36:01 MDT 2014
[INFO] Final Memory: 9M/22M
[INFO] ------------------------------------------------------------------------

Since the pom.xml file for the test-project already contains a Tomcat plugin , then to start the project, run the mvn tomcat7: run command , being in the C: \ apress \ gswmbook \ chapter6 \ test-project folder . Open a browser and go to localhost : 8080 / test-project / status . You will see OK , as shown in Figure 6-8 .

Fig.6-8. Page generated by the generated project



Results


Maven archetypes are project procurement that allows you to quickly launch new projects. In this chapter, built-in archetypes were used to generate complex Maven projects, such as web projects or multi-module projects. You also learned how to create and use custom archetypes.

In the next chapter, you will learn the basics of generating a site, creating documentation and reports using Maven.

Also popular now: