Java Code Examples for org.eclipse.aether.collection.CollectRequest#setRoot()

The following examples show how to use org.eclipse.aether.collection.CollectRequest#setRoot() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
Source File: ClasspathQuery.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private static Set<File> getJarFiles(final Collection<String> gavs)
{
    Set<File> jars = new HashSet<>();

    for (final String gav : gavs)
    {
        Artifact artifact = new DefaultArtifact(gav);

        DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE);

        CollectRequest collectRequest = new CollectRequest();
        collectRequest.setRoot(new Dependency(artifact, JavaScopes.COMPILE));
        collectRequest.setRepositories(Booter.newRepositories());

        DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFlter);

        List<ArtifactResult> artifactResults = null;
        try
        {
            artifactResults = _mavenRepositorySystem.resolveDependencies(_mavenRepositorySession, dependencyRequest)
                                                    .getArtifactResults();
        }
        catch (DependencyResolutionException e)
        {
            throw new RuntimeException(String.format("Error while dependency resolution for '%s'", gav), e);
        }

        if (artifactResults == null)
        {
            throw new RuntimeException(String.format("Could not resolve dependency for '%s'", gav));
        }

        for (ArtifactResult artifactResult : artifactResults)
        {
            System.out.println(artifactResult.getArtifact() + " resolved to "
                               + artifactResult.getArtifact().getFile());
        }

        jars.addAll(artifactResults.stream()
                                   .map(result -> result.getArtifact().getFile())
                                   .collect(Collectors.toSet()));
    }
    return jars;
}
 
Example 10
Source File: ArtifactRetriever.java    From maven-repository-tools with Eclipse Public License 1.0 4 votes vote down vote up
private List<ArtifactResult> getArtifactResults( List<String> artifactCoordinates, boolean
        includeProvidedScope, boolean includeTestScope, boolean includeRuntimeScope )
{

    List<Artifact> artifacts = new ArrayList<Artifact>();
    for ( String artifactCoordinate : artifactCoordinates )
    {
        artifacts.add( new DefaultArtifact( artifactCoordinate ) );
    }

    List<ArtifactResult> artifactResults = new ArrayList<ArtifactResult>();
    DependencyFilter depFilter = 
        DependencyFilterUtils.classpathFilter( JavaScopes.TEST );
    
    Collection<String> includes = new ArrayList<String>();
    // we always include compile scope, not doing that makes no sense
    includes.add( JavaScopes.COMPILE );
    
    Collection<String> excludes = new ArrayList<String>();
    // always exclude system scope since it is machine specific and wont work in 99% of cases
    excludes.add( JavaScopes.SYSTEM );

    if ( includeProvidedScope )
    {
        includes.add( JavaScopes.PROVIDED );
    }
    else 
    {
        excludes.add( JavaScopes.PROVIDED ); 
    }
    
    if ( includeTestScope ) 
    {
        includes.add( JavaScopes.TEST );
    }
    else
    {
        excludes.add( JavaScopes.TEST );
    }

    if ( includeRuntimeScope )
    {
        includes.add( JavaScopes.RUNTIME );
    }
    
    DependencySelector selector =
        new AndDependencySelector(
        new ScopeDependencySelector( includes, excludes ),
        new OptionalDependencySelector(),
        new ExclusionDependencySelector()
    );
    session.setDependencySelector( selector );

    for ( Artifact artifact : artifacts )
    {
        CollectRequest collectRequest = new CollectRequest();
        collectRequest.setRoot( new Dependency( artifact, JavaScopes.COMPILE ) );
        collectRequest.addRepository( sourceRepository );

        DependencyRequest dependencyRequest = new DependencyRequest( collectRequest, depFilter );

        try
        {
            DependencyResult resolvedDependencies = system.resolveDependencies( session, dependencyRequest );
            artifactResults.addAll( resolvedDependencies.getArtifactResults() );
            for ( ArtifactResult result : resolvedDependencies.getArtifactResults() )
            {
                successfulRetrievals.add( result.toString() );
            }
        }
        catch ( DependencyResolutionException e )
        {
            String extension = artifact.getExtension();
            if ( MavenConstants.packagingUsesJarOnly( extension ) )
            {
                logger.info( "Not reporting as failure due to " + artifact.getExtension() + " extension." );
            }
            else
            {
              logger.info( "DependencyResolutionException ", e );
              failedRetrievals.add( e.getMessage() );
            }
        }
        catch ( NullPointerException npe )
        {
            logger.info( "NullPointerException resolving dependencies for " + artifact + ":" + npe );
            if ( npe.getMessage() != null )
            {
                failedRetrievals.add( npe.getMessage() );
            }
            else
            {
                failedRetrievals.add( "NPE retrieving " + artifact );
            }
        }
    }

    return artifactResults;
}