org.eclipse.aether.artifact.DefaultArtifact Java Examples

The following examples show how to use org.eclipse.aether.artifact.DefaultArtifact. 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: ArtifactTransporter.java    From jenkins-build-monitor-plugin with MIT License 6 votes vote down vote up
public Path get(@NotNull String groupName, @NotNull String artifactName, @NotNull String version, @NotNull String artifactFileExtension) {
    Artifact artifact = new DefaultArtifact(groupName, artifactName, artifactFileExtension, version);

    RepositorySystem system = newRepositorySystem();
    RepositorySystemSession session = newRepositorySystemSession(system);

    ArtifactRequest request = new ArtifactRequest();
    request.setArtifact(artifact);
    request.setRepositories(repositories(system, session));

    try {
        ArtifactResult artifactResult = system.resolveArtifact(session, request);

        artifact = artifactResult.getArtifact();

        Log.info(artifact + " resolved to  " + artifact.getFile());

        return artifact.getFile().toPath();

    } catch (ArtifactResolutionException e) {
        throw new RuntimeException(format("Couldn't resolve a '%s' artifact for '%s:%s:%s'",
                artifactFileExtension, groupName, artifactName, version
        ), e);
    }
}
 
Example #2
Source File: DependencyGraphBuilderTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildLinkageCheckDependencyGraph_catchRootException() {
  // This should not throw exception
  DependencyGraph result =
      dependencyGraphBuilder.buildFullDependencyGraph(
          ImmutableList.of(new DefaultArtifact("ant:ant:jar:1.6.2")));

  Set<UnresolvableArtifactProblem> problems = result.getUnresolvedArtifacts();

  Truth.assertThat(problems)
      .comparingElementsUsing(problemOnArtifact)
      .containsAtLeast("xerces:xerces-impl:2.6.2", "xml-apis:xml-apis:2.6.2");

  Truth.assertThat(problems).hasSize(2);
  Truth.assertThat(problems)
      .comparingElementsUsing(
          Correspondence.transforming(UnresolvableArtifactProblem::toString, "has description"))
      .containsExactly(
          "xerces:xerces-impl:jar:2.6.2 was not resolved. Dependency path: ant:ant:jar:1.6.2"
              + " (compile) > xerces:xerces-impl:jar:2.6.2 (compile?)",
          "xml-apis:xml-apis:jar:2.6.2 was not resolved. Dependency path: ant:ant:jar:1.6.2"
              + " (compile) > xml-apis:xml-apis:jar:2.6.2 (compile?)");
}
 
Example #3
Source File: DependencyGraphBuilderTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildLinkageCheckDependencyGraph_grpcProtobufExclusion() {
  // Grpc-protobuf depends on grpc-protobuf-lite with protobuf-lite exclusion.
  // https://github.com/GoogleCloudPlatform/cloud-opensource-java/issues/1056
  Artifact grpcProtobuf = new DefaultArtifact("io.grpc:grpc-protobuf:1.25.0");

  DependencyGraph dependencyGraph = dependencyGraphBuilder
          .buildFullDependencyGraph(ImmutableList.of(grpcProtobuf));

  Correspondence<DependencyPath, String> pathToArtifactKey =
      Correspondence.transforming(
          dependencyPath -> Artifacts.makeKey(dependencyPath.getLeaf()),
          "has a leaf with groupID and artifactID");
  Truth.assertThat(dependencyGraph.list())
      .comparingElementsUsing(pathToArtifactKey)
      .doesNotContain("com.google.protobuf:protobuf-lite");
}
 
Example #4
Source File: DependencyGraphBuilderTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildLinkageCheckDependencyGraph_respectExclusions() {
  // hibernate-core declares jboss-jacc-api_JDK4 dependency excluding jboss-servlet-api_3.0.
  // jboss-jacc-api_JDK4 depends on jboss-servlet-api_3.0:1.0-SNAPSHOT, which is unavailable.
  // DependencyGraphBuilder should respect the exclusion and should not try to download
  // jboss-servlet-api_3.0:1.0-SNAPSHOT.
  Artifact hibernateCore = new DefaultArtifact("org.hibernate:hibernate-core:jar:3.5.1-Final");

  DependencyGraph result =
      dependencyGraphBuilder.buildFullDependencyGraph(ImmutableList.of(hibernateCore));

  Set<UnresolvableArtifactProblem> problems = result.getUnresolvedArtifacts();
  for (UnresolvableArtifactProblem problem : problems) {
    Truth.assertThat(problem.toString()).doesNotContain("jboss-servlet-api_3.0");
  }
}
 
Example #5
Source File: SimpleMavenCache.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {

    for(RemoteRepository repo : Utils.getRepositoryList()) {
      System.out.println(repo);
    }

    Artifact artifactObj = new DefaultArtifact("uk.ac.gate.plugins", "annie",
        "jar", "8.5-SNAPSHOT");
    // artifactObj = artifactObj.setFile(
    // new
    // File("/home/mark/.m2/repository/uk/ac/gate/plugins/annie/8.5-SNAPSHOT/annie-8.5-SNAPSHOT.jar"));

    SimpleMavenCache reader = new SimpleMavenCache(new File("repo"));
    System.out.println(reader.findArtifact(artifactObj));
    System.out.println(reader.findVersions(artifactObj));
    reader.cacheArtifact(artifactObj);
    System.out.println(reader.findArtifact(artifactObj));
    System.out.println(reader.findVersions(artifactObj));

    reader = new SimpleMavenCache(new File("repo2"), new File("repo"));
    System.out.println(reader.findArtifact(artifactObj));
    System.out.println(reader.findVersions(artifactObj));
  }
 
Example #6
Source File: DeployUtils.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
private boolean hasTransitiveSnapshots(Dependency dependency) throws MojoFailureException {
    ArtifactDescriptorRequest descriptorRequest = new ArtifactDescriptorRequest();
    descriptorRequest.setArtifact(
            new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), dependency.getType(), dependency.getVersion()));
    descriptorRequest.setRepositories(remoteRepos);

    try {
        ArtifactDescriptorResult result = repoSystem.readArtifactDescriptor(repoSession, descriptorRequest);
        Optional<org.eclipse.aether.graph.Dependency> snapshotDependency = result.getDependencies().stream()
                .filter(d -> d.getArtifact().isSnapshot())
                .findFirst();
        return snapshotDependency.isPresent();
    } catch (ArtifactDescriptorException e) {
        throw new MojoFailureException(e.getMessage(), e);
    }
}
 
Example #7
Source File: MyArtifactInstaller.java    From elasticsearch-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void installArtifact(ElasticsearchArtifact artifact, File file) throws ArtifactException
{
    log.debug("Installing '" + file.getAbsolutePath() + "' in the local maven repo");

    InstallRequest request = new InstallRequest();
    Artifact defaultArtifact = new DefaultArtifact(
            artifact.getGroupId(),
            artifact.getArtifactId(),
            artifact.getClassifier(),
            artifact.getType(),
            artifact.getVersion(),
            null,
            file);
    request.addArtifact(defaultArtifact);

    log.info(String.format("Installing maven artifact: %s", artifact));

    try
    {
        repositorySystem.install(repositorySession, request);
    }
    catch (InstallationException e) {
        throw new ArtifactException(e.getMessage(), e);
    }
}
 
Example #8
Source File: DevServerMojo.java    From yawp with MIT License 6 votes vote down vote up
public String resolveDevServerJar() {
    String version = getYawpVersion();
    List<RemoteRepository> allRepos = ImmutableList.copyOf(Iterables.concat(getProjectRepos()));

    ArtifactRequest request = new ArtifactRequest(new DefaultArtifact(YAWP_GROUP_ID, YAWP_DEVSERVER_ARTIFACT_ID, "jar", version), allRepos,
            null);

    ArtifactResult result;
    try {
        result = repoSystem.resolveArtifact(repoSession, request);
    } catch (ArtifactResolutionException e) {
        throw new RuntimeException("Could not resolve DevServer artifact in Maven.");
    }

    return result.getArtifact().getFile().getPath();
}
 
Example #9
Source File: SimpleModelResolver.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ModelSource resolveModel(String groupId, String artifactId, String version)
        throws UnresolvableModelException {
    Artifact pomArtifact = new DefaultArtifact(groupId, artifactId, "", "pom", version);

    try {
        ArtifactRequest request = new ArtifactRequest(pomArtifact, repositories, null);
        pomArtifact = system.resolveArtifact(session, request).getArtifact();
    } catch (org.eclipse.aether.resolution.ArtifactResolutionException ex) {
        throw new UnresolvableModelException(ex.getMessage(), groupId, artifactId, version, ex);
    } 

    File pomFile = pomArtifact.getFile();

    return new FileModelSource(pomFile);
}
 
Example #10
Source File: ClassPathBuilderTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolve() {

  Artifact grpcAuth = new DefaultArtifact("io.grpc:grpc-auth:1.15.1");

  ImmutableList<ClassPathEntry> classPath =
      classPathBuilder.resolve(ImmutableList.of(grpcAuth)).getClassPath();

  Truth.assertThat(classPath)
      .comparingElementsUsing(TestHelper.COORDINATES)
      .containsAtLeast(
          "io.grpc:grpc-auth:1.15.1", "com.google.auth:google-auth-library-credentials:0.9.0");
  classPath.forEach(
      path ->
          Truth.assertWithMessage("Every returned path should be an absolute path")
              .that(path.getJar().isAbsolute())
              .isTrue());
}
 
Example #11
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 #12
Source File: Mvn2NixMojo.java    From mvn2nix-maven-plugin with MIT License 6 votes vote down vote up
private Dependency mavenDependencyToDependency(
		org.apache.maven.model.Dependency dep) {
	Artifact art = new DefaultArtifact(dep.getGroupId(),
		dep.getArtifactId(),
		dep.getClassifier(),
		dep.getType(),
		dep.getVersion());
	Collection<Exclusion> excls = new HashSet<Exclusion>();
	for (org.apache.maven.model.Exclusion excl :
		dep.getExclusions()) {
		excls.add(mavenExclusionToExclusion(excl));
	}
	return new Dependency(art,
		dep.getScope(),
		new Boolean(dep.isOptional()),
		excls);
}
 
Example #13
Source File: RepositoryModelResolver.java    From archiva with Apache License 2.0 6 votes vote down vote up
public ModelSource resolveModel(Dependency dependency) throws UnresolvableModelException {
    try {
        Artifact artifact = new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), "", "pom", dependency.getVersion());
        VersionRangeRequest versionRangeRequest = new VersionRangeRequest(artifact, null, null);
        VersionRangeResult versionRangeResult = this.versionRangeResolver.resolveVersionRange(this.session, versionRangeRequest);
        if (versionRangeResult.getHighestVersion() == null) {
            throw new UnresolvableModelException(String.format("No versions matched the requested dependency version range '%s'", dependency.getVersion()), dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion());
        } else if (versionRangeResult.getVersionConstraint() != null && versionRangeResult.getVersionConstraint().getRange() != null && versionRangeResult.getVersionConstraint().getRange().getUpperBound() == null) {
            throw new UnresolvableModelException(String.format("The requested dependency version range '%s' does not specify an upper bound", dependency.getVersion()), dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion());
        } else {
            dependency.setVersion(versionRangeResult.getHighestVersion().toString());
            return this.resolveModel(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion());
        }
    } catch (VersionRangeResolutionException var5) {
        throw new UnresolvableModelException(var5.getMessage(), dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), var5);
    }
}
 
Example #14
Source File: ResolverTest.java    From migration-tooling with Apache License 2.0 6 votes vote down vote up
@Test
public void depManagementDoesntAddDeps() throws Exception {
  Aether aether = mock(Aether.class);
  when(aether.requestVersionRange(fromCoords("c:d:[2.0,)"))).thenReturn(newArrayList("2.0"));
  when(aether.requestVersionRange(fromCoords("a:b:[1.0,)")))
      .thenReturn(newArrayList("1.0", "2.0"));
  VersionResolver versionResolver = new VersionResolver(aether);

  Resolver resolver = new Resolver(mock(DefaultModelResolver.class), versionResolver, ALIASES);
  resolver.traverseDeps(
      mockDepManagementModel("a:b:1.0", "c:d:2.0"),
      Sets.newHashSet(),
      Sets.newHashSet(),
      new Rule(new DefaultArtifact("par:ent:1.2.3")));
  Collection<Rule> rules = resolver.getRules();
  assertThat(rules).hasSize(1);
  Rule actual = rules.iterator().next();
  assertThat(actual.name()).isEqualTo("c_d");
}
 
Example #15
Source File: PomXmlUtils.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
/**
 * Parse element for getting {@link Artifact} from it
 * @param element - {@link Element} for parse
 * @param versions - versions which are in <properties></properties> of pom.xml
 * @return {@link Artifact} - if parse is success
 *         Optional.absent() - if parse is failed
 */
private Artifact parseDependency(Element element, Map<String, String> versions) {
    Element groupElement = (Element) element.getElementsByTagName(GROUP).item(0);
    Element artifactElement = (Element) element.getElementsByTagName(ARTIFACT).item(0);
    Element versionElement = (Element) element.getElementsByTagName(VERSION).item(0);
    String groupId = groupElement != null ? groupElement.getTextContent() : null;
    String artifactId = artifactElement != null ? artifactElement.getTextContent() : null;
    String version = versionElement != null ? versionElement.getTextContent() : null;
    if (isLinkToVersion(version) && versions != null) {
        version = versions.get(version);
    }

    return (groupId != null && artifactId != null && version != null)
        ? (Artifact) new DefaultArtifact(getGAV(groupId, artifactId, version))
        : null;
}
 
Example #16
Source File: ExclusionFilesIntegrationTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testExclusion()
    throws IOException, RepositoryException, TransformerException, XMLStreamException,
        LinkageCheckResultException {

  Artifact artifact =
      new DefaultArtifact("org.apache.beam:beam-runners-google-cloud-dataflow-java:2.19.0");

  LinkageCheckerMain.main(
      new String[] {"-a", Artifacts.toCoordinates(artifact), "-o", exclusionFile.toString()});

  ClassPathBuilder classPathBuilder = new ClassPathBuilder();
  ClassPathResult classPathResult = classPathBuilder.resolve(ImmutableList.of(artifact));

  LinkageChecker linkagechecker =
      LinkageChecker.create(classPathResult.getClassPath(), ImmutableList.of(), exclusionFile);

  ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems =
      linkagechecker.findSymbolProblems();
  Truth.assertThat(symbolProblems).isEmpty();
}
 
Example #17
Source File: ResolverTest.java    From migration-tooling with Apache License 2.0 6 votes vote down vote up
@Test
public void nonConflictingDepManagementRange() throws Exception {
  Aether aether = mock(Aether.class);
  when(aether.requestVersionRange(fromCoords("a:b:[1.0,4.0]")))
      .thenReturn(newArrayList("1.0", "1.2", "2.0", "3.0", "4.0"));
  when(aether.requestVersionRange(fromCoords("a:b:[1.2,3.0]")))
      .thenReturn(newArrayList("1.2", "2.0", "3.0"));
  VersionResolver versionResolver = new VersionResolver(aether);

  Resolver resolver = new Resolver(mock(DefaultModelResolver.class), versionResolver, ALIASES);
  resolver.traverseDeps(
      mockDepManagementModel("a:b:[1.0,4.0]", "a:b:[1.2,3.0]"),
      Sets.newHashSet(),
      Sets.newHashSet(),
      new Rule(new DefaultArtifact("par:ent:1.2.3")));
  Collection<Rule> rules = resolver.getRules();
  assertThat(rules).hasSize(1);
  Rule actual = rules.iterator().next();
  assertThat(actual.version()).isEqualTo("3.0");
}
 
Example #18
Source File: SerializeGraphTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testTreeWithVersionConflict() throws IOException
{
    DependencyNode root = new DefaultDependencyNode(
            new Dependency( new DefaultArtifact( "com.google", "rootArtifact", "jar", "1.0.0" ), "compile" )
    );
    DependencyNode left = new DefaultDependencyNode(
            new Dependency( new DefaultArtifact( "org.apache", "left", "xml", "0.1-SNAPSHOT" ), "test", true )
    );
    DependencyNode right = new DefaultDependencyNode(
            new Dependency( new DefaultArtifact( "com.google", "rootArtifact", "jar", "2.0.0" ), "test" )
    );

    root.setChildren( Arrays.asList( left, right ) );

    String actual = serializer.serialize( root );
    File file = new File(getBasedir(), "/target/test-classes/SerializerTests/VersionConflict.txt");
    String expected = FileUtils.readFileToString(file);

    Assert.assertEquals(expected, actual);
}
 
Example #19
Source File: MongoCollector.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public List<Artifact> collectAvailableVersions(String coordinates) {
	List<MavenLibrary> libs = mavenLibraryRepository.findByGroupidAndArtifactidOrderByReleasedateDesc(
			coordinates.split(":")[0], 
			coordinates.split(":")[1]);
	List<Artifact> result = Lists.newArrayList();
	for (MavenLibrary mavenLibrary : libs) {
		Artifact artifact = new DefaultArtifact(
				String.format("%s:%s:%s",
					mavenLibrary.getGroupid(),
					mavenLibrary.getArtifactid(),
					mavenLibrary.getVersion()
				));
		result.add(artifact);
	}
	return result;
}
 
Example #20
Source File: DashboardMain.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
private static Map<Artifact, Artifact> findUpperBoundsFailures(
    Map<String, String> expectedVersionMap,
    DependencyGraph transitiveDependencies) {

  Map<String, String> actualVersionMap = transitiveDependencies.getHighestVersionMap();

  VersionComparator comparator = new VersionComparator();

  Map<Artifact, Artifact> upperBoundFailures = new LinkedHashMap<>();

  for (String id : expectedVersionMap.keySet()) {
    String expectedVersion = expectedVersionMap.get(id);
    String actualVersion = actualVersionMap.get(id);
    // Check that the actual version is not null because it is
    // possible for dependencies to appear or disappear from the tree
    // depending on which version of another dependency is loaded.
    // In both cases, no action is needed.
    if (actualVersion != null && comparator.compare(actualVersion, expectedVersion) < 0) {
      // Maven did not choose highest version
      DefaultArtifact lower = new DefaultArtifact(id + ":" + actualVersion);
      DefaultArtifact upper = new DefaultArtifact(id + ":" + expectedVersion);
      upperBoundFailures.put(lower, upper);
    }
  }
  return upperBoundFailures;
}
 
Example #21
Source File: DependencyGraphBuilderTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDependencyPathRoot_twoDependency() {
  DependencyGraph result =
      dependencyGraphBuilder.buildFullDependencyGraph(
          ImmutableList.of(
              new DefaultArtifact("com.google.guava:guava:28.1-jre"),
              new DefaultArtifact("com.google.api:gax:1.57.0")));

  List<DependencyPath> paths = result.list();

  // Because it's requesting a tree with multiple artifacts, the root of the tree is null
  assertNull(paths.get(0).get(0));
  assertEquals(
      "com.google.guava:guava:28.1-jre", Artifacts.toCoordinates(paths.get(0).getLeaf()));

  assertNull(paths.get(1).get(0));
  assertEquals("com.google.api:gax:1.57.0", Artifacts.toCoordinates(paths.get(1).getLeaf()));
}
 
Example #22
Source File: SingerMojo.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Path findMain() {
    final LocalRepositoryManager lrm = repositorySystemSession.getLocalRepositoryManager();
    final Artifact artifact = new DefaultArtifact(GAV.GROUP, "component-kitap", "fatjar", "jar", GAV.VERSION);
    final File location = new File(lrm.getRepository().getBasedir(), lrm.getPathForLocalArtifact(artifact));
    if (!location.exists()) {
        final ArtifactRequest artifactRequest =
                new ArtifactRequest().setArtifact(artifact).setRepositories(remoteRepositories);
        try {
            final ArtifactResult result =
                    repositorySystem.resolveArtifact(repositorySystemSession, artifactRequest);
            if (result.isMissing()) {
                throw new IllegalStateException("Can't find " + artifact);
            }
            return result.getArtifact().getFile().toPath();
        } catch (final ArtifactResolutionException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
    return location.toPath();
}
 
Example #23
Source File: PomXmlUtils.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
/**
 * Read maven group, artifact, version in xml node <parent></parent>
 * @param pomXml pom.xml for read
 * @return {@link Artifact} with parent's group, artifact, version
 */
Artifact readParentGAVInPomXml(Path pomXml) {
    Args.notNull(pomXml, "pomXml");
    Document doc = readDocumentFromFile(pomXml);
    String expression = String.format("/%s/%s", PROJECT, PARENT);
    NodeList nodeList = executeExpression(expression, doc);
    if (nodeList != null && nodeList.getLength() > 0) {
        Element element = (Element) nodeList.item(0);
        String groupId = element.getElementsByTagName(GROUP).item(0).getTextContent();
        String artifactId = element.getElementsByTagName(ARTIFACT).item(0).getTextContent();
        String version = element.getElementsByTagName(VERSION).item(0).getTextContent();
        if (groupId != null && artifactId != null && version != null)
            return (Artifact) new DefaultArtifact(getGAV(groupId, artifactId, version));
    }

    return null;
}
 
Example #24
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 #25
Source File: CacheTest.java    From vertx-stack with Apache License 2.0 6 votes vote down vote up
@Test
public void testCachingOfReleaseAndUpdate() throws IOException {
  String gacv = "org.acme:acme:jar:1.0";
  ResolutionOptions options = new ResolutionOptions();
  List<Artifact> list = cache.get(gacv, options);
  assertThat(list).isNull();

  Artifact artifact = new DefaultArtifact("org.acme:acme:jar:1.0").setFile(TEMP_FILE);
  Artifact artifact2 = new DefaultArtifact("org.acme:acme-dep:jar:1.0").setFile(TEMP_FILE);

  cache.put(gacv, options, Collections.singletonList(artifact));
  list = cache.get(gacv, options);
  assertThat(list).hasSize(1);

  cache.put(gacv, options, Collections.singletonList(artifact));
  list = cache.get(gacv, options);
  assertThat(list).hasSize(1);

  cache.put(gacv, options, Arrays.asList(artifact, artifact2));
  list = cache.get(gacv, options);
  assertThat(list).hasSize(2);
}
 
Example #26
Source File: DependencyTreeFormatterTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDependencyTree_scopeAndOptionalFlag() {
  List<DependencyPath> dependencyPathList = new ArrayList<>();

  DependencyPath path1 =
      new DependencyPath(null)
          .append(
              new Dependency(
                  new DefaultArtifact("io.grpc:grpc-auth:jar:1.15.0"), "compile", true));
  dependencyPathList.add(path1);

  DependencyPath path2 =
      new DependencyPath(null)
          .append(
              new Dependency(
                  new DefaultArtifact("io.grpc:grpc-auth:jar:1.15.0"), "compile", true))
          .append(
              new Dependency(
                  new DefaultArtifact("io.grpc:grpc-core:jar:1.15.0"), "provided", false));
  dependencyPathList.add(path2);

  String actualTreeOutput = DependencyTreeFormatter.formatDependencyPaths(dependencyPathList);
  String expectedTreeOutput =
      "  io.grpc:grpc-auth:jar:1.15.0\n" + "    io.grpc:grpc-core:jar:1.15.0\n";
  Assert.assertEquals(expectedTreeOutput, actualTreeOutput);
}
 
Example #27
Source File: ResolverTest.java    From migration-tooling with Apache License 2.0 6 votes vote down vote up
@Test
public void dependencyManagementWins() throws Exception {
  Aether aether = mock(Aether.class);
  when(aether.requestVersionRange(fromCoords("a:b:[1.0]"))).thenReturn(newArrayList("1.0"));
  when(aether.requestVersionRange(fromCoords("a:b:[2.0,)"))).thenReturn(newArrayList("2.0"));
  VersionResolver versionResolver = new VersionResolver(aether);

  Resolver resolver = new Resolver(mock(DefaultModelResolver.class), versionResolver, ALIASES);
  resolver.traverseDeps(
      mockDepManagementModel("a:b:[1.0]", "a:b:2.0"),
      Sets.newHashSet(),
      Sets.newHashSet(),
      new Rule(new DefaultArtifact("par:ent:1.2.3")));
  Collection<Rule> rules = resolver.getRules();
  assertThat(rules).hasSize(1);
  Rule actual = rules.iterator().next();
  assertThat(actual.version()).isEqualTo("1.0");
}
 
Example #28
Source File: AetherStubDownloader.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private File unpackedJar(String resolvedVersion, String stubsGroup,
		String stubsModule, String classifier) {
	try {
		log.info("Resolved version is [" + resolvedVersion + "]");
		if (StringUtils.isEmpty(resolvedVersion)) {
			log.warn("Stub for group [" + stubsGroup + "] module [" + stubsModule
					+ "] and classifier [" + classifier + "] not found in "
					+ this.remoteRepos);
			return null;
		}
		Artifact artifact = new DefaultArtifact(stubsGroup, stubsModule, classifier,
				ARTIFACT_EXTENSION, resolvedVersion);
		ArtifactRequest request = new ArtifactRequest(artifact, this.remoteRepos,
				null);
		if (log.isDebugEnabled()) {
			log.debug("Resolving artifact [" + artifact
					+ "] using remote repositories " + this.remoteRepos);
		}
		ArtifactResult result = this.repositorySystem.resolveArtifact(this.session,
				request);
		log.info("Resolved artifact [" + artifact + "] to "
				+ result.getArtifact().getFile());
		File temporaryFile = unpackStubJarToATemporaryFolder(
				result.getArtifact().getFile().toURI());
		log.info("Unpacked file to [" + temporaryFile + "]");
		return temporaryFile;
	}
	catch (IllegalStateException ise) {
		throw ise;
	}
	catch (Exception e) {
		throw new IllegalStateException(
				"Exception occurred while trying to download a stub for group ["
						+ stubsGroup + "] module [" + stubsModule
						+ "] and classifier [" + classifier + "] in "
						+ this.remoteRepos,
				e);
	}
}
 
Example #29
Source File: MavenArtifactResolver.java    From spring-cloud-deployer with Apache License 2.0 5 votes vote down vote up
private Artifact toArtifact(MavenResource resource, String extension) {
	return new DefaultArtifact(resource.getGroupId(),
			resource.getArtifactId(),
			resource.getClassifier() != null ? resource.getClassifier() : "",
			extension,
			resource.getVersion());
}
 
Example #30
Source File: LinkageCheckerRuleTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkippingProjectWithoutFile() throws EnforcerRuleException {
  when(mockProject.getArtifact())
      .thenReturn(
          new org.apache.maven.artifact.DefaultArtifact(
              "com.google.cloud",
              "foo-tests",
              "0.0.1",
              "compile",
              "jar",
              null,
              new DefaultArtifactHandler()));
  rule.execute(mockRuleHelper);
}