Reputation: 598
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?
Upvotes: 2
Views: 1668
Reputation: 44965
You could use the value of the predefined variables project.build.directory
, project.build.finalName
and project.packaging
to build the path of your archive as default value of a parameter of your plugin, something like:
public class MyMojo extends AbstractMojo {
/**
* @parameter default-value="${project.build.directory}/${project.build.finalName}.${project.packaging}"
*/
private String archivePath;
public void execute() throws MojoExecutionException {
File archive = new File(archivePath);
...
}
}
Upvotes: 1
Reputation: 137084
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.
Upvotes: 3