Programmatically resolving Maven dependencies outside of a plugin - get RepositorySystemSession and RepositorySystem

Ed . picture Ed . · Aug 3, 2012 · Viewed 18.1k times · Source

Maybe this is going to be a larger task than I had originally thought, but regardless, I'm trying to load a MavenProject from a file and then resolve its dependencies. I've got the code for both bits but I'm missing some object references that I need; specifically I need to get instances of RepositorySystemSession and RepositorySystem. Any tips?

Note: I have tagged this question with , but this is not a Maven plugin. I am happy to mandate Maven 3 (think I already have anyway..)

Here's the code I have so far:

Constructing the MavenProject:

public static MavenProject loadProject(File pomFile) throws Exception
{
    MavenProject ret = null;
    MavenXpp3Reader mavenReader = new MavenXpp3Reader();

    if (pomFile != null && pomFile.exists())
    {
        FileReader reader = null;

        try
            {
            reader = new FileReader(pomFile);
            Model model = mavenReader.read(reader);
            model.setPomFile(pomFile);

            ret = new MavenProject(model);
        }
        finally
        {
            // Close reader
        }
    }

    return ret;
}

Resolving dependencies:

public static List<Dependency> getArtifactsDependencies(MavenProject project, String dependencyType, String scope) throws Exception
{    
    DefaultArtifact pomArtifact = new DefaultArtifact(project.getId());

    RepositorySystemSession repoSession = null; // TODO
    RepositorySystem repoSystem = null; // TODO

    List<RemoteRepository> remoteRepos = project.getRemoteProjectRepositories();
    List<Dependency> ret = new ArrayList<Dependency>();

    Dependency dependency = new Dependency(pomArtifact, scope);

    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(dependency);
    collectRequest.setRepositories(remoteRepos);

    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));

    return ret;
}

I realise this might be an unusual request, maybe I should just scrap what I was trying to do and wrap it as a plugin...but I kind of just want to finish what I started now! Thanks in advance.

Answer

khmarbaise picture khmarbaise · Aug 3, 2012

I would recommend to read the information about Aether lib which is exactly is for such kind of purposes.

Note: Aether was previousely developed at Sonatype, but has since moved to Eclipse.