G_hi3 G_hi3 - 18 days ago 5
Java Question

Find the path to the main artifact in a Maven plugin

I'm developing a Maven plugin to automatically install the JAR on a server. The first step for me should be to find the compiled JAR and move it to the server, but how do I find my JAR?

My first attempt was:

public class MyMojo extends AbstractMojo {
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
String workingPath = System.getProperty("user.dir");
File targetDir = new File(workingPath + File.separatorChar + "target");

for (File f : targetDir.listFiles()) {
if (f.isFile() && f.getName().endsWith(".jar") {
System.out.println("Found jar " + f.getName());
}
}
}
}


But I don't want to use a fixed directory "target". Is there any way to know where the jar will be built?

Answer

Yes, the simple way to do this is to inject the MavenProject that is currently being built, and retrieve the file corresponding to its artifact, as returned by getArtifact(). This works whatever the packaging of the project (jar, war, etc.), or where the artifact was actually generated.

@Mojo(name = "foo")
public class MyMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true, required = true)
    private MavenProject project;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        // this is the main artifact file
        File file = project.getArtifact().getFile();
        getLog().info(file.toString());
    }

}

This declares the goal called "foo". It is injected the value ${project}, which is evaluated to the current Maven project by the PluginParameterExpressionEvaluator.

Your Maven plugin will need to have a dependency on maven-plugin-annotations (for the @Parameter and @Mojo annotation), and on maven-core for the MavenProject:

<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-core</artifactId>
  <version>3.3.9</version>
</dependency>
<dependency>
  <groupId>org.apache.maven.plugin-tools</groupId>
  <artifactId>maven-plugin-annotations</artifactId>
  <version>3.5</version>
  <scope>provided</scope>
</dependency>

Of course, this requires that the artifact for the project was actually built, which is to say that the plugin has to run after the package phase; otherwise there is no file to the artifact.

Comments