Java – programmatically resolve Maven dependencies outside the plug-in – get the repository systemsession and repository system
Maybe this will be a bigger task than I thought at first, but no matter I try to load a maven project from a file and solve its dependencies I have two codes, but I lack some object references I need; Specifically, I need to get the instances of repository systemsession and repository system Any tips?
Note: I marked this issue with Maven plugin, but this is not a maven plugin I am happy to ask Maven 3 (think I already have...)
Here is my code so far:
Build Maven project:
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; }
Resolve 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 know this may be an unusual requirement, maybe I should just discard what I'm doing and wrap it as a plug-in... But I just want to finish it now! Thank you in advance
Solution
Try jcabi aether, which is a wrapper from Apache aether from sonatype:
final File repo = this.session.getLocalRepository().getBasedir(); final Collection<Artifact> deps = new Aether(this.getProject(),repo).resolve( new DefaultArtifact("junit","junit-dep","","jar","4.10"),JavaScopes.RUNTIME );
If you are an external Maven plugin:
final File repo = new File(System.getProperty("java.io.tmpdir"),"my-repo"); final MavenProject project = new MavenProject(); project.setRemoteArtifactRepositories( Arrays.asList( new RemoteRepository( "maven-central","default","http://repo1.maven.org/maven2/" ) ) ); final Collection<Artifact> deps = new Aether(project,JavaScopes.RUNTIME );