Получить зависимости WAR Artifact с помощью Maven 2 API - PullRequest
4 голосов
/ 20 февраля 2012

Я нашел несколько постов, касающихся вопроса поиска артефактов, однако ответы, похоже, не работают в моем конкретном случае.

Я пишу плагин, который поможет с генерацией skinny war EAR , и я запускаю плагин, который я написал для моего модуля EAR maven. В коде плагина я дошел до стадии, на которой я хочу иметь возможность получить зависимости / артефакты зависимостей WAR - в настоящее время они не приходят ни с чем из того, что я пробовал. Я предполагаю, что это потому, что даже запуск зависимости: дерево в моем модуле EAR не включает их, они не являются «транзитивными» зависимостями.

// Neither of the two below return WAR transitive dependencies, just the WARs
project.getDependencies()
project.getArtifacts()

Мой новый подход в настоящее время таков:

ArtifactRepository localRepository = project.getDistributionManagementArtifactRepository();
List remoteRepositories = project.getRemoteArtifactRepositories();

ResolutionGroup resolutionGroup = artifactMetadataSource.retrieve(warArtifact, localRepository, remoteRepositories);
Set<Artifact> artifactDependencies = resolutionGroup.getArtifacts();

(Примечание. Это использует компонентный объект ArtifactMetadataSource проекта и зависимости maven-dependency-plugin:2.4)

Это не работает. Набор artifactDependencies пуст. Теперь это должно быть возможно, потому что запуск mvn dependency:tree в каталоге для модуля warArtifact работает нормально, как и ожидалось.

Есть идеи?

1 Ответ

4 голосов
/ 23 февраля 2012

У меня наконец есть ответ. По общему признанию это не отвечает должным образом на мой оригинальный вопрос, но это то, с чем я ушел.

Причина, по которой он не полностью отвечает моему первоначальному сообщению: требуется Maven 3.

Вот это в любом случае для тех, кому интересно:

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.sonatype.aether.RepositorySystem;
import org.sonatype.aether.RepositorySystemSession;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.collection.CollectRequest;
import org.sonatype.aether.graph.Dependency;
import org.sonatype.aether.graph.DependencyNode;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.resolution.DependencyRequest;
import org.sonatype.aether.util.artifact.DefaultArtifact;
import org.sonatype.aether.util.graph.PreorderNodeListGenerator;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @goal findShareables
 * @phase process-resources
 */
@SuppressWarnings("unchecked")
public class ShareableJarsInWarsExtractor extends AbstractMojo
{
    // ...

    /**
     * The MavenProject object.
     *
     * @parameter expression="${project}"
     * @readonly
     */
    private MavenProject project;

    /**
     * The entry point to Aether, i.e. the component doing all the work.
     *
     * @component
     */
    private RepositorySystem repoSystem;

    /**
     * The current repository/network configuration of Maven.
     *
     * @parameter default-value="${repositorySystemSession}"
     * @readonly
     */
    private RepositorySystemSession repoSession;

    /**
     * The project's remote repositories to use for the resolution of plugins and their dependencies.
     *
     * @parameter default-value="${project.remotePluginRepositories}"
     * @readonly
     */
    private List<RemoteRepository> remoteRepos;


    public void execute() throws MojoExecutionException
    {
        Artifact projectArtifact = getProjectArtifact();
        List<Dependency> projectDependencies = getArtifactsDependencies(projectArtifact);

        for (Dependency d : projectDependencies)
        {
            if (d.getArtifact() != null && "war".equals(d.getArtifact().getExtension()))
            {
                List<Dependency> warDependencies = getArtifactsDependencies(d.getArtifact());
                // I now have all of the WAR's dependencies!! Hooray!

                // ...
            }
        }

        // ...
    }


    private List<Dependency> getArtifactsDependencies(Artifact a)
    {
        List<Dependency> ret = new ArrayList<Dependency>();

        // Note: I get the POM artifact, not the WAR or whatever.
        DefaultArtifact pomArtifact = new DefaultArtifact(a.getGroupId(), a.getArtifactId(), "pom", a.getVersion());
        CollectRequest collectRequest = new CollectRequest();
        collectRequest.setRoot(new Dependency(pomArtifact, "compile"));
        collectRequest.setRepositories(remoteRepos);

        try
        {
            DependencyNode node = repoSystem.collectDependencies(repoSession, collectRequest).getRoot();
            DependencyRequest projectDependencyRequest = new DependencyRequest(node, null);

            repoSystem.resolveDependencies(repoSession, projectDependencyRequest);

            PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
            node.accept(nlg);

            ret.addAll(nlg.getDependencies(true));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return ret;
    }


    private Artifact getProjectArtifact()
    {
        // Todo: There must be a better way!
        return new DefaultArtifact(project.getArtifact().toString());
    }


    // ...
}

Мой POM определяет следующие зависимости:

        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>3.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-model</artifactId>
            <version>3.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>3.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-artifact</artifactId>
            <version>3.0.4</version>
        </dependency>
...