1

How can I in an very easy way retrieve all direct and transitive dependencies for a given Maven POM in my own Java program?

I aware of the existing questions on Stackoverflow, especially the one using Ivy to resolve the dependencies. I am looking for a solution using Maven, which is able also to resolve the transitive dependencies.

Oliver
  • 3,815
  • 8
  • 35
  • 63
  • 1
    The first question is: For what purpose? Can you explain what is the intention or the problem you are trying to solve? – khmarbaise Dec 13 '20 at 14:29
  • I have an Java application, which should analyse the dependency tree of a given POM. The application is part of our release tooling for jQAssistant. – Oliver Dec 18 '20 at 09:37

2 Answers2

2

If you need this during a Maven build, you can easily access it in a Maven plugin using project.getDependencies().

If you have a standalone Java program, you can use Maven resolver or the older Aether libraries to do the resolution.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142
0

I was now able to solve the problem by using JBoss Shrinkwrap.

Here is a code snipped similar to the one I now use in my tools:

MavenStrategyStage resolve = 
    Maven.configureResolver()
         // do not consult Maven Central or any other repository
         .workOffline()
         // import the configuration of the given settings.xml
         .fromFile(homeDir + "/jqa-release-environment/maven-settings.xml")
         // load the POM you would like to analyse
         .loadPomFromFile(pomFile)
         .importCompileAndRuntimeDependencies()
         .importRuntimeAndTestDependencies()
         .resolve();

MavenWorkingSession mavenWorkingSession = 
    ((MavenWorkingSessionContainer) resolve).getMavenWorkingSession();

List<MavenDependency> dependencies = new ArrayList<>();
dependencies.addAll(mavenWorkingSession.getDependenciesForResolution());
dependencies.addAll(mavenWorkingSession.getDependencyManagement());

To be able to use Shrinkwrap, I added the following dependencies to my POM.

<dependency>
    <groupId>org.jboss.shrinkwrap.resolver</groupId>
    <artifactId>shrinkwrap-resolver-depchain</artifactId>
    <type>pom</type>
    <version>3.1.4</version>
</dependency>
<dependency>
    <groupId>org.jboss.shrinkwrap.resolver</groupId>
    <artifactId>shrinkwrap-resolver-impl-maven</artifactId>
    <version>3.1.4</version>
</dependency>
<dependency>
    <groupId>org.jboss.shrinkwrap.resolver</groupId>
    <artifactId>shrinkwrap-resolver-api-maven</artifactId>
    <version>3.1.4</version>
</dependency>
Oliver
  • 3,815
  • 8
  • 35
  • 63