Gili
Gili

Reputation: 90180

How do I look up a MavenProject?

How do I programmatically construct a MavenProject instance (not the current project) given its groupId, artifactId, version, etc?

UPDATE: I'm trying to create a patch for http://jira.codehaus.org/browse/MDEP-322. I believe the maven-dependency-plugin depends on Maven 2.x so I can't use any Maven 3.x APIs.

Upvotes: 0

Views: 986

Answers (1)

nonVirtualThunk
nonVirtualThunk

Reputation: 2852

How you would go about doing this depends on whether you want to construct the project from an artifact in your local repository or from a pom file on your hard drive. Either way, you'll need to get a ProjectBuilder, which you can do like so in a Mojo:

/** @component role = "org.apache.maven.project.ProjectBuilder" */
protected ProjectBuilder m_projectBuilder;

If you want to build from an artifact in your local repo, you'll also need:

/** @parameter expression="${localRepository}" */
protected ArtifactRepository m_localRepository;

Once you have that, you can construct a MavenProject from an artifact from your local repository:

  //Construct the artifact representation
Artifact artifact = 
    new DefaultArtifact(groupId,artifactId,version,scope,type,classifier,new DefaultArtifactHandler());
  //Resolve it against the local repository
artifact = m_localRepository.find(artifact);
  //Create a project building request
ProjectBuildingRequest request = new DefaultProjectBuildingRequest();
  //Build the project and get the result
MavenProject project = m_projectBuilder.build(artifact,request).getProject();

Or from a pom file:

File pomFile = new File("path/to/pom.xml");
ProjectBuildingRequest request = new DefaultProjectBuildingRequest();
MavenProject project = m_projectBuilder.build(pomFile,request).getProject();

Upvotes: 1

Related Questions