Maven:Explored

MAVEN

Maven can do more than just build software – it can assist with testing, run web applications and produce reports on projects, as well as any number of other tasks provided by plug-ins

Installing the MAVEN

On Windows

Post installation it will go to C:\Program Files\Apache Maven.x.x.x folder\
Set the environment PATH variable to “C:\Program Files\Apache Maven.x.x.x folder\” folder
Confirm with mvn -v in a new shell. The result should look similar to below

1. Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T04:57:37-07:00)
2. Maven home: /opt/apache-maven-3.3.3
3. Java version: 1.8.0_45, vendor: Oracle Corporation
4. Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre
5. Default locale: en_US, platform encoding: UTF-8
6. OS name: “mac os x”, version: “10.8.5”, arch: “x86_64”, family: “mac”

On Centos 7

Download maven tar.gz file from the website or do below
$ sudo wget http://mirror.cc.columbia.edu/pub/software/apache/maven/maven-3/3.0.5/binaries/apache-maven-3.0.5-bin.tar.gz

$ sudo tar xzf[xtract zip file] apache-maven-3.0.5-bin.tar.gz -C /usr/local
$ cd /usr/local
$ sudo ln(create a link or synonym for apache folder name) -s apache-maven-3.0.5 maven

Next, set up Maven path system-wide (setting the environment variable)
$ sudo vi /etc/profile.d/maven.sh
export M2_HOME=/usr/local/maven

export PATH=${M2_HOME}/bin:${PATH}[in last ${PATH} is specified because to concatenate with other path variable list]

Finally, log out and log in again to activate the above environment variables.
To verify successful installation of maven, check the version of maven:

Configuration of MAVAN both User and Global Level

This is the configuration file for Maven. It can be specified at two levels:
1. User Level. This settings.xml file provides configuration for a single user, and is normally provided in ${user.home}/.m2/settings.xml.
NOTE: This location can be overridden with the CLI option:
-s /path/to/user/settings.xml

2. Global Level. This settings.xml file provides configuration for all Maven
users on a machine (assuming they’re all using the same Maven installation). It’s normally provided in ${maven.home}/conf/settings.xml.
NOTE: This location can be overridden with the CLI option:
-gs /path/to/global/settings.xml

Setting configurable for MAVEN

1) Local repository – You can configure where to keep all the artifacts on your local machine.

2) Offline – Determine whether MAVEN should attempt to connect to the network for executing the build to download any prerequisite artifacts.

3) Mirrors – Specify our repository location where plugins or artifacts can be downloaded.

4) Profile – it is tell the maven from where to look for some variables for instance directory location, artifactory location, etc before going to default value. For instance we can tell the maven to look for maven local repository first to get the plugins and then move to maven global repository if it doesn’t ‘t find. But we need to ensure the profile is activated.

MAVEN SYNTAX and Lifecycle

What is Build Lifecycle?
A Build Lifecycle is a well-defined sequence of phases which define the order in which the goals are to be executed. Here phase represents a stage in life cycle.

As an example, a typical Maven Build Lifecycle is consists of following sequence of phases

  • Validate – validate the project is correct and all necessary information is available
  • Compile – compile the source code of the project
  • Test – test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • Package – take the compiled code and package it in its distributable format, such as a JAR.
  • Integration-test – process and deploy the package if necessary into an environment where integration tests can be run
  • Verify – run any checks to verify the package is valid and meets quality criteria
  • Install – install the package into the local repository, for use as a dependency in other projects locally
  • Deploy – done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

There are always pre and post phases which can be used to register goals which must run prior to or after a particular phase.

When Maven starts building a project, it steps through a defined sequence of phases and executes goals which are registered with each phase. Maven has following three standard lifecycles:

· clean

· default(or build)

· site

A goal represents a specific task which contributes to the building and managing of a project. It may be bound to zero or more build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation.

The order of execution depends on the order in which the goal(s) and the build phase(s) are invoked. For example, consider the command below. The clean and package arguments are build phases while the dependency:copy-dependencies is a goal.

mvn clean dependency:copy-dependencies package
Here the clean phase will be executed first, and then the dependency:copy-dependencies goal will be executed, and finally package phase will be executed.

go to link Clean Lifecycle

When we execute mvn post-clean command, Maven invokes the clean lifecycle consisting of the following phases.

pre-clean

clean

post-clean

Maven clean goal (clean:clean) is bound to the clean phase in the clean lifecycle. Its clean:clean goal deletes the output of a build by deleting the build directory. Thus when mvn clean command executes, Maven deletes the build directory.

We can customize this behavior by mentioning goals in any of the above phases of clean life cycle.

In the following example, We’ll attach maven-antrun-plugin:run goal to the pre-clean, clean, and post-clean phases. This will allow us to echo text [CUSTOM TASK] messages displaying the phases of the clean lifecycle.

org.apache.maven.plugins —maven-antrun-plugin

id.pre-clean
pre-clean
run
pre-clean phase

The syntax for running Maven is as follows:
mvn [options] [<goal(s)>] [<phase(s)>]

All available options are documented in the built in help that you can access with
mvn -h

The typical invocation for building a Maven project uses a Maven life cycle phase. E.g.
mvn package

The built in life cycles and their phases are in order are:
clean – pre-clean, clean, post-clean

default – validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy

site – pre-site, site, post-site, site-deploy

A fresh build of a project generating all packaged outputs and the documentation site and deploying it to a repository manager could be done with

mvn clean deploy site-deploy

Just creating the package and installing it in the local repository for re-use from other projects can be done with

mvn clean install

This is the most common build invocation for a Maven project.

When not working with a project and in some other use cases, you might want to invoke a specific task implemented by a part of Maven – this is called a goal of a plugin. E.g.:

mvn archetype:generate
or
mvn checkstyle:check

There are many different plugins available and they all implement different goals.

We can force the maven to use particular plugin version by adding that to our project object model inside the project folder. This would inside the section of the POM

A maven could be executed with –X command line to debug.

buy Keppra in bulk Understanding of POM

A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects. Examples for this are the build directory, which is target; the source directory, which is src/main/java; the test source directory, which is src/test/java; and so on.

The POM was renamed from project.xml in Maven 1 to pom.xml in Maven 2. Instead of having a maven.xml file that contains the goals that can be executed, the goals or plugins are now configured in the pom.xml. When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, and then executes the goal.

Some of the configuration that can be specified in the POM are the project dependencies, the plugins or goals that can be executed, the build profiles, and so on. Other information such as the project version, description, developers, mailing lists and such can also be specified.

Location of super pom in version 3.0 is mavan.model.builder.3.0.
It should be noted that there should be a single POM file for each project.

· All POM files require the project element and three mandatory fields: groupId, artifactId, version.
· Projects notation in repository is groupId: artifactId: version.
· Root element of POM.xml is project and it has three major sub-nodes :
Node
Description

get link groupId : This is an Id of project’s group. This is generally unique amongst an organization or a project. For example, a banking group com.company.bank has all bank related projects.

artifactId :This is an Id of the project. This is generally name of the project. For example, consumer-banking. Along with the groupId, the artifactId defines the artifact’s location within the repository.

version :This is the version of the project. Along with the groupId, It is used within an artifact’s repository to separate versions from each other. For example:

com.company.bank: consumer-banking:1.0
com.company.bank: consumer-banking: 1.1.

It corresponds to folder structure in MAVEN. Default maven will have src\MAIN\JAVA
And scr\TEST\JAVA further both will have folder as per dot separated values given in pom tag.

If package pom tag will have dev.alm.com then both above MAIN/JAVA and TEST/JAVA will have child folders as dev/alm/com

Dependency: It will show the decency of the project. The MAVAN will down load them in the repository if not found on the machine.

Build
Resources
Plugin

Maven is – at its heart – a plugin execution framework; all work is done by plugins. There are the build and the reporting plugins:

Build plugins will be executed during the build and they should be configured in the element from the POM.

Reporting plugins will be executed during the site generation and they should be configured in the element from the POM. Because the result of a Reporting plugin is part of the generated site, Reporting plugins should be both internationalized and localized. You can read more about the localization of our plugins and how you can help.

Like mvn archetype: generate is a plugin that will generate the maven project structure. Archetype could be normal java project or could be created as spring framework.

A mojo is a Maven plain Old Java Object. Each mojo is an executable goal in Maven, and a plugin is a distribution of one or more related mojos. In short, a mojo is a maven goal, to extend functionality not already found in maven.

Below is the class which extent abstractmojo where you could pass in parameter from section carry out the necessary job.

Remember that a plug-in consists of one or more Mojos(Java Classes) where a Mojo maps to a goal

public class MyAnimalMojo extends AbstractMojo

{
/**
* @parameter
*/
private List animals;
public void execute()
throws MojoExecutionException
{

}
}

Below the pom.xml that you would use to call that plugin.
maven-myanimal-plugin
1.0
cat
dog
aardvark

Difference between Maven Install and Maven Deploy

In maven
mvn install is intended to install the artifacts into the local repository and NOT into the remote repository. To upload the artifacts to the remote repository you need to say:

mvn deploy
The mvn deploy will use the entries from distributionManagement to upload the artifacts to the given repository.

Help Goal
Recent Maven plugins have generally an help goal to have in the command line the description of the plugin, with their parameters and types. For instance, to understand the javadoc goal, you need to call:

1. mvn javadoc:help -Ddetail -Dgoal=javadoc
And you will see all parameters for the javadoc:javadoc goal, similar to this page.

EXEC plugin is available to execute external program.

War file deployment to Tomcat 7 and tomcat 8

Remotely deploy to tomcat 7 servers:  Tomcat7-maven-plugin is used to deploy to tomcat 8 server. Use the https link to the server to carry out the deployment.

 

Distribution Manageme: Distribution management acts precisely as it sounds: it manages the distribution of the artifact and supporting files generated throughout the build process. Starting with the last elements first:

DownloadUrl: is the url of the repository from whence another POM may point to in order to grab this POM’s artifact. In the simplest terms, we told the POM how to upload it (through repository/url), but from where can the public download it? This element answers that question.

Status: Warning! Like a baby bird in a nest, the status should never be touched by human hands! The reason for this is that Maven will set the status of the project when it is transported out to the repository. Its valid types are as follows.

None: No special status. This is the default for a POM.

Converted: The manager of the repository converted this POM from an earlier version to Maven 2.

Partner: This could just as easily have been called synched. This means that this artifact has been synched with a partner repository.

Deployed: By far the most common status, meaning that this artifact was deployed from a Maven 2 or 3 instance. This is what you get when you manually deploy using the command-line deploy phase.

Verified: This project has been verified, and should be considered finalized.

Repository: Whereas the repositories element specifies in the POM the location and manner in which Maven may download remote artifacts for use by the current project, distribution Management specifies where (and how) this project will get to a remote repository when it is deployed. The repository elements will be used for snapshot distribution if the snapshot Repository is not defined.

Name: The id is used to uniquely identify this repository amongst many, and the name is a human readable form.

uniqueVersion: The unique version takes a true or false value to denote whether artifacts deployed to this repository should get a uniquely generated version number, or use the version number defined as part of the address.

url: This is the core of the repository element. It specifies both the location and the transport protocol to be used to transfer a built artifact (and POM file, and checksum data) to the repository.

layout: These are the same types and purpose as the layout element defined in the repository element. They are default and legacy.

[outside of distribution repository]

Profiles

A new feature of the POM 4.0 is the ability of a project to change settings depending on the environment where it is being built. A profile element contains both an optional activation (a profile trigger) and the set of changes to be made to the POM if that profile has been activated. For example, a project built for a test environment may point to a different database than that of the final deployment. Or dependencies may be pulled from different repositories based upon the JDK version used. The elements of profiles are as follows:

Activation

Activations are the key of a profile. The power of a profile comes from its ability to modify the basic POM only under certain circumstances. Those circumstances are specified via an activation element.

Activation occurs when one or more of the specified criteria have been met. When the first positive result is encountered, processing stops and the profile is marked as active.

jdk: activation has a built in, Java-centric check in the jdk element. This will activate if the test is run under a jdk version number that matches the prefix given. In the above example,1.5.0_06 will match. Ranges are also supported as of Maven 2.1. See the maven-enforcer-plugin for more details about supported ranges.

Os: The os element can define some operating system specific properties shown above. See the maven-enforcer-plugins RequireOS Rule for more details about OS values.

Property: The profile will activate if Maven detects a property (a value which can be dereferenced within the POM by ${name}) of the corresponding name=value pair.

File: Finally, a given filename may activate the profile by the existence of a file, or if it is missing. NOTE: interpolation for this element is limited to ${basedir}, System properties and request properties.

For reporting.

Settings.xml
There are two locations where a settings.xml file may live:

The Maven install: $M2_HOME/conf/settings.xml

A user’s install: ${user.home}/.m2/settings.xml

The former settings.xml are also called global settings, the latter settings.xml are referred to as user settings. If both files exists, their contents gets merged, with the user-specificsettings.xml being dominant.

If you try to add artifactory setting to point to shared central repository[like artifactory], you need to specifically mention maven central repository to download artifacts that are not in the shared central repository. Please see below how explicitly I have added the maven central repository setting in the below setting.xml file.

The need to have proxy(internet proxy setting) in Maven Setting.xml file.
In corporate environment we generally have proxy. Setting the proxy in the setting.xml will solve the issue where you see that org.apache.maven related plugins are not downloadable. Ensure below setting in the setting.xml file between tag. Also ensure resolve artifact feature is not enabled in the current 4.3 version artifactory (oss) as it doesn’t work out… Use only the setting.xml file on the server (global configuration) to do the settings.

 

[Set the server details in your Maven] we do it Nolio… remote scripts for moving the war files to remote servers.]

 

 

Versioning

1) Major.Minor.Build.Snapshot(this represents a snapshot of the build which is underdevelopment) maven always looks for latest version from the repository if you referencing snapshot.

Although, In case of SNAPSHOT, Maven automatically fetches the latest SNAPSHOT on daily basis. You can force maven to download latest snapshot build using -U switch to any maven command.

2) Major.Minor.Build.DateTime(release version is the final version which is released to production).Maven will never download a newer release version

Deployment Automation with Maven

Plugin

maven-release-plugin is configured to automate the deployment process.

This is the plugin used to deploy the application.

Create and Install a maven build plugin.

package sample.plugin;

import org.apache.maven.plugin.AbstractMojo;

import org.apache.maven.plugin.MojoExecutionException;

import org.apache.maven.plugins.annotations.Mojo;

@Mojo( name = “sayhi”)

public class GreetingMojo extends AbstractMojo

{

public void execute() throws MojoExecutionException

{

getLog().info( “Hello, world.” );

}

}

§ The class org.apache.maven.plugin.AbstractMojo provides most of the infrastructure required to implement a mojo except for the execute method.

§ The annotation “@Mojo” is required and control how and when the mojo is executed.

§ The execute method can throw two exceptions:

§ org.apache.maven.plugin.MojoExecutionException if an unexpected problem occurs. Throwing this exception causes a “BUILD ERROR” message to be displayed.

§ org.apache.maven.plugin.MojoFailureException if an expected problem (such as a compilation failure) occurs. Throwing this exception causes a “BUILD FAILURE” message to be displayed.

§ The getLog method (defined in AbstractMojo) returns a log4j-like logger object which allows plugins to create messages at levels of “debug”, “info”, “warn”, and “error”. This logger is the accepted means to display information to the user. Please have a look at the section Retrieving the Mojo Logger for a hint on its proper usage.

Next to mojo class, one should create a POM file.

groupId This is the group ID for the plugin, and should match the common prefix to the packages used by the mojos
artifactId This is the name of the plugin
version This is the version of the plugin
packaging This should be set to “maven-plugin”
dependencies A dependency must be declared to the Maven Plugin Tools API to resolve “AbstractMojo” and related classes

 

Leave a Reply

Your email address will not be published. Required fields are marked *