org.eclipse.aether.resolution.DependencyRequest Java Examples

The following examples show how to use org.eclipse.aether.resolution.DependencyRequest. 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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
Source File: RemotePluginLoader.java    From digdag with Apache License 2.0 5 votes vote down vote up
private List<ArtifactResult> resolveArtifacts(List<RemoteRepository> repositories, String dep)
{
    DependencyRequest depRequest = buildDependencyRequest(repositories, dep, JavaScopes.RUNTIME);
    try {
        return system.resolveDependencies(session, depRequest).getArtifactResults();
    }
    catch (DependencyResolutionException ex) {
        throw Throwables.propagate(ex);
    }
}
 
Example #14
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 #15
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);

}
 
Example #16
Source File: MavenArtifactResolver.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public DependencyResult resolveManagedDependencies(Artifact artifact, List<Dependency> deps, List<Dependency> managedDeps,
        List<RemoteRepository> mainRepos, String... excludedScopes) throws BootstrapMavenException {
    try {
        return repoSystem.resolveDependencies(repoSession,
                new DependencyRequest().setCollectRequest(
                        newCollectManagedRequest(artifact, deps, managedDeps, mainRepos, excludedScopes)));
    } catch (DependencyResolutionException e) {
        throw new BootstrapMavenException("Failed to resolve dependencies for " + artifact, e);
    }
}
 
Example #17
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 #18
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 #19
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 #20
Source File: Aether.java    From migration-tooling with Apache License 2.0 4 votes vote down vote up
/**
 * Given a dependency request, this makes the call to aether to transitively resolve the
 * dependencies.
 */
DependencyResult requestDependencyResolution(DependencyRequest dependencyRequest)
    throws DependencyResolutionException {
  return repositorySystem.resolveDependencies(repositorySystemSession, dependencyRequest);
}
 
Example #21
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 #22
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 #23
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 #24
Source File: DevMojo.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void addQuarkusDevModeDeps(StringBuilder classPathManifest)
        throws MojoExecutionException, DependencyResolutionException {
    final String pomPropsPath = "META-INF/maven/io.quarkus/quarkus-core-deployment/pom.properties";
    final InputStream devModePomPropsIs = DevModeMain.class.getClassLoader().getResourceAsStream(pomPropsPath);
    if (devModePomPropsIs == null) {
        throw new MojoExecutionException("Failed to locate " + pomPropsPath + " on the classpath");
    }
    final Properties devModeProps = new Properties();
    try (InputStream is = devModePomPropsIs) {
        devModeProps.load(is);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to load " + pomPropsPath + " from the classpath", e);
    }
    final String devModeGroupId = devModeProps.getProperty("groupId");
    if (devModeGroupId == null) {
        throw new MojoExecutionException("Classpath resource " + pomPropsPath + " is missing groupId");
    }
    final String devModeArtifactId = devModeProps.getProperty("artifactId");
    if (devModeArtifactId == null) {
        throw new MojoExecutionException("Classpath resource " + pomPropsPath + " is missing artifactId");
    }
    final String devModeVersion = devModeProps.getProperty("version");
    if (devModeVersion == null) {
        throw new MojoExecutionException("Classpath resource " + pomPropsPath + " is missing version");
    }

    final DefaultArtifact devModeJar = new DefaultArtifact(devModeGroupId, devModeArtifactId, "jar", devModeVersion);
    final DependencyResult cpRes = repoSystem.resolveDependencies(repoSession,
            new DependencyRequest()
                    .setCollectRequest(
                            new CollectRequest()
                                    .setRoot(new org.eclipse.aether.graph.Dependency(devModeJar, JavaScopes.RUNTIME))
                                    .setRepositories(repos)));

    for (ArtifactResult appDep : cpRes.getArtifactResults()) {
        //we only use the launcher for launching from the IDE, we need to exclude it
        if (!(appDep.getArtifact().getGroupId().equals("io.quarkus")
                && appDep.getArtifact().getArtifactId().equals("quarkus-ide-launcher"))) {
            addToClassPaths(classPathManifest, appDep.getArtifact().getFile());
        }
    }
}
 
Example #25
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 #26
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 #27
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 #28
Source File: DependencyResolver.java    From start.spring.io with Apache License 2.0 4 votes vote down vote up
private DependencyResult resolveDependencies(DependencyRequest dependencyRequest)
		throws DependencyResolutionException {
	DependencyResult resolved = this.repositorySystem.resolveDependencies(this.repositorySystemSession,
			dependencyRequest);
	return resolved;
}