org.eclipse.aether.graph.DependencyFilter Java Examples

The following examples show how to use org.eclipse.aether.graph.DependencyFilter. 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: NbPluginDependenciesResolver.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public DependencyNode resolve(Plugin plugin, Artifact pluginArtifact, DependencyFilter dependencyFilter, List<RemoteRepository> repositories, RepositorySystemSession session) throws PluginResolutionException {
    
    WorkspaceReader wr = session.getWorkspaceReader();
    NbWorkspaceReader nbwr = null;
    if (wr instanceof NbWorkspaceReader) {
        nbwr = (NbWorkspaceReader)wr;
        //this only works reliably because the NbWorkspaceReader is part of the session, not a component
        nbwr.silence();
    }
    try {
        return super.resolve(plugin, pluginArtifact, dependencyFilter, repositories, session);
    } finally {
        if (nbwr != null) {
            nbwr.normal();
        }
    }
}
 
Example #3
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 #4
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 #5
Source File: DependencyGraph.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
private static ImmutableList<List<DependencyNode>> findArtifactPaths(
    DependencyNode root, Artifact artifact) {
  String coordinates = Artifacts.toCoordinates(artifact);
  DependencyFilter filter =
      (node, parents) ->
          node.getArtifact() != null // artifact is null at a root dummy node.
              && Artifacts.toCoordinates(node.getArtifact()).equals(coordinates);
  UniquePathRecordingDependencyVisitor visitor = new UniquePathRecordingDependencyVisitor(filter);
  root.accept(visitor);
  return ImmutableList.copyOf(visitor.getPaths());
}
 
Example #6
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 #7
Source File: NewestVersionSelector.java    From wildfly-swarm with Apache License 2.0 5 votes vote down vote up
private UnsolvableVersionConflictException newFailure(final ConflictResolver.ConflictContext context) {
    DependencyFilter filter = new DependencyFilter() {
        public boolean accept(DependencyNode node, List<DependencyNode> parents) {
            return context.isIncluded(node);
        }
    };
    PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor(filter);
    context.getRoot().accept(visitor);
    return new UnsolvableVersionConflictException(visitor.getPaths());
}
 
Example #8
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 #9
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 #10
Source File: PluginPreprocessor.java    From gyro with Apache License 2.0 4 votes vote down vote up
@Override
public List<Node> preprocess(List<Node> nodes, RootScope scope) {
    PluginSettings settings = scope.getSettings(PluginSettings.class);

    List<String> artifactCoords = new ArrayList<>();
    List<Node> repositoryNodes = new ArrayList<>();

    for (Node node : nodes) {
        if (node instanceof DirectiveNode) {
            if ("plugin".equals(((DirectiveNode) node).getName())) {
                artifactCoords.add(getArtifactCoord((DirectiveNode) node));
            } else if ("repository".equals(((DirectiveNode) node).getName())) {
                repositoryNodes.add(node);
            }
        }
    }

    if (artifactCoords.stream().allMatch(settings::pluginInitialized)) {
        return nodes;
    }

    NodeEvaluator evaluator = new NodeEvaluator();
    evaluator.evaluate(scope, repositoryNodes);

    for (String ac : artifactCoords) {
        if (settings.pluginInitialized(ac)) {
            continue;
        }

        try {
            GyroCore.ui().write("@|magenta ↓ Loading plugin:|@ %s\n", ac);

            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(ac);
            Dependency dependency = new Dependency(artifact, JavaScopes.RUNTIME);
            DependencyFilter filter = DependencyFilterUtils.classpathFilter(JavaScopes.RUNTIME);
            List<RemoteRepository> repositories = scope.getSettings(RepositorySettings.class).getRepositories();
            CollectRequest collectRequest = new CollectRequest(dependency, repositories);
            DependencyRequest request = new DependencyRequest(collectRequest, filter);
            DependencyResult result = system.resolveDependencies(session, request);

            settings.putDependencyResult(ac, result);

            for (ArtifactResult ar : result.getArtifactResults()) {
                settings.putArtifactIfNewer(ar.getArtifact());
            }
        } catch (Exception error) {
            throw new GyroException(
                String.format("Can't load the @|bold %s|@ plugin!", ac),
                error);
        }
    }

    settings.addAllUrls();

    return nodes;
}
 
Example #11
Source File: Aether.java    From migration-tooling with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a DependencyRequest, i.e. a request to resolve transitive dependencies, from
 * a collect request.
 */
//TODO(petros): add some means to add exclusions.
DependencyRequest createDependencyRequest(CollectRequest collectRequest, DependencyFilter filter) {
  return new DependencyRequest(collectRequest, filter);
}
 
Example #12
Source File: Aether.java    From migration-tooling with Apache License 2.0 4 votes vote down vote up
DependencyRequest createDependencyRequest(CollectRequest collectRequest) {
  DependencyFilter compileFilter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE);
  return createDependencyRequest(collectRequest, compileFilter);
}
 
Example #13
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 #14
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;
}
 
Example #15
Source File: ClassLoaderResolverTest.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
@Test(expected = MojoExecutionException.class)
public void testResolutionFailure() throws Exception {
    when(repositorySystem.resolveDependencies(eq(repositorySystemSession), any(DependencyRequest.class)))
            .thenThrow(new DependencyResolutionException(new DependencyResult(new DependencyRequest(root, mock(DependencyFilter.class))), new Throwable()));
    classLoaderResolver.resolve(new MavenCoordinate(FOO, BAR, QUX, JAR));
}
 
Example #16
Source File: UniquePathRecordingDependencyVisitor.java    From cloud-opensource-java with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new visitor that uses the specified filter to identify terminal nodes of interesting
 * paths.
 *
 * @param filter The filter used to select terminal nodes of paths to record, may be {@code null}
 *     to match any node.
 */
public UniquePathRecordingDependencyVisitor(DependencyFilter filter) {
  this.filter = filter;
  paths = new ArrayList<>();
  parents = new ArrayList<>();
}