md_5
md_5

Reputation: 630

Programmatic builds using Maven 3 API

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?

Upvotes: 10

Views: 2481

Answers (3)

JP Moresmau
JP Moresmau

Reputation: 7403

Internet searches for how to do Maven builds using the API always lead me here, so I'd like to document how I've solved this issue. Do not use DefaultMaven directly. Instead, use the maven-verifier project:

<dependency>
    <groupId>org.apache.maven.shared</groupId>
    <artifactId>maven-verifier</artifactId>
    <version>1.6</version>
</dependency>

Then you can use the Verifier class to build a project. The only catch is to pass the proper environment variable:

String baseDir = "<root path of the maven project you want to build>";
Map<String,String> env=new HashMap<>();
env.put("maven.multiModuleProjectDirectory", baseDir);

try {
    Verifier v=new Verifier(baseDir);
    v.executeGoals(Arrays.asList("clean","package"),env);
} catch (Exception e) {
    e.printStackTrace();
}

This resulted for me in the project being built, and a log.txt file being created in baseDir with the output of maven.

Hope this helps!

Upvotes: 1

bmargulies
bmargulies

Reputation: 100196

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.

Upvotes: 3

cowls
cowls

Reputation: 24354

I've never actually used this API, looks interesting though.

I can't see where you are setting your goals to run?

You might need to call: setGoals on the Maven Execution Request.

http://maven.apache.org/ref/3.0.3/maven-core/apidocs/org/apache/maven/execution/DefaultMavenExecutionRequest.html#setGoals%28java.util.List%29

Upvotes: 0

Related Questions