org.eclipse.aether.artifact.Artifact Java Examples

The following examples show how to use org.eclipse.aether.artifact.Artifact. 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: 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 #2
Source File: DeployArtifacts.java    From unleash-maven-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void execute(ExecutionContext context) throws MojoExecutionException, MojoFailureException {
  this.log.info("Deploying the release artifacts into the distribution repository");

  try {
    Collection<Artifact> deployedArtifacts = this.deployer.deployArtifacts(this.metadata.getReleaseArtifacts());
    if (!deployedArtifacts.isEmpty()) {
      this.log.debug("\tDeployed the following release artifacts to the remote repository:");
      for (Artifact a : deployedArtifacts) {
        this.log.debug("\t\t" + a);
      }
    }
  } catch (DeploymentException e) {
    throw new MojoFailureException("Unable to deploy artifacts into remote repository.", e);
  }
}
 
Example #3
Source File: ExtraArtifactsHandler.java    From thorntail with Apache License 2.0 6 votes vote down vote up
private void addDependencies(Function<Artifact, Boolean> duplicateFilter, Optional<String> extension, Optional<String> classifier) {
    List<Dependency> dependencies = input.stream()
            .map(DependencyNode::getDependency)
            .collect(Collectors.toList());

    Set<String> existingGavs = dependencies.stream()
            .map(Dependency::getArtifact)
            .filter(duplicateFilter::apply)
            .map(this::toGav)
            .collect(Collectors.toSet());

    List<DependencyNode> newNodes = input.stream()
            .filter(n -> !existingGavs.contains(toGav(n.getDependency().getArtifact())))
            .map(n -> createNode(n, extension, classifier))
            .collect(Collectors.toList());
    output.addAll(newNodes);
}
 
Example #4
Source File: AutoDiscoverDeployService.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
private DeployRequest createAutoDiscoverDeployRequest(List<Artifact> dependencies, boolean testScope) {
    List<DeployConfigRequest> configs = dependencies.stream()
            .filter(a -> ModuleRequest.CONFIG_TYPE.equals(a.getExtension()))
            .map(a -> DeployConfigRequest.build(a.getGroupId(), a.getArtifactId(), a.getVersion(), a.getClassifier()))
            .collect(Collectors.toList());

    List<DeployArtifactRequest> artifacts = dependencies.stream()
            .filter(a -> ModuleRequest.ZIP_TYPE.equals(a.getExtension()) || ModuleRequest.GZIP_TYPE.equals(a.getExtension()))
            .map(a -> DeployArtifactRequest.build(a.getGroupId(), a.getArtifactId(), a.getVersion(), a.getClassifier(), a.getExtension()))
            .collect(Collectors.toList());

    List<DeployApplicationRequest> applications = dependencies.stream()
            .filter(a -> "jar".equals(a.getExtension()))
            .map(a -> DeployApplicationRequest.build(a.getGroupId(), a.getArtifactId(), a.getVersion(), a.getClassifier(), testScope))
            .collect(Collectors.toList());

    return new DeployRequest(applications, artifacts, configs, false, false, "", false, testScope);
}
 
Example #5
Source File: PinpointPluginTestSuite.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private List<PinpointPluginTestInstance> createCasesWithDependencies(PinpointPluginTestContext context) throws ArtifactResolutionException, DependencyResolutionException {
    List<PinpointPluginTestInstance> cases = new ArrayList<PinpointPluginTestInstance>();

    DependencyResolver resolver = getDependencyResolver(repositories);
    Map<String, List<Artifact>> dependencyCases = resolver.resolveDependencySets(dependencies);

    for (Map.Entry<String, List<Artifact>> dependencyCase : dependencyCases.entrySet()) {
        List<String> libs = new ArrayList<String>();

        for (File lib : resolver.resolveArtifactsAndDependencies(dependencyCase.getValue())) {
            libs.add(lib.getAbsolutePath());
        }

        if (testOnSystemClassLoader) {
            cases.add(new NormalPluginTestCase(context, dependencyCase.getKey(), libs, true));
        }

        if (testOnChildClassLoader) {
            cases.add(new NormalPluginTestCase(context, dependencyCase.getKey(), libs, false));
        }
    }

    return cases;
}
 
Example #6
Source File: DependencyDownloader.java    From go-offline-maven-plugin with Apache License 2.0 6 votes vote down vote up
private Set<ArtifactWithRepoType> getArtifactsFromCollectResult(CollectResult collectResult, RepositoryType context) {
    CollectAllDependenciesVisitor visitor = new CollectAllDependenciesVisitor();
    collectResult.getRoot().accept(visitor);
    Set<Artifact> visitorArtifacts = visitor.getArtifacts();
    Set<ArtifactWithRepoType> artifacts = new HashSet<>();
    for (Artifact visitorArtifact : visitorArtifacts) {
        if (!isReactorArtifact(visitorArtifact)) {
            artifacts.add(new ArtifactWithRepoType(visitorArtifact, context));
        }
    }
    Artifact rootArtifact = collectResult.getRoot().getArtifact();
    if (!isReactorArtifact(rootArtifact)) {
        artifacts.add(new ArtifactWithRepoType(rootArtifact, context));
    }
    return artifacts;
}
 
Example #7
Source File: LibraryFactory.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
static Collection<LibraryFile> loadTransitiveDependencies(MavenCoordinates root)
    throws CoreException {
  Set<LibraryFile> dependencies = new HashSet<>();
  Collection<Artifact> artifacts = DependencyResolver.getTransitiveDependencies(
      root.getGroupId(), root.getArtifactId(), root.getVersion(), null);
  for (Artifact artifact : artifacts) {
    MavenCoordinates coordinates = new MavenCoordinates.Builder()
        .setGroupId(artifact.getGroupId())
        .setArtifactId(artifact.getArtifactId())
        .setVersion(artifact.getVersion())
        .build();
    LibraryFile file = new LibraryFile(coordinates);
    dependencies.add(file);
  }
  return dependencies;
}
 
Example #8
Source File: AetherResolver.java    From onos with Apache License 2.0 6 votes vote down vote up
private String getSha(Artifact artifact) throws Exception {
    String directory = artifact.getFile().getParent();
    StringBuilder file = new StringBuilder();

    // artifactId-version[-classifier].version.sha1
    file.append(artifact.getArtifactId())
            .append('-').append(artifact.getVersion());

    if (!artifact.getClassifier().isEmpty()) {
        file.append('-').append(artifact.getClassifier());
    }
    file.append('.').append(artifact.getExtension())
            .append(".sha1");

    String shaPath = Paths.get(directory, file.toString()).toString();

    try (Reader reader = new FileReader(shaPath)) {
        return new BufferedReader(reader).readLine().trim().split(" ", 2)[0];
    }
}
 
Example #9
Source File: ResolverTest.java    From vertx-stack with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatExcludedDependenciesAndThereDependenciesAreResolvedWithATransitiveNotExcludedMentionedFirst() {
  new LocalRepoBuilder(LOCAL)
      .addArtifact(new LocalArtifact("com.acme", "acme-api", "1.0")
          .generateMainArtifact()
          .addDependency(new LocalDependency("com.acme", "acme-log", "1.0").type("txt")))

      .addArtifact(new LocalArtifact("com.acme", "acme-excluded", "1.0")
          .generateMainArtifact()
          .addDependency(new LocalDependency("com.acme", "acme-log", "1.0").type("txt")))

      .addArtifact(new LocalArtifact("com.acme", "acme-log", "1.0").generateMainArtifact())

      .addArtifact(new LocalArtifact("com.acme", "acme", "1.0")
          .generateMainArtifact()
          .addDependency(new LocalDependency("com.acme", "acme-api", "1.0").type("txt"))
          .addDependency(new LocalDependency("com.acme", "acme-excluded", "1.0").type("txt"))
      )
      .build();
  List<Artifact> artifacts = resolver.resolve("com.acme:acme:txt:1.0",
      new ResolutionOptions().setWithTransitive(true).addExclusion("com.acme:acme-excluded"));
  assertThat(artifacts.stream().map(Artifact::getArtifactId).collect(Collectors.toList()))
      .hasSize(3)
      .contains("acme", "acme-api", "acme-log");
}
 
Example #10
Source File: ResolverTest.java    From vertx-stack with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolutionWhenADependencyIsPresentTwiceInTheGraphWithVersion() {
  
  new LocalRepoBuilder(LOCAL)
      .addArtifact(new LocalArtifact("com.acme", "acme-api", "1.0").generateMainArtifact())
      .addArtifact(new LocalArtifact("com.acme", "acme-api", "1.1").generateMainArtifact())
      .addArtifact(new LocalArtifact("com.acme", "acme-lib", "1.0")
          .generateMainArtifact()
          .addDependency(new LocalDependency("com.acme", "acme-api", "1.0").type("txt"))
      )
      .addArtifact(new LocalArtifact("com.acme", "acme", "1.0")
          .generateMainArtifact()
          .addDependency(new LocalDependency("com.acme", "acme-lib", "1.0").type("txt"))
          .addDependency(new LocalDependency("com.acme", "acme-test", "1.0").type("txt").scope("test"))
          .addDependency(new LocalDependency("com.acme", "acme-api", "1.1").type("txt"))
      )
      .build();
  List<Artifact> artifacts = resolver.resolve("com.acme:acme:txt:1.0", new ResolutionOptions().setWithTransitive(true));
  assertThat(artifacts.stream().map(Artifact::toString).collect(Collectors.toList()))
      .hasSize(3)
      .contains("com.acme:acme:txt:1.0", "com.acme:acme-api:txt:1.1", "com.acme:acme-lib:txt:1.0");
}
 
Example #11
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 #12
Source File: DependencyResolverTest.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveArtifactsAndDependencies() throws DependencyResolutionException, ArtifactResolutionException {
    DependencyResolverFactory factory = new DependencyResolverFactory();
    DependencyResolver resolver = factory.get();

    Map<String, List<Artifact>> sets = resolver.resolveDependencySets("org.eclipse.aether:aether-util:[0,)", "org.eclipse.aether:aether-spi");

    int i = 0;
    for (Map.Entry<String, List<Artifact>> set : sets.entrySet()) {
        logger.debug("{}", i++);
        List<File> results = resolver.resolveArtifactsAndDependencies(set.getValue());

        logger.debug(set.getKey());

        for (File result : results) {
            logger.debug("{}", result);
        }
    }
}
 
Example #13
Source File: SimpleReactorReader.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public File findArtifact(Artifact artifact) {
  MavenProject project = getProject(artifact);
  if (project != null) {
    if ("pom".equals(artifact.getExtension())) {
      return project.getFile();
    } else if ("jar".equals(artifact.getExtension()) && "".equals(artifact.getClassifier())) {
      return new File(project.getBuild().getOutputDirectory());
    }
  }
  Artifact _artifact = getArtifact(artifact);
  if (_artifact != null) {
    return _artifact.getFile();
  }
  return null;
}
 
Example #14
Source File: SimpleReactorReader.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
private SimpleReactorReader(Collection<MavenProject> projects, Collection<Artifact> artifacts) {
  repository = new WorkspaceRepository("reactor", new Object());

  Map<String, MavenProject> projectsByGAV = new LinkedHashMap<>();
  for (MavenProject project : projects) {
    String projectKey = ArtifactUtils.key(project.getGroupId(), project.getArtifactId(), project.getVersion());
    projectsByGAV.put(projectKey, project);
  }
  this.projectsByGAV = ImmutableMap.copyOf(projectsByGAV);

  Map<String, Artifact> artifactsByGAVCE = new LinkedHashMap<>();
  for (Artifact artifact : artifacts) {
    artifactsByGAVCE.put(keyGAVCE(artifact), artifact);
  }
  this.artifactsByGAVCE = ImmutableMap.copyOf(artifactsByGAVCE);
}
 
Example #15
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 #16
Source File: AetherUtils.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
public static Artifact toArtifact(org.apache.maven.artifact.Artifact artifact) {
  if (artifact == null) {
    return null;
  }

  String version = artifact.getVersion();
  if (version == null && artifact.getVersionRange() != null) {
    version = artifact.getVersionRange().toString();
  }

  Map<String, String> props = null;
  if (org.apache.maven.artifact.Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) {
    String localPath = (artifact.getFile() != null) ? artifact.getFile().getPath() : "";
    props = Collections.singletonMap(ArtifactProperties.LOCAL_PATH, localPath);
  }

  Artifact result = new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(), artifact.getArtifactHandler().getExtension(), version, props,
      newArtifactType(artifact.getType(), artifact.getArtifactHandler()));
  result = result.setFile(artifact.getFile());

  return result;
}
 
Example #17
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 #18
Source File: DependencyPath.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
/** Returns the artifact at the end of the path. */
public Artifact getLeaf() {
  if (path.isEmpty()) {
    return root;
  } else {
    return path.get(path.size() - 1).getArtifact();
  }
}
 
Example #19
Source File: ArtifactDownload.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method fetches the artifact from the remote server using aether library
 * 
 * @param groupId group ID of the artifact
 * @param artifactId artifact ID of the artifact
 * @param version artifact version to be downloaded
 * @param classifier classifier of the artifact
 * @param packaging packaging of the artifact
 * @param localRepository destination path
 * @return location of the downloaded artifact in the local system
 * @throws IOException
 */
public static File getArtifactByAether(String groupId, String artifactId, String version, String classifier, String packaging, File localRepository) throws IOException {
	RepositorySystem repositorySystem = newRepositorySystem();
	RepositorySystemSession session = newSession(repositorySystem, localRepository);

	Artifact artifact = new DefaultArtifact(groupId, artifactId, classifier, packaging, version);
	ArtifactRequest artifactRequest = new ArtifactRequest();
	artifactRequest.setArtifact(artifact);

	List<RemoteRepository> repositories = new ArrayList<>();
	Section ini = Utils.getConfig().get(Constants.INI_URL_HEADER);

	RemoteRepository remoteRepository = new RemoteRepository.Builder("public", "default", ini.get(Constants.INI_NEXUS_SOOT_RELEASE)).build();

	repositories.add(remoteRepository);

	artifactRequest.setRepositories(repositories);
	File result = null;

	try {
		ArtifactResult artifactResult = repositorySystem.resolveArtifact(session, artifactRequest);
		artifact = artifactResult.getArtifact();
		if (artifact != null) {
			result = artifact.getFile();
		}
	}
	catch (ArtifactResolutionException e) {
		throw new IOException("Artifact " + groupId + ":" + artifactId + ":" + version + " could not be downloaded due to " + e.getMessage());
	}

	return result;

}
 
Example #20
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 #21
Source File: AutoDiscoverDeployService.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
private Artifact getDeployArtifact(String mavenCoords) {
    Artifact artifact = new DefaultArtifact(mavenCoords);
    ArtifactRequest artifactRequest = new ArtifactRequest();
    artifactRequest.setArtifact(artifact);
    artifactRequest.setRepositories(AetherUtil.newRepositories(deployConfig));
    try {
        ArtifactResult artifactResult = system.resolveArtifact(session, artifactRequest);
        return artifactResult.getArtifact();
    } catch (ArtifactResolutionException e) {
        LOG.error("Unable to resolve deploy artifact '{}', unable to auto-discover ", mavenCoords, e);
    }
    return null;
}
 
Example #22
Source File: BuildComponentM2RepositoryMojo.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
protected String copyComponentDependencies(final Artifact car,
        final BiConsumer<ZipEntry, InputStream> onDependency) {
    String gav = null;
    try (final ZipInputStream read =
            new ZipInputStream(new BufferedInputStream(new FileInputStream(car.getFile())))) {
        ZipEntry entry;
        while ((entry = read.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                continue;
            }

            final String path = entry.getName();
            if ("TALEND-INF/metadata.properties".equals(path)) {
                final Properties properties = new Properties();
                properties.load(read);
                gav = properties.getProperty("component_coordinates").replace("\\:", "");
                continue;
            }
            if (!path.startsWith("MAVEN-INF/repository/")) {
                continue;
            }

            onDependency.accept(entry, read);
        }
    } catch (final IOException e) {
        throw new IllegalArgumentException(e);
    }
    return gav;
}
 
Example #23
Source File: DependencyResolver.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private static List<Artifact> getArtifactList(String value) {
    if (value == null) {
        return Collections.emptyList();
    }

    String[] artifactNameArray = value.split(ArtifactIdUtils.ARTIFACT_SEPARATOR);
    return ArtifactIdUtils.toArtifact(artifactNameArray);
}
 
Example #24
Source File: CarConsumer.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
protected Set<Artifact> getComponentArtifacts() {
    return getArtifacts(it -> {
        try (final JarFile file = new JarFile(it.getFile())) { // filter components with this marker
            return ofNullable(file.getEntry("TALEND-INF/dependencies.txt")).map(ok -> it).orElse(null);
        } catch (final IOException e) {
            return null;
        }
    }).filter(Objects::nonNull).collect(toSet());
}
 
Example #25
Source File: MavenAddonDependencyResolver.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
private AddonId toAddonId(Artifact artifact)
{
   if (isAddon(artifact))
   {
      return AddonId.from(artifact.getGroupId() + ":" + artifact.getArtifactId(), artifact.getBaseVersion());
   }
   throw new IllegalArgumentException("Not a forge-addon: " + artifact);
}
 
Example #26
Source File: BomTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadBom_coordinates() throws ArtifactDescriptorException {
  Bom bom = Bom.readBom("com.google.cloud:google-cloud-bom:0.61.0-alpha");
  List<Artifact> managedDependencies = bom.getManagedDependencies();
  // Characterization test. As long as the artifact doesn't change (and it shouldn't)
  // the answer won't change.
  Assert.assertEquals(134, managedDependencies.size());
  Assert.assertEquals("com.google.cloud:google-cloud-bom:0.61.0-alpha", bom.getCoordinates());
}
 
Example #27
Source File: CacheTest.java    From vertx-stack with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisabledCache() throws IOException {
  String gacv = "org.acme:acme:jar:1.0";
  cache = new Cache(true, false, cacheFile);
  ResolutionOptions options = new ResolutionOptions();
  List<Artifact> list = cache.get(gacv, options);
  assertThat(list).isNull();

  File file = File.createTempFile("acme", ".jar");
  Artifact artifact = new DefaultArtifact("org.acme:acme:jar:1.0").setFile(file);

  cache.put(gacv, options, Collections.singletonList(artifact));
  list = cache.get(gacv, options);
  assertThat(list).isNull();
}
 
Example #28
Source File: Bom.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the dependencyManagement section of an artifact and returns
 * the artifacts included there.
 *
 * @param mavenRepositoryUrls URLs of Maven repositories to search for BOM members
 */
public static Bom readBom(String coordinates, List<String> mavenRepositoryUrls)
    throws ArtifactDescriptorException {
  Artifact artifact = new DefaultArtifact(coordinates);

  RepositorySystem system = RepositoryUtility.newRepositorySystem();
  RepositorySystemSession session = RepositoryUtility.newSession(system);

  ArtifactDescriptorRequest request = new ArtifactDescriptorRequest();

  for (String repositoryUrl : mavenRepositoryUrls) {
    request.addRepository(RepositoryUtility.mavenRepositoryFromUrl(repositoryUrl));
  }

  request.setArtifact(artifact);

  ArtifactDescriptorResult resolved = system.readArtifactDescriptor(session, request);
  List<Exception> exceptions = resolved.getExceptions();
  if (!exceptions.isEmpty()) {
    throw new ArtifactDescriptorException(resolved, exceptions.get(0).getMessage());
  }
  
  List<Artifact> managedDependencies = new ArrayList<>();
  for (Dependency dependency : resolved.getManagedDependencies()) {
    Artifact managed = dependency.getArtifact();
    if (!shouldSkipBomMember(managed) && !managedDependencies.contains(managed)) {
      managedDependencies.add(managed);
    }
  }
  
  Bom bom = new Bom(coordinates, ImmutableList.copyOf(managedDependencies));
  return bom;
}
 
Example #29
Source File: GenerateMetadataMojo.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private Artifact toArtifact(final org.apache.maven.artifact.Artifact artifact) {
    final ArtifactTypeRegistry registry = session.getArtifactTypeRegistry();
    final ArtifactType type = registry.get(artifact.getType());

    return new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(),
        type.getExtension(), artifact.getVersion(), type);
}
 
Example #30
Source File: AetherUtils.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
/**
 * Download artifacts
 * @param artifacts {@link Set<Artifact>} artifacts for download
 * @return {@link List<Artifact>} of resolved artifact
 * @throws IllegalArgumentException if artifacts is null
 */
public List<Artifact> downloadArtifacts(Set<Artifact> artifacts) {
    Args.notNull(artifacts, "artifacts");
    Set<ArtifactRequest> artifactRequests = createArtifactRequests(artifacts);
    List<ArtifactResult> artifactResults = resolveArtifactRequests(artifactRequests);
    List<Artifact> result = Lists.newArrayList();
    for (ArtifactResult res : artifactResults) {
        result.add(res.getArtifact());
    }
    return result;
}