Alex Rivera | Logout

Programmatic builds using Maven 3 API

Asked 2013-01-11T10:10:43.867
10

Before you ask why I can just spawn a process to execute mvn, I wish to execute a Maven build through the Maven API, so that I can gather info on what goes on in the build, the artifacts produced etc etc. After depending on org.apache.maven:maven-core:jar:3.0.4, I have written the following method in an attempt to do such a thing:

public static void build(File directory, File pom) {
    Maven maven = new DefaultMaven();
    MavenExecutionRequest exec = new DefaultMavenExecutionRequest();
    exec.setBaseDirectory(directory);
    exec.setPom(pom);
    MavenExecutionResult result = maven.execute(exec);
    MavenProject proj = result.getProject();
    Artifact art = proj.getArtifact();
    System.out.println(art);
}

However this code fails at maven.execute due to null pointer exceptions. These null pointer exceptions are basically everywhere due to private fields in DefaultMaven not being initialized. They are all annotated with @Required, so I am guessing this is something to do with Plexus.

How can I successfully use Maven to execute such a build?

Edit
Report

1 Answer

3

You'll want to use the actual Maven embedding API:

http://maven.apache.org/ref/3.0/maven-embedder/apidocs/index.html

To see examples, look towards the open source of M2Eclipse.

Now, this component is not really very well-named. It's actually a convenience wrapper aimed at making an CLI. so, what you'll want to do is read the source of it.

answered 2013-01-11T12:14:26.190

Your Answer