org.eclipse.aether.collection.CollectRequest Java Examples

The following examples show how to use org.eclipse.aether.collection.CollectRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Resolver.java    From buck with Apache License 2.0 6 votes vote down vote up
private ImmutableMap<String, Artifact> getRunTimeTransitiveDeps(Iterable<Dependency> mavenCoords)
    throws RepositoryException {

  CollectRequest collectRequest = new CollectRequest();
  collectRequest.setRequestContext(JavaScopes.RUNTIME);
  collectRequest.setRepositories(repos);

  for (Dependency dep : mavenCoords) {
    collectRequest.addDependency(dep);
  }

  DependencyFilter filter = DependencyFilterUtils.classpathFilter(JavaScopes.RUNTIME);
  DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, filter);

  DependencyResult dependencyResult = repoSys.resolveDependencies(session, dependencyRequest);

  ImmutableSortedMap.Builder<String, Artifact> knownDeps = ImmutableSortedMap.naturalOrder();
  for (ArtifactResult artifactResult : dependencyResult.getArtifactResults()) {
    Artifact node = artifactResult.getArtifact();
    knownDeps.put(buildKey(node), node);
  }
  return knownDeps.build();
}
 
Example #2
Source File: ArtifactHelper.java    From LicenseScout with Apache License 2.0 6 votes vote down vote up
/**
 * Calculates the set of transitive dependencies of the passed artifacts.
 * 
 * @param repositoryParameters
 * @param artifacts
 * @param artifactScope
 * @return a list of File locations where the JARs of the dependencies are located in the local file system
 * @throws DependencyResolutionException
 */
public static List<File> getDependencies(final IRepositoryParameters repositoryParameters,
                                         final List<ArtifactItem> artifacts, final ArtifactScope artifactScope)
        throws DependencyResolutionException {
    final RepositorySystem system = repositoryParameters.getRepositorySystem();
    final RepositorySystemSession session = repositoryParameters.getRepositorySystemSession();
    final DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter(artifactScope.getScopeValue());
    final Set<File> artifactFiles = new HashSet<>();
    for (final ArtifactItem artifactItem : artifacts) {
        Artifact artifact = createDefaultArtifact(artifactItem);
        final CollectRequest collectRequest = new CollectRequest();
        collectRequest.setRoot(new Dependency(artifact, artifactScope.getScopeValue()));
        collectRequest.setRepositories(repositoryParameters.getRemoteRepositories());
        final DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFlter);
        final DependencyResult dependencyResult = system.resolveDependencies(session, dependencyRequest);
        final List<ArtifactResult> artifactResults = dependencyResult.getArtifactResults();
        for (final ArtifactResult artifactResult : artifactResults) {
            artifactFiles.add(artifactResult.getArtifact().getFile());
        }
    }
    return new ArrayList<>(artifactFiles);
}
 
Example #3
Source File: NbRepositorySystem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public CollectResult collectDependencies(RepositorySystemSession session, CollectRequest request) throws DependencyCollectionException {
    DefaultRepositorySystemSession cloned = new DefaultRepositorySystemSession(session);
    DependencyGraphTransformer transformer = session.getDependencyGraphTransformer();
    //need to reset the transformer to prevent the transformation to happen and to it below separately.
    cloned.setDependencyGraphTransformer(null);
    CollectResult res = super.collectDependencies(cloned, request);
    CloningDependencyVisitor vis = new CloningDependencyVisitor();
    res.getRoot().accept(vis);

    //this part copied from DefaultDependencyCollector
    try {
        DefaultDependencyGraphTransformationContext context =
                new DefaultDependencyGraphTransformationContext(session);
        res.setRoot(transformer.transformGraph(res.getRoot(), context));
    } catch (RepositoryException e) {
        res.addException(e);
    }

    if (!res.getExceptions().isEmpty()) {
        throw new DependencyCollectionException(res);
    }
    res.getRoot().setData("NB_TEST", vis.getRootNode());
    return res;
}
 
Example #4
Source File: ArtifactResolver.java    From migration-tooling with Apache License 2.0 6 votes vote down vote up
/**
 * Given a set of coordinates, resolves the transitive dependencies, and then returns the root
 * node to the resolved dependency graph. The root node is a sentinel node with direct edges
 * on the artifacts users declared explicit on.
 */
public DependencyNode resolveArtifacts(List<String> artifactCoords) {
  List<Dependency> directDependencies = createDirectDependencyList(artifactCoords);
  CollectRequest collectRequest =
      aether.createCollectRequest(directDependencies, managedDependencies);

  DependencyRequest dependencyRequest = aether.createDependencyRequest(collectRequest);
  DependencyResult dependencyResult;
  try {
    dependencyResult = aether.requestDependencyResolution(dependencyRequest);
  } catch (DependencyResolutionException e) {
    //FIXME(petros): This is very fragile. If one artifact doesn't resolve, no artifacts resolve.
    logger.warning("Unable to resolve transitive dependencies: " + e.getMessage());
    return null;
  }
  // root is a sentinel node whose direct children are the requested artifacts.
  return dependencyResult.getRoot();
}
 
Example #5
Source File: Maven.java    From bazel-deps with MIT License 6 votes vote down vote up
public static Set<Artifact> transitiveDependencies(Artifact artifact) {

    RepositorySystem system = newRepositorySystem();

    RepositorySystemSession session = newRepositorySystemSession(system);

    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(new Dependency(artifact, ""));
    collectRequest.setRepositories(repositories());

    CollectResult collectResult = null;
    try {
      collectResult = system.collectDependencies(session, collectRequest);
    } catch (DependencyCollectionException e) {
      throw new RuntimeException(e);
    }

    PreorderNodeListGenerator visitor = new PreorderNodeListGenerator();
    collectResult.getRoot().accept(visitor);

    return ImmutableSet.copyOf(
      visitor.getNodes().stream()
        .filter(d -> !d.getDependency().isOptional())
        .map(DependencyNode::getArtifact)
        .collect(Collectors.toList()));
  }
 
Example #6
Source File: MavenArtifactResolver.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Turns the list of dependencies into a simple dependency tree
 */
public DependencyResult toDependencyTree(List<Dependency> deps, List<RemoteRepository> mainRepos)
        throws BootstrapMavenException {
    DependencyResult result = new DependencyResult(
            new DependencyRequest().setCollectRequest(new CollectRequest(deps, Collections.emptyList(), mainRepos)));
    DefaultDependencyNode root = new DefaultDependencyNode((Dependency) null);
    result.setRoot(root);
    GenericVersionScheme vs = new GenericVersionScheme();
    for (Dependency i : deps) {
        DefaultDependencyNode node = new DefaultDependencyNode(i);
        try {
            node.setVersionConstraint(vs.parseVersionConstraint(i.getArtifact().getVersion()));
            node.setVersion(vs.parseVersion(i.getArtifact().getVersion()));
        } catch (InvalidVersionSpecificationException e) {
            throw new RuntimeException(e);
        }
        root.getChildren().add(node);
    }
    return result;
}
 
Example #7
Source File: DependencyResolver.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public List<File> resolveArtifactsAndDependencies(List<Artifact> artifacts) throws DependencyResolutionException {
    List<Dependency> dependencies = new ArrayList<Dependency>();

    for (Artifact artifact : artifacts) {
        dependencies.add(new Dependency(artifact, JavaScopes.RUNTIME));
    }

    CollectRequest collectRequest = new CollectRequest((Dependency) null, dependencies, repositories);
    DependencyFilter classpathFilter = DependencyFilterUtils.classpathFilter(JavaScopes.RUNTIME);
    DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFilter);
    DependencyResult result = system.resolveDependencies(session, dependencyRequest);

    List<File> files = new ArrayList<File>();

    for (ArtifactResult artifactResult : result.getArtifactResults()) {
        files.add(artifactResult.getArtifact().getFile());
    }

    return files;
}
 
Example #8
Source File: ExtensionDescriptorMojo.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private CollectRequest newCollectRequest(DefaultArtifact projectArtifact) throws MojoExecutionException {
    final ArtifactDescriptorResult projectDescr;
    try {
        projectDescr = repoSystem.readArtifactDescriptor(repoSession,
                new ArtifactDescriptorRequest()
                        .setArtifact(projectArtifact)
                        .setRepositories(repos));
    } catch (ArtifactDescriptorException e) {
        throw new MojoExecutionException("Failed to read descriptor of " + projectArtifact, e);
    }

    final CollectRequest request = new CollectRequest().setRootArtifact(projectArtifact)
            .setRepositories(repos)
            .setManagedDependencies(projectDescr.getManagedDependencies());
    for (Dependency dep : projectDescr.getDependencies()) {
        if ("test".equals(dep.getScope())
                || "provided".equals(dep.getScope())
                || dep.isOptional()) {
            continue;
        }
        request.addDependency(dep);
    }
    return request;
}
 
Example #9
Source File: ClassLoaderResolverTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    classLoaderResolver = new ClassLoaderResolver(log, repositorySystem, repositorySystemSession, Collections.<RemoteRepository>emptyList());
    when(repositorySystem.collectDependencies(eq(repositorySystemSession), any(CollectRequest.class)))
            .thenReturn(new CollectResult(new CollectRequest()).setRoot(root));
    when(child.getDependency()).thenReturn(new Dependency(new DefaultArtifact(FOO,
            BAR,
            QUX,
            BAZ,
            FOO + BAR,
            Collections.<String, String>emptyMap(),
            new File(FOO + "/" + BAR)), QUX + BAZ));
    when(root.accept(any(DependencyVisitor.class))).then(new Answer<Void>() {
        public Void answer(InvocationOnMock invocationOnMock) {
            DependencyVisitor dependencyVisitor = invocationOnMock.getArgument(0);
            dependencyVisitor.visitEnter(child);
            dependencyVisitor.visitLeave(child);
            return null;
        }
    });
}
 
Example #10
Source File: DependencyDownloader.java    From go-offline-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Download a plugin, all of its transitive dependencies and dependencies declared on the plugin declaration.
 * <p>
 * Dependencies and plugin artifacts that refer to an artifact in the current reactor build are ignored.
 * Transitive dependencies that are marked as optional are ignored
 * Transitive dependencies with the scopes "test", "system" and "provided" are ignored.
 *
 * @param plugin the plugin to download
 */
public Set<ArtifactWithRepoType> resolvePlugin(Plugin plugin) {
    Artifact pluginArtifact = toArtifact(plugin);
    Dependency pluginDependency = new Dependency(pluginArtifact, null);
    CollectRequest collectRequest = new CollectRequest(pluginDependency, pluginRepositories);
    collectRequest.setRequestContext(RepositoryType.PLUGIN.getRequestContext());

    List<Dependency> pluginDependencies = new ArrayList<>();
    for (org.apache.maven.model.Dependency d : plugin.getDependencies()) {
        Dependency dependency = RepositoryUtils.toDependency(d, typeRegistry);
        pluginDependencies.add(dependency);
    }
    collectRequest.setDependencies(pluginDependencies);

    try {
        CollectResult collectResult = repositorySystem.collectDependencies(pluginSession, collectRequest);
        return getArtifactsFromCollectResult(collectResult, RepositoryType.PLUGIN);
    } catch (DependencyCollectionException | RuntimeException e) {
        log.error("Error resolving plugin " + plugin.getGroupId() + ":" + plugin.getArtifactId());
        handleRepositoryException(e);
    }
    return Collections.emptySet();
}
 
Example #11
Source File: CycleBreakerGraphTransformerTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCycleBreaking() throws DependencyResolutionException {
  RepositorySystem system = RepositoryUtility.newRepositorySystem();
  DefaultRepositorySystemSession session =
      RepositoryUtility.createDefaultRepositorySystemSession(system);

  // This dependencySelector selects everything except test scope. This creates a dependency tree
  // with a cycle of dom4j:dom4j:jar:1.6.1 (optional) and jaxen:jaxen:jar:1.1-beta-6 (optional).
  session.setDependencySelector(new ScopeDependencySelector("test"));

  session.setDependencyGraphTransformer(
      new ChainedDependencyGraphTransformer(
          new CycleBreakerGraphTransformer(), // This prevents StackOverflowError
          new JavaDependencyContextRefiner()));

  // dom4j:1.6.1 is known to have a cycle
  CollectRequest collectRequest = new CollectRequest();
  collectRequest.setRepositories(ImmutableList.of(RepositoryUtility.CENTRAL));
  collectRequest.setRoot(new Dependency(new DefaultArtifact("dom4j:dom4j:1.6.1"), "compile"));
  DependencyRequest request = new DependencyRequest(collectRequest, null);

  // This should not raise StackOverflowError
  system.resolveDependencies(session, request);
}
 
Example #12
Source File: LinkageCheckerRuleTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a dependency graph node resolved from {@code coordinates}.
 */
private DependencyNode createResolvedDependencyGraph(String... coordinates)
    throws RepositoryException {
  CollectRequest collectRequest = new CollectRequest();
  collectRequest.setRootArtifact(dummyArtifactWithFile);
  collectRequest.setRepositories(ImmutableList.of(RepositoryUtility.CENTRAL));
  collectRequest.setDependencies(
      Arrays.stream(coordinates)
          .map(DefaultArtifact::new)
          .map(artifact -> new Dependency(artifact, "compile"))
          .collect(toImmutableList()));
  DependencyNode dependencyNode =
      repositorySystem.collectDependencies(repositorySystemSession, collectRequest).getRoot();

  DependencyRequest dependencyRequest = new DependencyRequest();
  dependencyRequest.setRoot(dependencyNode);
  DependencyResult dependencyResult =
      repositorySystem.resolveDependencies(repositorySystemSession, dependencyRequest);

  return dependencyResult.getRoot();
}
 
Example #13
Source File: DependencyResolver.java    From start.spring.io with Apache License 2.0 6 votes vote down vote up
static List<String> resolveDependencies(String groupId, String artifactId, String version,
		List<BillOfMaterials> boms, List<RemoteRepository> repositories) {
	DependencyResolver instance = instanceForThread.get();
	List<Dependency> managedDependencies = instance.getManagedDependencies(boms, repositories);
	Dependency aetherDependency = new Dependency(new DefaultArtifact(groupId, artifactId, "pom",
			instance.getVersion(groupId, artifactId, version, managedDependencies)), "compile");
	CollectRequest collectRequest = new CollectRequest((org.eclipse.aether.graph.Dependency) null,
			Collections.singletonList(aetherDependency), repositories);
	collectRequest.setManagedDependencies(managedDependencies);
	DependencyRequest dependencyRequest = new DependencyRequest(collectRequest,
			DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE, JavaScopes.RUNTIME));
	try {
		return instance.resolveDependencies(dependencyRequest).getArtifactResults().stream()
				.map(ArtifactResult::getArtifact)
				.map((artifact) -> artifact.getGroupId() + ":" + artifact.getArtifactId())
				.collect(Collectors.toList());
	}
	catch (DependencyResolutionException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example #14
Source File: ByteBuddyMojoTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    when(repositorySystem.collectDependencies(Mockito.<RepositorySystemSession>any(), Mockito.<CollectRequest>any())).thenReturn(new CollectResult(new CollectRequest()).setRoot(root));
    project = File.createTempFile(FOO, TEMP);
    assertThat(project.delete(), is(true));
    assertThat(project.mkdir(), is(true));
}
 
Example #15
Source File: Maven3DependencyTreeBuilder.java    From archiva with Apache License 2.0 5 votes vote down vote up
private void resolve( ResolveRequest resolveRequest )
{

    RepositorySystem system = mavenSystemManager.getRepositorySystem();
    RepositorySystemSession session = MavenSystemManager.newRepositorySystemSession( resolveRequest.localRepoDir );

    org.eclipse.aether.artifact.Artifact artifact = new DefaultArtifact(
        resolveRequest.groupId + ":" + resolveRequest.artifactId + ":" + resolveRequest.version );

    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot( new Dependency( artifact, "" ) );

    // add remote repositories
    for ( RemoteRepository remoteRepository : resolveRequest.remoteRepositories )
    {
        org.eclipse.aether.repository.RemoteRepository repo = new org.eclipse.aether.repository.RemoteRepository.Builder( remoteRepository.getId( ), "default", remoteRepository.getLocation( ).toString() ).build( );
        collectRequest.addRepository(repo);
    }
    collectRequest.setRequestContext( "project" );

    //collectRequest.addRepository( repo );

    try
    {
        CollectResult collectResult = system.collectDependencies( session, collectRequest );
        collectResult.getRoot().accept( resolveRequest.dependencyVisitor );
        log.debug("Collected dependency results for resolve");
    }
    catch ( DependencyCollectionException e )
    {
        log.error( "Error while collecting dependencies (resolve): {}", e.getMessage(), e );
    }



}
 
Example #16
Source File: Mojo.java    From capsule-maven-plugin with MIT License 5 votes vote down vote up
private Set<ArtifactResult> resolveDependencies(final Dependency dependency) {
	try {
		final CollectRequest collectRequest = new CollectRequest(new org.eclipse.aether.graph.Dependency(resolve(dependency).getArtifact(), ""), remoteRepos);
		return set(repoSystem.resolveDependencies(repoSession, new DependencyRequest(collectRequest, null)).getArtifactResults());
	} catch (final DependencyResolutionException e) {
		warn("\t\t[Resolve] Failed to resolve: [" + coords(dependency) + "]");
		return new HashSet<>();
	}
}
 
Example #17
Source File: ModifiedClassPathRunner.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private List<URL> resolveCoordinates(String[] coordinates) throws Exception {
	DefaultServiceLocator serviceLocator = MavenRepositorySystemUtils
			.newServiceLocator();
	serviceLocator.addService(RepositoryConnectorFactory.class,
			BasicRepositoryConnectorFactory.class);
	serviceLocator.addService(TransporterFactory.class, HttpTransporterFactory.class);
	RepositorySystem repositorySystem = serviceLocator
			.getService(RepositorySystem.class);
	DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
	LocalRepository localRepository = new LocalRepository(
			System.getProperty("user.home") + "/.m2/repository");
	session.setLocalRepositoryManager(
			repositorySystem.newLocalRepositoryManager(session, localRepository));
	CollectRequest collectRequest = new CollectRequest(null,
			Arrays.asList(new RemoteRepository.Builder("central", "default",
					"https://repo.maven.apache.org/maven2").build()));

	collectRequest.setDependencies(createDependencies(coordinates));
	DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, null);
	DependencyResult result = repositorySystem.resolveDependencies(session,
			dependencyRequest);
	List<URL> resolvedArtifacts = new ArrayList<>();
	for (ArtifactResult artifact : result.getArtifactResults()) {
		resolvedArtifacts.add(artifact.getArtifact().getFile().toURI().toURL());
	}
	return resolvedArtifacts;
}
 
Example #18
Source File: MavenAddonDependencyResolver.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Response<File[]> resolveResources(final AddonId addonId)
{
   RepositorySystem system = container.getRepositorySystem();
   Settings settings = getSettings();
   DefaultRepositorySystemSession session = container.setupRepoSession(system, settings);
   final String mavenCoords = toMavenCoords(addonId);
   Artifact queryArtifact = new DefaultArtifact(mavenCoords);
   session.setDependencyTraverser(new AddonDependencyTraverser(classifier));
   session.setDependencySelector(new AddonDependencySelector(classifier));
   Dependency dependency = new Dependency(queryArtifact, null);

   List<RemoteRepository> repositories = MavenRepositories.getRemoteRepositories(container, settings);

   CollectRequest collectRequest = new CollectRequest(dependency, repositories);
   DependencyResult result;
   try
   {
      result = system.resolveDependencies(session, new DependencyRequest(collectRequest, null));
   }
   catch (DependencyResolutionException e)
   {
      throw new RuntimeException(e);
   }
   List<Exception> collectExceptions = result.getCollectExceptions();
   Set<File> files = new HashSet<File>();
   List<ArtifactResult> artifactResults = result.getArtifactResults();
   for (ArtifactResult artifactResult : artifactResults)
   {
      Artifact artifact = artifactResult.getArtifact();
      if (isFurnaceAPI(artifact) ||
               (this.classifier.equals(artifact.getClassifier())
                        && !addonId.getName().equals(artifact.getGroupId() + ":" + artifact.getArtifactId())))
      {
         continue;
      }
      files.add(artifact.getFile());
   }
   return new MavenResponseBuilder<File[]>(files.toArray(new File[files.size()])).setExceptions(collectExceptions);
}
 
Example #19
Source File: MavenArtifactResolvingHelper.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
@Override
public Set<ArtifactSpec> resolveAll(Set<ArtifactSpec> specs) throws Exception {
    if (specs.isEmpty()) {

        return specs;
    }

    final CollectRequest request = new CollectRequest();
    request.setRepositories(this.remoteRepositories);

    specs.forEach(spec -> request
            .addDependency(new Dependency(new DefaultArtifact(spec.groupId(),
                    spec.artifactId(),
                    spec.classifier(),
                    spec.type(),
                    spec.version()),
                    "compile")));

    CollectResult result = this.system.collectDependencies(this.session, request);

    PreorderNodeListGenerator gen = new PreorderNodeListGenerator();
    result.getRoot().accept(gen);

    return gen.getNodes().stream()
            .filter(node -> !"system".equals(node.getDependency().getScope()))
            .map(node -> {
                final Artifact artifact = node.getArtifact();

                return new ArtifactSpec(node.getDependency().getScope(),
                        artifact.getGroupId(),
                        artifact.getArtifactId(),
                        artifact.getVersion(),
                        artifact.getExtension(),
                        artifact.getClassifier(),
                        null);
            })
            .map(this::resolve)
            .filter(x -> x != null)
            .collect(Collectors.toSet());
}
 
Example #20
Source File: RemotePluginLoader.java    From digdag with Apache License 2.0 5 votes vote down vote up
private static DependencyRequest buildDependencyRequest(List<RemoteRepository> repositories, String identifier, String scope)
{
    Artifact artifact = new DefaultArtifact(identifier);

    DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter(scope);

    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(new Dependency(artifact, scope));
    collectRequest.setRepositories(repositories);

    return new DependencyRequest(collectRequest, classpathFlter);
}
 
Example #21
Source File: AetherImporter.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Prepare an import with dependencies
 * <p>
 * This method does resolve even transient dependencies and also adds the
 * sources if requested
 * </p>
 */
public static AetherResult prepareDependencies ( final Path tmpDir, final ImportConfiguration cfg ) throws RepositoryException
{
    Objects.requireNonNull ( tmpDir );
    Objects.requireNonNull ( cfg );

    final RepositoryContext ctx = new RepositoryContext ( tmpDir, cfg.getRepositoryUrl (), cfg.isAllOptional () );

    // add all coordinates

    final CollectRequest cr = new CollectRequest ();
    cr.setRepositories ( ctx.getRepositories () );
    for ( final MavenCoordinates coords : cfg.getCoordinates () )
    {
        final Dependency dep = new Dependency ( new DefaultArtifact ( coords.toString () ), COMPILE );
        cr.addDependency ( dep );
    }

    final DependencyFilter filter = DependencyFilterUtils.classpathFilter ( COMPILE );
    final DependencyRequest deps = new DependencyRequest ( cr, filter );

    // resolve

    final DependencyResult dr = ctx.getSystem ().resolveDependencies ( ctx.getSession (), deps );
    final List<ArtifactResult> arts = dr.getArtifactResults ();

    if ( !cfg.isIncludeSources () )
    {
        // we are already done here
        return asResult ( arts, cfg, of ( dr ) );
    }

    // resolve sources

    final List<ArtifactRequest> requests = extendRequests ( arts.stream ().map ( ArtifactResult::getRequest ), ctx, cfg );

    return asResult ( resolve ( ctx, requests ), cfg, of ( dr ) );
}
 
Example #22
Source File: RepackageExtensionMojo.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private List<Dependency> obtainBomDependencies(final String urlLocation) {
    final Artifact artifact = downloadAndInstallArtifact(urlLocation).getArtifact();

    final Dependency dependency = new Dependency(artifact, JavaScopes.RUNTIME);

    final List<RemoteRepository> remoteRepositories = project.getRepositories().stream()
        .map(r -> new RemoteRepository.Builder(r.getId(), r.getLayout(), r.getUrl()).build())
        .collect(Collectors.toList());

    CollectResult result;
    try {
        final ArtifactDescriptorRequest descriptorRequest = new ArtifactDescriptorRequest(artifact, remoteRepositories, null);
        final ArtifactDescriptorResult descriptor = repository.readArtifactDescriptor(session, descriptorRequest);

        final List<Dependency> dependencies = Stream.concat(
            descriptor.getDependencies().stream(),
            descriptor.getManagedDependencies().stream())
            .collect(Collectors.toList());

        final DefaultRepositorySystemSession sessionToUse = new DefaultRepositorySystemSession(session);
        sessionToUse.setDependencyGraphTransformer(new NoopDependencyGraphTransformer());

        final CollectRequest request = new CollectRequest(dependency, dependencies, remoteRepositories);
        result = repository.collectDependencies(sessionToUse, request);
    } catch (final DependencyCollectionException | ArtifactDescriptorException e) {
        throw new IllegalStateException("Unabele to obtain BOM dependencies for: " + urlLocation, e);
    }

    final DependencyNode root = result.getRoot();

    final PostorderNodeListGenerator visitor = new PostorderNodeListGenerator();
    root.accept(visitor);

    return visitor.getDependencies(true);
}
 
Example #23
Source File: MavenArtifactResolvingHelperTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
/**
 * @see #testArtifactExtensions()
 */
@Test
public void testManagedDependenciesExtensions() throws Exception {
    // prepare mocks
    // always find an artifact in local repo
    Mockito.when(localRepositoryManager.find(Mockito.any(), Mockito.any(LocalArtifactRequest.class)))
            .thenReturn(new LocalArtifactResult(new LocalArtifactRequest())
                    .setAvailable(true).setFile(new File("test.jar")));
    // return non-null when system.collectDependencies() is called
    CollectResult collectResult = new CollectResult(new CollectRequest());
    collectResult.setRoot(new DefaultDependencyNode((Artifact) null));
    Mockito.when(system.collectDependencies(Mockito.any(), Mockito.any(CollectRequest.class)))
            .thenReturn(collectResult);


    DependencyManagement dependencyManagement = new DependencyManagement();
    dependencyManagement.addDependency(createDependency("ejb-client"));
    dependencyManagement.addDependency(createDependency("javadoc"));
    dependencyManagement.addDependency(createDependency("pom"));

    MavenArtifactResolvingHelper artifactResolverHelper =
            new MavenArtifactResolvingHelper(resolver, system, sessionMock, dependencyManagement);
    // try to resolve artifacts with various packagings
    List<ArtifactSpec> artifacts = Arrays.asList(createSpec("ejb"), createSpec("pom"), createSpec("javadoc"));
    artifactResolverHelper.resolveAll(artifacts, true, false);


    ArgumentCaptor<CollectRequest> captor = ArgumentCaptor.forClass(CollectRequest.class);
    Mockito.verify(system).collectDependencies(Mockito.any(), captor.capture());
    // verify managed dependencies extensions
    Assert.assertEquals("jar", captor.getValue().getManagedDependencies().get(0).getArtifact().getExtension()); // type ejb-client
    Assert.assertEquals("jar", captor.getValue().getManagedDependencies().get(1).getArtifact().getExtension()); // type javadoc
    Assert.assertEquals("pom", captor.getValue().getManagedDependencies().get(2).getArtifact().getExtension()); // type pom
    // verify artifact extensions
    Assert.assertEquals("jar", captor.getValue().getDependencies().get(0).getArtifact().getExtension()); // packaging ejb
    Assert.assertEquals("pom", captor.getValue().getDependencies().get(1).getArtifact().getExtension()); // packaging pom
    Assert.assertEquals("jar", captor.getValue().getDependencies().get(2).getArtifact().getExtension()); // packaging javadoc
}
 
Example #24
Source File: MavenArtifactResolver.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public DependencyResult resolveDependencies(Artifact artifact, List<Dependency> deps, List<RemoteRepository> mainRepos)
        throws BootstrapMavenException {
    final CollectRequest request = newCollectRequest(artifact, mainRepos);
    request.setDependencies(deps);
    try {
        return repoSystem.resolveDependencies(repoSession,
                new DependencyRequest().setCollectRequest(request));
    } catch (DependencyResolutionException e) {
        throw new BootstrapMavenException("Failed to resolve dependencies for " + artifact, e);
    }
}
 
Example #25
Source File: MavenDependencyResolver.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
public List<com.baidu.formula.launcher.model.Dependency> getArtifactsDependencies(
        MavenProject project, String scope)
        throws DependencyCollectionException, DependencyResolutionException {
    DefaultArtifact pomArtifact = new DefaultArtifact(project.getId());

    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 = repositorySystem.collectDependencies(session, collectRequest).getRoot();
    DependencyRequest projectDependencyRequest = new DependencyRequest(node, null);

    repositorySystem.resolveDependencies(session, projectDependencyRequest);

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

    ret.addAll(nlg.getDependencies(true));
    return ret.stream().map(d -> {
        com.baidu.formula.launcher.model.Dependency dep = new com.baidu.formula.launcher.model.Dependency();
        dep.setArtifactId(d.getArtifact().getArtifactId());
        dep.setGroupId(d.getArtifact().getGroupId());
        dep.setVersion(d.getArtifact().getVersion());
        return dep;
    }).collect(Collectors.toList());
}
 
Example #26
Source File: DependencyGraphBuilder.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
private DependencyNode resolveCompileTimeDependencies(
    List<DependencyNode> dependencyNodes, DefaultRepositorySystemSession session)
    throws DependencyResolutionException {

  ImmutableList.Builder<Dependency> dependenciesBuilder = ImmutableList.builder();
  for (DependencyNode dependencyNode : dependencyNodes) {
    Dependency dependency = dependencyNode.getDependency();
    if (dependency == null) {
      // Root DependencyNode has null dependency field.
      dependenciesBuilder.add(new Dependency(dependencyNode.getArtifact(), "compile"));
    } else {
      // The dependency field carries exclusions
      dependenciesBuilder.add(dependency.setScope("compile"));
    }
  }
  ImmutableList<Dependency> dependencyList = dependenciesBuilder.build();
          
  if (localRepository != null) {
    LocalRepository local = new LocalRepository(localRepository.toAbsolutePath().toString());
    session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, local));
  }

  CollectRequest collectRequest = new CollectRequest();
  if (dependencyList.size() == 1) {
    // With setRoot, the result includes dependencies with `optional:true` or `provided`
    collectRequest.setRoot(dependencyList.get(0));
  } else {
    collectRequest.setDependencies(dependencyList);
  }
  for (RemoteRepository repository : repositories) {
    collectRequest.addRepository(repository);
  }
  DependencyRequest dependencyRequest = new DependencyRequest();
  dependencyRequest.setCollectRequest(collectRequest);

  // resolveDependencies equals to calling both collectDependencies (build dependency tree) and
  // resolveArtifacts (download JAR files).
  DependencyResult dependencyResult = system.resolveDependencies(session, dependencyRequest);
  return dependencyResult.getRoot();
}
 
Example #27
Source File: DependencyDownloader.java    From go-offline-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Download a single dependency and all of its transitive dependencies that is needed by the build without appearing in any dependency tree
 * <p>
 * Dependencies and plugin artifacts that refer to an artifact in the current reactor build are ignored.
 * Transitive dependencies that are marked as optional are ignored
 * Transitive dependencies with the scopes "test", "system" and "provided" are ignored.
 *
 * @param dynamicDependency the dependency to download
 */
public Set<ArtifactWithRepoType> resolveDynamicDependency(DynamicDependency dynamicDependency) {
    DefaultArtifact artifact = new DefaultArtifact(dynamicDependency.getGroupId(), dynamicDependency.getArtifactId(), dynamicDependency.getClassifier(), "jar", dynamicDependency.getVersion());

    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(new Dependency(artifact, null));
    RepositoryType repositoryType = dynamicDependency.getRepositoryType();
    RepositorySystemSession session;
    switch (repositoryType) {
        case MAIN:
            session = remoteSession;
            collectRequest.setRepositories(remoteRepositories);
            collectRequest.setRequestContext(repositoryType.getRequestContext());
            break;
        case PLUGIN:
            session = pluginSession;
            collectRequest.setRepositories(pluginRepositories);
            collectRequest.setRequestContext(repositoryType.getRequestContext());
            break;
        default:
            throw new IllegalStateException("Unknown enum val " + repositoryType);

    }
    try {
        CollectResult collectResult = repositorySystem.collectDependencies(session, collectRequest);
        return getArtifactsFromCollectResult(collectResult, repositoryType);
    } catch (DependencyCollectionException | RuntimeException e) {
        log.error("Error resolving dynamic dependency" + dynamicDependency.getGroupId() + ":" + dynamicDependency.getArtifactId());
        handleRepositoryException(e);
    }
    return Collections.emptySet();
}
 
Example #28
Source File: PluginAddCommand.java    From gyro with Apache License 2.0 5 votes vote down vote up
private boolean validate(String plugin) {
    try {
        DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();

        locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
        locator.addService(TransporterFactory.class, FileTransporterFactory.class);
        locator.addService(TransporterFactory.class, HttpTransporterFactory.class);

        RepositorySystem system = locator.getService(RepositorySystem.class);
        DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
        String localDir = Paths.get(System.getProperty("user.home"), ".m2", "repository").toString();
        LocalRepository local = new LocalRepository(localDir);
        LocalRepositoryManager manager = system.newLocalRepositoryManager(session, local);

        session.setLocalRepositoryManager(manager);

        Artifact artifact = new DefaultArtifact(plugin);
        Dependency dependency = new Dependency(artifact, JavaScopes.RUNTIME);
        DependencyFilter filter = DependencyFilterUtils.classpathFilter(JavaScopes.RUNTIME);
        CollectRequest collectRequest = new CollectRequest(dependency, repositories);
        DependencyRequest request = new DependencyRequest(collectRequest, filter);
        system.resolveDependencies(session, request);

        return true;
    } catch (DependencyResolutionException e) {
        GyroCore.ui().write("@|bold %s|@ was not installed for the following reason(s):\n", plugin);

        for (Exception ex : e.getResult().getCollectExceptions()) {
            GyroCore.ui().write("   @|red %s|@\n", ex.getMessage());
        }

        GyroCore.ui().write("\n");

        return false;
    }
}
 
Example #29
Source File: MavenArtifactResolver.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public CollectResult collectDependencies(Artifact artifact, List<Dependency> deps, List<RemoteRepository> mainRepos)
        throws BootstrapMavenException {
    final CollectRequest request = newCollectRequest(artifact, mainRepos);
    request.setDependencies(deps);
    try {
        return repoSystem.collectDependencies(repoSession, request);
    } catch (DependencyCollectionException e) {
        throw new BootstrapMavenException("Failed to collect dependencies for " + artifact, e);
    }
}
 
Example #30
Source File: SimpleMavenCache.java    From gate-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void cacheArtifact(Artifact artifact)
    throws IOException, SettingsBuildingException,
    DependencyCollectionException, DependencyResolutionException,
    ArtifactResolutionException, ModelBuildingException {

  // setup a maven resolution hierarchy that uses the main local repo as
  // a remote repo and then cache into a new local repo
  List<RemoteRepository> repos = Utils.getRepositoryList();
  RepositorySystem repoSystem = Utils.getRepositorySystem();
  DefaultRepositorySystemSession repoSession =
      Utils.getRepositorySession(repoSystem, null);

  // treat the usual local repository as if it were a remote, ignoring checksum
  // failures as the local repo doesn't have checksums as a rule
  RemoteRepository localAsRemote =
      new RemoteRepository.Builder("localAsRemote", "default",
          repoSession.getLocalRepository().getBasedir().toURI().toString())
              .setPolicy(new RepositoryPolicy(true,
                      RepositoryPolicy.UPDATE_POLICY_NEVER,
                      RepositoryPolicy.CHECKSUM_POLICY_IGNORE))
              .build();

  repos.add(0, localAsRemote);

  repoSession.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(
      repoSession, new LocalRepository(head.getAbsolutePath())));

  Dependency dependency = new Dependency(artifact, "runtime");

  CollectRequest collectRequest = new CollectRequest(dependency, repos);

  DependencyNode node =
      repoSystem.collectDependencies(repoSession, collectRequest).getRoot();

  DependencyRequest dependencyRequest = new DependencyRequest();
  dependencyRequest.setRoot(node);

  repoSystem.resolveDependencies(repoSession, dependencyRequest);

}