Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0
Table of Contents
indent20px
styledisc

Mojo Developer Cookbook

 This page contains code snippets demonstrating commonly used tasks when writing Maven plug-ins. There are no guarantees that these are the 'right' way to do things, but they have worked at least once for the author(s).

Commonly used components 

These components are commonly used, also in the following snippets.

The maven project, or the effective pom.

With the MavenProject object, you would be able to access a lot of things ( that is if you don't know the @component or @expression for it.

Code Block
/** @parameter default-value="${project}" */
private org.apache.maven.project.MavenProject mavenProject;




Creating a maven project


Code Block
/** @component */
private MavenProjectBuilder mavenProjectBuilder;




The dependencies declared in your plugin.


Code Block
/** @parameter default-value="${plugin.artifacts}" */
private java.util.List pluginArtifacts;




For accessing artifacts and repositories


Code Block
/** @component */
private org.apache.maven.artifact.factory.ArtifactFactory artifactFactory;

/** @component */
private org.apache.maven.artifact.resolver.ArtifactResolver resolver;

/**@parameter default-value="${localRepository}" */
private org.apache.maven.artifact.repository.ArtifactRepository localRepository;

/** @parameter default-value="${project.remoteArtifactRepositories}" */
private java.util.List remoteRepositories;

/** @parameter default-value="${project.distributionManagementArtifactRepository}" */
private ArtifactRepository deploymentRepository;




For resolving artifact verions


Code Block
/** @component */
private ArtifactMetadataSource artifactMetadataSource;



Deploying and installing


Code Block
/** @component */
private ArtifactDeployer deployer;

/** @component */
private ArtifactInstaller installer;


You may want to add @required and @readonly, but I dropped them to keep it short.

The ones listed here are the common ones. But you can use other properties in default-value="${...}". See MavenPropertiesGuide for more info...

Dependencies for Components

When developing with the above mentioned commonly used components you will
want to add the following dependencies to your pom.xml:

Code Block
<dependency>
	<groupId>org.apache.maven</groupId>
	<artifactId>maven-artifact</artifactId>
	<version>2.0</version>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupId>org.apache.maven</groupId>
	<artifactId>maven-project</artifactId>
	<version>2.0</version>
	<scope>compile</scope>
</dependency>




Storing Properties

 If you want to store properties in your mojo and make those properties accessible to other elements ( such as plugins, resource files, etc ). You can do something like this

Code Block
mavenProject.getProperties().put( "my.mojo.property", "my mojo value" )


This is like adding to your pom

Code Block
xml
xml
<project>
  ...
  <properties>
    <my.mojo.property>my mojo value</my.mojo.property>
  </properties>
</project>




Creating and resolving an artifact

 To create an artifact, use an ArtifactFactory.

Code Block
artifact = artifactFactory.createArtifactWithClassifier(groupId, artifactId, version, type, classifier);


An artifact doesn't help you much until it's resolved (using an ArtifactResolver). This resolving process is not transitive!

Code Block
resolver.resolve( artifact, remoteRepositories, localRepository );


Now you get the artifact file (in the local repository):

Code Block
File artifactFile = artifact.getFile();



Resolving an artifact from a version range

First you need to create the version range:

Code Block
versionRange = VersionRange.createFromVersionSpec(versionSpecification);

Then you need to create the artifact from the version range:

Code Block
artifact = artifactFactory.createDependentArtifact(groupId, artifactId, versionRange, type, classifier, scope);
// or
artifact = artifactFactory.createExtensionArtifact(groupId, artifactId, versionRange);
// or
artifact = artifactFactory.createPluginArtifact(groupId, artifactId, versionRange);

Once you have the artifact with version range you use the ArtifactMetadataSource to retrieve the versions:

Code Block
List/*<ArtifactVersion>*/ versions = artifactMetatdataSource.retrieveAvailableVersions(artifact, localRepository, remoteRepository);

Then you can parse the list of versions and find the version that you are after (for example using versionRange.matchVersion) and then create a new artifact using tha version.


Resolving transitively

You need a MavenProject. If you don't have (the right) one, you can create it with just a groupId:artifactId:version:

Code Block
Artifact pomArtifact = artifactFactory.createArtifact(groupId, artifactId, version, classifier, "pom");
MavenProject pomProject = mavenProjectBuilder.buildFromRepository( pomArtifact, remoteRepositories, localRepositories );


Now you can use the ArtifactResolver to resolve transitively.

Code Block
Set artifacts = pomProject.createArtifacts( this.factory, null, null);
ArtifactFilter filter = ...
ArtifactResolutionResult arr = resolver.resolveTransitively(artifacts, pomArtifact, pomProject.getManagedVersionMap(), local, remoteRepos, source, filter);
Set result = arr.getArtifacts();


The filter is optional, and limits the resolving. Possible filters are:

  • ScopeArtifactFilter
  • InclusionArtifactFilter
  • ExclusionArtifactFilter
  • TypeArtifactFilter
  • AndArtifactFilter (to combine them)
  • or create your own, by implementing ArtifactFilter

Running external commands

Use CommandLine and CommandLineUtils from org.codehaus.plexus.util.cli

Code Block
CommandLine cl = new CommandLine("command");
cl.addArguments( new String[] { "arg1", "arg2", "arg3" } );
InputStream input = ...
StreamConsumer output = ...
StreamConsumer error = ...
int returnValue = CommandLineUtils.executeCommandLine(cl, input, output, error);


The input parameter is optional. For the output and error StreamConsumers, you can use CommandLineUtils.StringStreamConsumer which captures the output
in a String.

Installing and deploying artifacts

If you need want to install or deploy an artifact as part of a project build, you can add them to the MavenProject and they will be picked up in the install or deploy phase.

Code Block
project.getArtifact().setFile(file) // for the main artifact
projectHelper.attachArtifact(project, type, classifier, file) // for attached artifacts


If you install/deploy in a standalone goal, or you need to install/deploy an artifact that is not part of the project being built, you can use the ArtifactInstaller or ArtifactDeployer.

Code Block
Artifact artifact = artifactFactory.createArtifactWithClassifier(groupId, artifactId, version, type, classifier);
installer.install(file, artifact, localRepository); // to install
deployer.deploy(file, artifact, deploymentRepository, localRepository); // to deploy (includes the install)




Creating an ArtifactRepository

Usually an artifact repository will be injected into your mojo. Should you need to create one yourself, you will need an ID, a URL and a layout.

Code Block
ArtifactRepository repo = new DefaultArtifactRepository( "repositoryId", "http://my.repository.url", new DefaultRepositoryLayout() ); // use LegacyRepositoryLayout for an m1 repo&nbsp;




Accessing the Plexus container

If you want access to the container, for doing your own component lookups, implement the org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable interface

Code Block
public void contextualize( Context context ) throws ContextException {	container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );}

So if you want to lookup a component, you can do something like this

Code Block
Object myComponent = container.lookup( role, roleHint, container.getLookupRealm() );

Getting dependency artifact path

In some cases you may need to get the path of a jar artifact from a Dependency. This is how you can do it:

Code Block
Set artifacts = project.getDependencyArtifacts();
for (Iterator artifactIterator = artifacts.iterator(); artifactIterator.hasNext();) {
  Artifact artifact = (Artifact) artifactIterator.next();
  if (artifact.getGroupId().equals(dependency.getGroupId()) && artifact.getArtifactId().equals(dependency.getArtifactId())) {
    return artifact.getFile().getPath();
  }
}


In this snippet, project is the MavenProject instance of the project (@parameter default-value="${project}") and dependency is instance of Dependency (@parameter default-value="${project.dependencies}).