Do you know about Maven?

Maven is a leading dependency management and build tool for Java™ developers, and it lives up to its name! It standardizes the software build process by illustrating the construction of a project, deploying it as an application, and then sharing it with other projects.

About this Series

Think you know Java programming? The truth is that most developers have only scratched the surface of the Java platform and barely know enough to do their job. In this series, The Java Technology sleuths dig deep into the core features of the Java platform, revealing tips and tricks that can help you solve your toughest programming challenges.

Maven uses a reliable set of plug-ins to provide all of its functionality. In Maven, plug-ins have targets, and behind the scenes, those targets are Java methods. The target performs build tasks, such as compiling the project, packaging it, and deploying it to local or remote servers. These activities map perfectly to the phases of the build life cycle.

Maven provides its own build plug-ins that are packaged and ready to use, pre-configured with default values. The “convention over configuration” principle ensures that the configuration can be extended for the complexity of a given task. Most build tasks require minimal configuration.

You can also customize the behavior of Maven plug-ins. Using Maven elements, it is easy to override plugin defaults and define new values. Unsurprisingly, the default values for most overrides are the and values of the Compiler plug-in.

Need proof? How many times have you added the XML in Listing 1 to the POM to set the correct JVM version?

Listing 1. Java version configuration in the Compiler plug-in

org.apache.maven.plugins

maven-compiler-plugin

3.6.1 track

   1.8

   1.8
Copy the code

Execute the Maven life cycle

Each plug-in target maps to a Maven lifecycle phase. Issuing the MVN compile command tells the MVN utility to invoke all targets bound to the compile lifecycle phase. The Compile target of the Compiler plug-in is bound to this lifecycle stage.

There is a one-to-many relationship between stages and goals. Multiple plug-in targets can be bound to the same stage to form a collection of related tasks. Phases are also layered, meaning that execution of one phase results in execution of all phases preceding it.

In this case, issuing the MVN compile command initiates the validate phase (the first phase of Maven’s default build life cycle) and invokes all targets bound to that phase.

The Maven and Google Code sites maintain a list of Maven plug-ins. These plug-ins provide a variety of useful and time-saving features that you can integrate into your build process. I’ll introduce some of the most useful plug-ins I’ve found and show you how to make the most of them.

1. Execute a digital signature on the JAR or WAR

Click the button below to download the code for this example. It contains a simple application and a POM file containing the configured Jarsigner plug-in.

Get the code

Digitally signing a JAR or WAR is an important task, especially if you want to distribute your application. Fortunately, the Java platform provides an archive signing utility called Jarsigner. It is a command-line tool that performs signature on an archive file by passing it its location and various parameters, such as the keystore that contains your encryption key.

Jarsigner can be found in the <%JAVA_HOME%>/bin directory of the JDK installation. Listing 2 shows how to use this utility to sign the JAR.

Listing 2. Use the Jarsigner utility to sign the archive file

jarsigner

-keystore /path/to/keystore.jks

-storepass

-keypass

YourArchive.jar

alias
Copy the code

Jarsigner is an easy-to-use command line tool that works right out of the box. If you can automate the signing process, wouldn’t it be better to sign the archive files during the Package phase of the build cycle? You can achieve this thanks to the Maven Jarsigner plug-in, which includes the Jarsigner utility. You only need to bind the plug-in’s Sign target to the Package phase of your build cycle.

First, you need a keystore. If not, you can create it using the Java platform’s keytool utility, which is found in the <%JAVA_HOME%>/bin directory of the JDK installation.

Create a keystore

To create a keystore, navigate to where you want to place it and execute the commands in Listing 3. Be sure to replace KeyAlias with an appropriate value, such as your domain name. The official Oracle documentation details additional configuration options accepted by the tool.

Listing 3. Create a keystore for the Jarsigner utility

1keytool -genkey -alias -keyalg RSA -keystore keystore.jks -keysize 2048

The process of creating a keystore requires you to answer a series of questions about yourself and your organization and provide a secure password. This password will be required when you configure the Maven Jarsigner plug-in (as you will do next).

Add Jarsigner to your build process

Now add the Maven Jarsigner plug-in to your build lifecycle, and then configure it to digitally sign the JARS generated during the Package phase. The association to this stage makes sense because the JAR is constructed and stored in your project’s default output directory, which is usually the Target directory. In the section of the POM file, add the code shown in Listing 4.

Listing 4. Adding the Jarsigner plug-in

org.apache.maven.plugins

maven-jarsigner-plugin

1.4

You want to sign the JAR after it is built, so you need to wire the signing process (wrapped in the Sign target) to the Package lifecycle phase. To do this, add the code in Listing 5 to the plug-in.

Listing 5. Connect the Sign target to the Package stage

    sign

    package



        sign
Copy the code

The Sign target requires some configuration details to digitally sign the JAR. So you should add the keystore location, the alias of the credentials you want to use, the keystore password, and the password of the credentials between the elements, as shown in Listing 6.

Listing 6. Specifying security credentials

/location/of/keystore.jks

KeyAlias

password

password

This is the minimum configuration required to implement the JAR signature feature. Note that the plug-in provides a number of additional configuration options to choose from.

The final step is to build the JAR and verify that it has been signed correctly. Execute the package target from the command line as follows: MVN clean Package. In the console output, you see that the JAR is being built and then signed. Figure 1 shows what you might see

Figure 1. The output shows that the archive was signed

Build the JAR into the target output directory, where the Jarsigner plug-in expects to find it. The plug-in will sign the JAR using the credentials you provide, and then add two additional files to the meta-INF directory: a signature file with the.sf extension, and a signature block file with the.rsa extension.

A digitally signed JAR is now available for classification.

Verifying a digital signature

Before classifying the JAR, let’s verify that it’s properly signed. You can do this using Maven Jarsigner’s Verify target, or using the Jarsigner tool from the command line. In Listing 7, I use the command line tool and pass it the archive file I want to validate.

Listing 7. Verify the signed JAR using the Jarsigner utility

1jarsigner -verify target/YourJavaArchive.jar

If successful, the following message is received: JAR Verified.

Sign the WAR file

Signing jars is not Jarsigner’s only feature. The plug-in can perform signing on any Java archive file, including a WAR file. To see how this works, change the PACKAGING type of the POM from JAR to WAR, add the Maven WAR plug-in (shown in Listing 8), and run the command: MVN Clean Package.

Listing 8. Adding the Maven WAR plug-in

org.apache.maven.plugins

maven-war-plugin

3.1.0

Check the target directory and you’ll find the signed WAR file.

Perform signature on multiple archive files

Jarsigner also handles this if you have multiple archive files to sign. The code in Listing 9 specifies the JAR’s signing location as target/all, and all jars in this directory will be signed.

Listing 9. Specify an archive directory

1target/all

If you need more precise control over which archive files to sign, you can use wildcards to explicitly include and exclude files, as shown in Listing 10.

Listing 10. Include and exclude selected archive files

* 1.0. The jar

*SNAPSHOT.jar

2. Deploy a protected Web application using Maven Cargo

Click the button below to download the code for this example. It contains a simple Web application and a POM file containing the configured Cargo plug-in.

Get the code

The Cargo plug-in from Codehaus is a wrapper around the Cargo API. The API is designed to configure, start, stop, and deploy an application to a variety of supported containers, as well as parse, create, and merge Java EE modules.

One particularly important feature is Cargo’s ability to specify server properties in a container-agnostic way. These attributes include ports, remote security credentials, JVM parameters, and (most interesting to us) user login details for the application you want to deploy. The plug-in supports the latest versions of 14 of the most popular servers.

The Cargo plug-in is best associated with the Package phase of the Maven life cycle. You can also directly reference the run target to execute it independently: MVN cargo:run. Standalone execution assumes that the project is packaged and ready for deployment.

We first associate Cargo’s run target with the Package stage, as shown in Listing 11.

Listing 11. Associate the Run target for Cargo with the Package stage

org.codehaus.cargo

cargo-maven2-plugin

1.6.4

       package



           run
Copy the code

With Maven integration complete, you now need to configure the target container to which you want Cargo to deploy your application. Cargo supports a variety of container scenarios, including deployment to an already running local or remote server (which includes starting the server when needed). Alternatively, Cargo can be configured to download, install, deploy, and start any of the 14 servers it supports.

For this example, I will use IBM® WebSphere® Liberty, which I have downloaded and unpacked into a directory called Servers.

Container configuration requires at least the container ID and the home directory location of the installed server. Listing 12 shows the configuration of the Liberty server in my Servers/WLP directory.

Listing 12. Container configuration

   liberty

   \path\to\servers\wlp
Copy the code

Download the container ZIP file

Another option is to specify the URL of the Liberty ZIP file on the IBM Web site, in which case the Cargo plug-in downloads and installs the server. Listing 13 shows the code to do this.

Listing 13. Installing the container from the network

liberty

https://public.dhe.ibm.com/ibmdl/export/pub/ software/websphere/wasdev/downloads/WLP / 17.0.0.2 / WLP - webProfile7-17.0.0.2. Zip/path/to/downloadDir/path/to/extractDirCopy the code

When the run target is first executed, the ZIP file is downloaded and decompressed. On subsequent execution, Maven detects that the file has been downloaded and installed and skips the task.

You now have minimal configuration and can deploy the application to your server to test the configuration. The process is started by calling the Package stage (MVN Package). The application is compiled, packaged, and deployed to the server, and can be accessed at the following URL: http://localhost:8080/{artifactid}/index.html.

Custom context root directory

By default, artifactid is used to name the context root of a Web application. In some cases, you need to specify a custom context root directory. In Listing 14, I define the context root as home.

Listing 14. Custom context root

       home
Copy the code

Deploy the application, the Web application can be accessed through the following address: localhost: 8080 / home/index. HTML.

Specify user login information

You now have a very reliable deployment process that downloads and installs a server to deploy your application to a custom context root. This is just the beginning of what the Cargo plug-in can do.

Cargo really came into its own when we started defining configuration properties. As I mentioned earlier, these configuration properties are container properties, such as ports, protocols, and most importantly, user login details.

Let’s add a user to the sample application and force a login to the site. To keep things simple, we’ll use a basic authentication approach that requires minimal configuration in the application’s web.xml file. Listing 15 shows the user-role specification and restrictions on WelcomeServlet Web resources.

Listing 15. Declaring user roles

       Welcome Servlet

       /WelcomeServlet/*

       GET







       user-role









   BASIC

   file







   user-role
Copy the code

The Cargo plug-in can be configured to create a user for a user-role, which can be done dynamically at deployment time. Listing 16 shows the user name and password defined for the user-role. The user name is user, and the password is user123! .

Listing 16. Defining the user name and password

user:user1234! :user-roleCopy the code

The format of the attribute is username:password:role. Multiple users can be declared for the same and different roles in a property by separating the property collection with a vertical line symbol:

1username1:password1:role11,… ,role1N|username2:password2:role21,… ,role2N|…

With the user name and password assigned to the user role, you can now package and deploy the application. With a single command (MVN Clean Package), your Web application will be compiled, packaged, and deployed into the Liberty container. The server will also start.

If you navigate to the URL http://localhost:8080/home/WelcomeServlet, you will see a login box, as shown in figure 2. Enter the username and password configured In the Cargo plug-in, and click Log In to enter the application.

Figure 2. Login box

3. Install a custom JAR into your local repository

The traditional way to include a JAR in a project is to create a directory in the project and make sure it is on the classpath. With Maven, you don’t need to do that. Instead of putting jars and projects together, Maven stores them in an isolated local repository. Your project must then specify dependencies on these jars.

This local repository is populated with dependencies downloaded from the central Maven repository. It’s like a Maven aircraft carrier, with thousands of popular and generic jars. But what if the JAR you want to use is not in Maven’s central repository? Of course, you can rely on traditional solutions to include jars directly in your project, but you won’t benefit from Maven’s dependency management.

You can install jars into your local Maven repository using the Maven Install Plugin. First, you need to download the plug-in, and then you can execute its install-file target. This example is slightly different from the previous ones in that you do not associate the target with a Maven lifecycle phase. You specify the target in the Maven command line tool.

The install-file target requires five parameters to specify the location of the JAR file, group, artifactid, its version number, and package type. Listing 17 shows the structure of the Maven command.

Listing 17. Install the JAR in your local Maven repository

mvn install:install-file

-Dfile=PATH/TO/YOUR-JAR.jar

-DgroupId=GROUP-ID

-DartifactId=ARTIFACT-ID

-Dversion=VERSION

-Dpackaging=jar
Copy the code

For the JAR you want to install, you need to specify the values of the parameters shown above. You can specify them as any value you want. After doing this, you can see for yourself that the new files are stored in your local Maven repository. Navigate to the repository directory /.m2/repository and find the folder named group-id. If the groupId value is a reverse domain name, such as com.readlearnCode, search the com directory and navigate to the ReadlearnCode directory. Here you can find a folder that contains the version numbers of the artifacts and JARS that have been installed in that folder. The location of the JAR may be similar to: /. M2 / repository/com/readlearncode / 4.0 / MyJar. JAR.

Your JAR is now available for all of your projects. You can add it as a dependency to your POM as usual, as shown in Listing 18.

Listing 18. Specify your JAR as a dependency

GROUP-ID

ARTIFACT-ID

VERSION

4. Create a GitHub based Maven repository

Click the button below to download the code for this example. It contains a simple application and a POM file with site-Maven-plugin configured.

Get the code

There are many reasons for hosting Maven repositories on GitHub, including licensing issues, privacy, and the cost of commercial hosting. Regardless of why you chose to host a GitHub based Maven repository, setting up a repository is easy.

First, create a branch in the existing GitHub repository and install the project artifacts directly into that branch. This is bound to the Deploy phase of the Maven life cycle so that the remote repository can be refreshed automatically when a project is deployed.

Add GitHub credentials

After you have created a Maven branch in the GitHub repository, you need to add your GitHub repository credentials to Maven’s settings.xml file. This file is usually found in the.m2 directory. Between the elements of settings.xml, you need to define a new server and specify your user name and password. Listing 19 demonstrates this process (note that I named my new server Github).

Listing 19. Configuring a Github repository as a server

   github

   USERNAME_OR_EMAIL

   PASSWORD
Copy the code

Two-factor authentication

If two-factor authentication is enabled, you need to create a Personal Access Token using GitHub Settings. Copy and paste the token directly into the element. For extra security, follow the instructions on Maven’s website to encrypt your password.

Maven site plugin

In Maven POM, you will use GitHub’s site-Maven-plugin. The first thing you need to do is set up a base directory from which to submit files. Start by creating a temporary directory and placing it in the target directory of your project, as shown in Listing 20. For this example, I’ll name the directory repo-stage.

Next, because you want to associate this plug-in with the deploy phase, you must specify the repository location in the Maven-deploy-plugin. The code snippet in Listing 20 shows how to specify the repository location.

Listing 20. Specify the alternative local repository

maven-deploy-plugin

2.8.2

          Repo.stage::default::file://

          ${project.build.directory}/repo-stage
Copy the code

Finally, the site-Maven-plugin needs to be configured and associated with the deploy phase. To do this, pass the id of the GitHub server you created earlier to the plug-in. It also needs to be passed the repository name and owner, the branch to which you committed the project artifact, and a comment for that submission. You also need to turn off Jekyll so it doesn’t think it needs to generate GitHub pages.

Listing 21 shows the complete configuration of the site-Maven-plugin. Note that the repository name is dependency (GitHub will create it if the branch does not exist).

Listing 21. Configuring the site plug-in

com.github.github

site-maven-plugin

0.12

   github

   MavenSampler

   atheedom

   refs/heads/dependency



     Artifacts for

     ${project.name}/${project.artifactId}/${project.version}



   true





          ${project.build.directory}/repo-stage





       **/*









       deploy



           site
Copy the code

All that remains is to run the command MVN clean deploy. From the console, you’ll see the plug-in upload the repository file to your GitHub account, create a commit, and push the commit to the dependency branch. The console output should look like Figure 3.

Figure 3. Console output from a successful commit

To verify that all steps work as expected, visit your GitHub repository and select the Dependency branch. You will see all the artifacts for your project, as shown in Figure 4.

Figure 4. Screen capture of the Maven repository on GitHub

After confirming that your artifacts have been safely submitted to your GitHub Maven repository, you may want to share the new repository with others who want to rely on your project.

Add GitHub as the repository

To specify the GitHub Maven repository as a remote repository for their own projects, subscribers need to declare the repository in their POM, as shown in Listing 22. The artifacts for your project will then be specified as normal, as shown in Listing 23.

Listing 22. Specifying GitHub as a remote repository

   PROJECT_NAME-dependency



          https://raw.github.com/

          GITHUB_USERNAME/PROJECT_NAME/dependency





       true

       always
Copy the code

Listing 23. Project dependencies

com.readlearncode

maven-sampler

1.0

You now have a simple, public Maven repository to deploy your dependencies and share them with the world.

More time-saving tips and tricks

Apache Maven is so widely used that finding unknown tips and tricks is like prospecting for gold. So I decided to end with some information that I found very useful. Here, you’ll find some valuable tips for saving time and avoiding frustration.

“Roomba” without dependencies

Development can be fun and exciting, especially when you work with new apis and technologies. Maven also introduces new technologies quickly and easily: You just copy and paste dependencies into your POM files, and you’re done. However, as developers, we sometimes get carried away with our passions and forget to remove unused dependencies; Or we’re too lazy to do it. Over time, this bad habit can make your POM bigger and slow down your deployment.

So my first tip is that Maven is like Roomba, the robotic vacuum cleaner. Simply run the command in Listing 24 and Maven will analyze your project code to find unused dependencies and validate them.

Listing 24. Validate unused dependencies

1dependency:analyze

Clean the local repository

You need to clean your Maven repository from time to time – perhaps because of misuse, or because your IDE indexing is very slow. For whatever reason, you can execute the code in Listing 25 to remove all contaminants.

Listing 25. Cleaning the local repository

1mvn dependency:purge-local-repository

This will clean the current project and then automatically download all of its dependencies. Your project will be reborn and ready to surpass itself again.

Add a timestamp!

Adding a timestamp to the build cycle can be very useful. Maven 2 introduces the build variable maven.build.timestamp, which represents the start time of the build. This variable can be used anywhere in the POM via the variable ${maven.build.timestamp}.

You can use the Java SimpleDateFormat class to format the timestamp and declare it with properties. Listing 26 shows an example of how to do this.

Listing 26. Timestamp format

    yyyy-MM-dd'T'HH:mm:ss'Z'
Copy the code

Echo properties

Have you ever wondered about a Maven attribute value? Without guessing, you can use maven-antrun-plugin to get a definitive answer. This compact tool will echo back to the console any properties you pass to it.

In Listing 27, you associate Antrun’s Run target with Maven’s Validate phase (the first default lifecycle phase), using elements from the Configuration section to output attribute values.

Listing 27. Echo the properties to the console

org.apache.maven.plugins

maven-antrun-plugin

1.1

       validate

           run

                   settings.localRepository = ${settings.localRepository}

              project.build.directory = ${project.build.directory}
Copy the code

You can now perform the Validate phase using MVN Validate and see the property values output to the console.

conclusion

Maven is more than just a build tool, thanks to plug-ins that simplify and automate many development tasks. In this article, I’ve introduced some plug-ins and provided tips on how to use them for a more efficient and productive development lifecycle.

If you also want to get a high salary in IT industry, you can attend our training camp courses, choose the most suitable for their own courses to learn, technical masters teach, 7 months later, enter the famous enterprises to get a high salary. Our course content includes: Java engineering, high performance and distributed, high performance, easy to understand. High architecture. Performance tuning, Spring, MyBatis, Netty source analysis and big data and other knowledge points. If you want to get a high salary, want to learn, want to have a good employment prospects, want to compete with others can obtain advantages, want to enter Ali interview but worry about the interview, you can come, group number is: 454377428

Note: Add group requirement

1. Those with 1-5 work experience, who do not know where to start in the face of the current popular technology and need to break the technical bottleneck can be recruited.

2. I have been in the company for a long time and have been comfortable, but I hit a wall in the interview when I changed my job. Need to study in a short period of time, job-hopping can be added.

3. If you have no working experience, but have a solid foundation, and have a good command of Java working mechanism, common design ideas and common Java development framework, you can add.

4, feel very good B, general needs can be done. But the knowledge points learned are not systematic, it is difficult to continue to break through in the field of technology can be added.

5. Ali Java senior bull live explain knowledge points, share knowledge, sorting out and summarizing years of work experience, with everyone to establish their own technical system and technical knowledge in a comprehensive and scientific way!

6. No small or small white or other groups, thank you.

We have the target, now it’s action! Remember: learning is always your business, and you won’t have much time if you don’t learn, but you can sometimes use what you learn to have more fun! Time is the basic component of life, but also the fundamental scale of all things exist, our time is there, our life is there! Our values will rise or fall there too! Java programmers, come on