siom
siom

Reputation: 1807

Retrieve list of a module's dependencies with a maven plugin MOJO

I am developing a maven plugin that uses javassist. In order to load classes that should be manipulated with javassist I have to setup the classpath manually:

classPool.appendClassPath("/path/to/the/file.jar");

Is there a way to retrieve the list of all dependencies for the current module the maven plugin is running in? As you can specify the dependencies for the module that plugin runs in with the <dependencies/> element there should be some way to retrieve them inside my MOJO.

Example: Let's assume I have the following pom.xml where my plugin is defined:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>my-group-id</groupId>
        <artifactId>my-parent-artifact-id</artifactId>
        <version>0.4.1-SNAPSHOT</version>
    </parent>
    <artifactId>my-artifact-id</artifactId>

    <dependencies>
        <dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-math3</artifactId>
                <version>3.4</version>
            </dependency>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>my-group-id</groupId>
                <artifactId>my-maven-plugin</artifactId>
                <version>${project.version}</version>
                ...
            </plugin>
        </plugins>
    </build>
</project>

Now inside my MOJO of my-maven-plugin I want to retrieve the file location for the artifact commons-math3 that is declared inside the <dependencies/> section of the module. In general I also want to retrieve the <dependencies/> from the parent module and all of their transitive dependencies.

Upvotes: 0

Views: 1792

Answers (1)

siom
siom

Reputation: 1807

Meanwhile I have found the solution myself:

/**
 * @goal cmp
 * @phase verify
 */
public class JApiCmpMojo extends AbstractMojo {
    /**
     * @parameter default-value="${project}"
     */
    private org.apache.maven.project.MavenProject mavenProject;
    ...
    private void setUpClassPathUsingMavenProject(JarArchiveComparatorOptions comparatorOptions) throws MojoFailureException {
        notNull(mavenProject, "Maven parameter mavenProject should be provided by maven container.");
        Set<Artifact> dependencyArtifacts = mavenProject.getDependencyArtifacts();
        for (Artifact artifact : dependencyArtifacts) {
            ...
        }
    }
}

The MavenProject instance you get from the container has the method getDependencyArtifacts(). Each artifact in this set has a method getFile() that retuns a java.io.File object.

Upvotes: 1

Related Questions