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

The following examples show how to use org.eclipse.aether.collection.CollectRequest#setRepositories() . 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: 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 3
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 4
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 5
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 6
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 7
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 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: 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 11
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 12
Source File: MavenArtifactResolvingHelper.java    From wildfly-swarm with Apache License 2.0 4 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")));

    RepositorySystemSession tempSession =
            new RepositorySystemSessionWrapper(this.session,
                                               new ConflictResolver(new NewestVersionSelector(),
                                                                    new JavaScopeSelector(),
                                                                    new SimpleOptionalitySelector(),
                                                                    new JavaScopeDeriver()
                                               )
            );

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

    PreorderNodeListGenerator gen = new PreorderNodeListGenerator();
    result.getRoot().accept(gen);
    List<DependencyNode> nodes = gen.getNodes();

    resolveDependenciesInParallel(nodes);

    return nodes.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 13
Source File: PluginBundleManager.java    From BIMserver with GNU Affero General Public License v3.0 4 votes vote down vote up
private void loadDependencies(String pluginBundleVersion, boolean strictDependencyChecking, Model model,
			DelegatingClassLoader delegatingClassLoader)
			throws DependencyCollectionException, InvalidVersionSpecificationException, Exception {
		if (model.getRepositories() != null) {
			for (Repository repository : model.getRepositories()) {
				mavenPluginRepository.addRepository(repository.getId(), "default", repository.getUrl());
			}
		}

		List<Dependency> dependenciesToResolve = new ArrayList<>();
		for (org.apache.maven.model.Dependency dependency2 : model.getDependencies()) {
			String scope = dependency2.getScope();
			if (scope != null && (scope.contentEquals("test"))) {
				// Skip
				continue;
			}
			Dependency d = new Dependency(new DefaultArtifact(dependency2.getGroupId(), dependency2.getArtifactId(), dependency2.getType(), dependency2.getVersion()), dependency2.getScope());
			Set<Exclusion> exclusions = new HashSet<>();
			d.setExclusions(exclusions);
			exclusions.add(new Exclusion("org.opensourcebim", "pluginbase", null, "jar"));
			exclusions.add(new Exclusion("org.opensourcebim", "shared", null, "jar"));
			exclusions.add(new Exclusion("org.opensourcebim", "ifcplugins", null, "jar"));
			dependenciesToResolve.add(d);
		}
		CollectRequest collectRequest = new CollectRequest(dependenciesToResolve, null, null);
		collectRequest.setRepositories(mavenPluginRepository.getRepositoriesAsList());
		CollectResult collectDependencies = mavenPluginRepository.getSystem().collectDependencies(mavenPluginRepository.getSession(), collectRequest);
		PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
		DependencyNode rootDep = collectDependencies.getRoot();
		rootDep.accept(nlg);
		
		for (Dependency dependency : nlg.getDependencies(true)) {
			if (dependency.getScope().contentEquals("test")) {
				continue;
			}
//			LOGGER.info(dependency.getArtifact().getGroupId() + "." + dependency.getArtifact().getArtifactId());
			Artifact dependencyArtifact = dependency.getArtifact();
			PluginBundleIdentifier pluginBundleIdentifier = new PluginBundleIdentifier(dependencyArtifact.getGroupId(), dependencyArtifact.getArtifactId());
			if (pluginBundleIdentifierToPluginBundle.containsKey(pluginBundleIdentifier)) {
				if (strictDependencyChecking) {
					String version = dependencyArtifact.getVersion();
					if (!version.contains("[") && !version.contains("(")) {
						version = "[" + version + "]";
					}
					VersionRange versionRange = VersionRange.createFromVersionSpec(version);
					// String version =
					// pluginBundleIdentifierToPluginBundle.get(pluginBundleIdentifier).getPluginBundleVersion().getVersion();
					ArtifactVersion artifactVersion = new DefaultArtifactVersion(pluginBundleVersion);
					if (versionRange.containsVersion(artifactVersion)) {
						// OK
					} else {
						throw new Exception(
								"Required dependency " + pluginBundleIdentifier + " is installed, but it's version (" + pluginBundleVersion + ") does not comply to the required version (" + dependencyArtifact.getVersion() + ")");
					}
				} else {
					LOGGER.info("Skipping strict dependency checking for dependency " + dependencyArtifact.getArtifactId());
				}
			} else {
				try {
					if (dependencyArtifact.getGroupId().contentEquals("com.sun.xml.ws")) {
						continue;
					}
					MavenPluginLocation mavenPluginLocation = mavenPluginRepository.getPluginLocation(dependencyArtifact.getGroupId(), dependencyArtifact.getArtifactId());
					if (dependencyArtifact.getExtension().contentEquals("jar")) {
						Path depJarFile = mavenPluginLocation.getVersionJar(dependencyArtifact.getVersion());
						
						FileJarClassLoader jarClassLoader = new FileJarClassLoader(pluginManager, delegatingClassLoader, depJarFile);
						jarClassLoaders.add(jarClassLoader);
						delegatingClassLoader.add(jarClassLoader);
					}
				} catch (Exception e) {
					e.printStackTrace();
					throw new Exception("Required dependency " + pluginBundleIdentifier + " is not installed");
				}
			}
		}
	}