org.apache.maven.RepositoryUtils Java Examples

The following examples show how to use org.apache.maven.RepositoryUtils. 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: LinkageCheckerRule.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
/** Builds a class path for {@code bomProject}. */
private ClassPathResult findBomClasspath(
    MavenProject bomProject, RepositorySystemSession repositorySystemSession)
    throws EnforcerRuleException {

  ArtifactTypeRegistry artifactTypeRegistry = repositorySystemSession.getArtifactTypeRegistry();
  ImmutableList<Artifact> artifacts =
      bomProject.getDependencyManagement().getDependencies().stream()
          .map(dependency -> RepositoryUtils.toDependency(dependency, artifactTypeRegistry))
          .map(Dependency::getArtifact)
          .filter(artifact -> !Bom.shouldSkipBomMember(artifact))
          .collect(toImmutableList());

  ClassPathResult result = classPathBuilder.resolve(artifacts);
  ImmutableList<UnresolvableArtifactProblem> artifactProblems = result.getArtifactProblems();
  if (!artifactProblems.isEmpty()) {
    throw new EnforcerRuleException("Failed to collect dependency: " + artifactProblems);
  }
  return result;
}
 
Example #2
Source File: Bom.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
public static Bom readBom(Path pomFile) throws MavenRepositoryException {
  RepositorySystem system = RepositoryUtility.newRepositorySystem();
  RepositorySystemSession session = RepositoryUtility.newSession(system);

  MavenProject mavenProject = RepositoryUtility.createMavenProject(pomFile, session);
  String coordinates = mavenProject.getGroupId() + ":" + mavenProject.getArtifactId() 
      + ":" + mavenProject.getVersion();
  DependencyManagement dependencyManagement = mavenProject.getDependencyManagement();
  List<org.apache.maven.model.Dependency> dependencies = dependencyManagement.getDependencies();

  ArtifactTypeRegistry registry = session.getArtifactTypeRegistry();
  ImmutableList<Artifact> artifacts = dependencies.stream()
      .map(dependency -> RepositoryUtils.toDependency(dependency, registry))
      .map(Dependency::getArtifact)
      .filter(artifact -> !shouldSkipBomMember(artifact))
      .collect(ImmutableList.toImmutableList());
  
  Bom bom = new Bom(coordinates, artifacts);
  return bom;
}
 
Example #3
Source File: DependencyDownloader.java    From go-offline-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Download a plugin, all of its transitive dependencies and dependencies declared on the plugin declaration.
 * <p>
 * Dependencies and plugin artifacts that refer to an artifact in the current reactor build are ignored.
 * Transitive dependencies that are marked as optional are ignored
 * Transitive dependencies with the scopes "test", "system" and "provided" are ignored.
 *
 * @param plugin the plugin to download
 */
public Set<ArtifactWithRepoType> resolvePlugin(Plugin plugin) {
    Artifact pluginArtifact = toArtifact(plugin);
    Dependency pluginDependency = new Dependency(pluginArtifact, null);
    CollectRequest collectRequest = new CollectRequest(pluginDependency, pluginRepositories);
    collectRequest.setRequestContext(RepositoryType.PLUGIN.getRequestContext());

    List<Dependency> pluginDependencies = new ArrayList<>();
    for (org.apache.maven.model.Dependency d : plugin.getDependencies()) {
        Dependency dependency = RepositoryUtils.toDependency(d, typeRegistry);
        pluginDependencies.add(dependency);
    }
    collectRequest.setDependencies(pluginDependencies);

    try {
        CollectResult collectResult = repositorySystem.collectDependencies(pluginSession, collectRequest);
        return getArtifactsFromCollectResult(collectResult, RepositoryType.PLUGIN);
    } catch (DependencyCollectionException | RuntimeException e) {
        log.error("Error resolving plugin " + plugin.getGroupId() + ":" + plugin.getArtifactId());
        handleRepositoryException(e);
    }
    return Collections.emptySet();
}
 
Example #4
Source File: AbstractUnleashMojo.java    From unleash-maven-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@MojoProduces
@Named("additionalDeployemntRepositories")
private Set<RemoteRepository> getAdditionalDeploymentRepositories() {
  Set<Repository> repos = new HashSet<>();
  if (this.additionalDeploymentRepositories != null) {
    repos.addAll(this.additionalDeploymentRepositories);
  }

  System.getProperties().forEach((key, value) -> {
    if (key.toString().startsWith(PROPERTY_REPO_BASE)) {
      Repository.parseFromProperty(value.toString()).ifPresent(repo -> repos.add(repo));
    }
  });

  return repos.stream().map(repo -> {
    DefaultRepositoryLayout layout = new DefaultRepositoryLayout();
    ArtifactRepositoryPolicy snapshotsPolicy = new ArtifactRepositoryPolicy();
    ArtifactRepositoryPolicy releasesPolicy = new ArtifactRepositoryPolicy();

    ArtifactRepository artifactRepository = new MavenArtifactRepository(repo.getId(), repo.getUrl(), layout,
        snapshotsPolicy, releasesPolicy);
    this.settings.getServers().stream().filter(server -> Objects.equals(server.getId(), repo.getId())).findFirst()
        .ifPresent(server -> artifactRepository.setAuthentication(createServerAuthentication(server)));
    return RepositoryUtils.toRepo(artifactRepository);
  }).collect(Collectors.toSet());
}
 
Example #5
Source File: OpenSourceLicenseCheckMojo.java    From license-check with MIT License 6 votes vote down vote up
/**
 * Uses Aether to retrieve an artifact from the repository.
 *
 * @param coordinates as in groupId:artifactId:version
 * @return the located artifact
 */
Artifact retrieveArtifact(final String coordinates)
{

  final ArtifactRequest request = new ArtifactRequest();
  request.setArtifact(new DefaultArtifact(coordinates));
  request.setRepositories(remoteRepos);

  ArtifactResult result = null;
  try {
    result = repoSystem.resolveArtifact(repoSession, request);
  } catch (final ArtifactResolutionException e) {
    getLog().error("Could not resolve parent artifact (" + coordinates + "): " + e.getMessage());
  }

  if (result != null) {
    return RepositoryUtils.toArtifact(result.getArtifact());
  }
  return null;
}
 
Example #6
Source File: LinkageMonitor.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a copy of {@code bom} replacing its managed dependencies that have locally-installed
 * snapshot versions.
 */
@VisibleForTesting
static Bom copyWithSnapshot(
    RepositorySystem repositorySystem,
    RepositorySystemSession session,
    Bom bom,
    Map<String, String> localArtifacts)
    throws ModelBuildingException, ArtifactResolutionException {
  ImmutableList.Builder<Artifact> managedDependencies = ImmutableList.builder();

  Model model =
      buildModelWithSnapshotBom(repositorySystem, session, bom.getCoordinates(), localArtifacts);

  ArtifactTypeRegistry registry = session.getArtifactTypeRegistry();
  ImmutableList<Artifact> newManagedDependencies =
      model.getDependencyManagement().getDependencies().stream()
          .map(dependency -> RepositoryUtils.toDependency(dependency, registry))
          .map(Dependency::getArtifact)
          .collect(toImmutableList());
  for (Artifact managedDependency : newManagedDependencies) {
    if (Bom.shouldSkipBomMember(managedDependency)) {
      continue;
    }
    String version =
        localArtifacts.getOrDefault(
            managedDependency.getGroupId() + ":" + managedDependency.getArtifactId(),
            managedDependency.getVersion());
    managedDependencies.add(managedDependency.setVersion(version));
  }
  // "-SNAPSHOT" suffix for coordinate to distinguish easily.
  return new Bom(bom.getCoordinates() + "-SNAPSHOT", managedDependencies.build());
}
 
Example #7
Source File: ReleaseMetadata.java    From unleash-maven-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@PostConstruct
public void init() {
  // setting the artifact version to a release version temporarily since the dist repository checks for a snapshot
  // version of the artifact. Maybe this can be implemented in a different manner but then we would have to setup the
  // repository manually
  org.apache.maven.artifact.Artifact projectArtifact = this.project.getArtifact();
  String oldVersion = projectArtifact.getVersion();
  projectArtifact.setVersion("1");

  // replace properties in remote repository URL and getting the remote repo
  ArtifactRepository artifactRepository = this.project.getDistributionManagementArtifactRepository();
  if (artifactRepository != null) {
    PomPropertyResolver propertyResolver = new PomPropertyResolver(this.project, this.settings, this.profiles,
        this.releaseArgs);
    artifactRepository.setUrl(propertyResolver.expandPropertyReferences(artifactRepository.getUrl()));
    this.deploymentRepository = RepositoryUtils.toRepo(artifactRepository);
  }

  // resetting the artifact version
  projectArtifact.setVersion(oldVersion);

  for (MavenProject p : this.reactorProjects) {
    // puts the initial module artifact coordinates into the cache
    addArtifactCoordinates(ProjectToCoordinates.POM.apply(p), ReleasePhase.PRE_RELEASE);

    // caching of SCM settings of every POM in order to go back to it before setting next dev version
    this.cachedScmSettings.put(ProjectToCoordinates.EMPTY_VERSION.apply(p), p.getModel().getScm());

    Optional<Document> parsedPOM = PomUtil.parsePOM(p);
    if (parsedPOM.isPresent()) {
      this.originalPOMs.put(ProjectToCoordinates.EMPTY_VERSION.apply(p), parsedPOM.get());
    }
  }
}
 
Example #8
Source File: Analyzer.java    From revapi with Apache License 2.0 5 votes vote down vote up
private static Artifact findProjectArtifact(MavenProject project) {
    String extension = project.getArtifact().getArtifactHandler().getExtension();

    String fileName = project.getModel().getBuild().getFinalName() + "." + extension;
    File f = new File(new File(project.getBasedir(), "target"), fileName);
    if (f.exists()) {
        Artifact ret = RepositoryUtils.toArtifact(project.getArtifact());
        return ret.setFile(f);
    } else {
        return null;
    }
}
 
Example #9
Source File: UpdateStageDependenciesMojo.java    From gitflow-helper-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
protected void execute(final GitBranchInfo branchInfo) throws MojoExecutionException, MojoFailureException {
    getLog().debug("update-stage-dependencies setting up Repository session...");

    DefaultRepositorySystemSession reresolveSession = new DefaultRepositorySystemSession(repositorySystemSession);
    reresolveSession.setUpdatePolicy(org.eclipse.aether.repository.RepositoryPolicy.UPDATE_POLICY_ALWAYS);
    reresolveSession.setCache(new DefaultRepositoryCache());

    LocalRepositoryManager localRepositoryManager = reresolveSession.getLocalRepositoryManager();

    getLog().debug("configuring stage as the remote repository for artifact resolution requests...");
    List<RemoteRepository> stageRepo = Arrays.asList(RepositoryUtils.toRepo(getDeploymentRepository(stageDeploymentRepository)));

    boolean itemsPurged = false;

    try {
        DependencyResolutionResult depencencyResult = dependenciesResolver.resolve(
                new DefaultDependencyResolutionRequest(project, reresolveSession));

        for (Dependency dependency : depencencyResult.getResolvedDependencies()) {
            if (!dependency.getArtifact().isSnapshot()) {
                // Find the artifact in the local repo, and if it came from the 'stageRepo', populate that info
                // as the 'repository' on the artifact.
                LocalArtifactResult localResult = localRepositoryManager.find(reresolveSession,
                        new LocalArtifactRequest(dependency.getArtifact(), stageRepo, null));

                // If the result has a file... and the getRepository() matched the stage repo id...
                if (localResult.getFile() != null && localResult.getRepository() != null) {
                    getLog().info("Purging: " + dependency + " from remote repository: " + localResult.getRepository() + ".");
                    File deleteTarget = new File(localRepositoryManager.getRepository().getBasedir(), localRepositoryManager.getPathForLocalArtifact(dependency.getArtifact()));

                    if (deleteTarget.isDirectory()) {
                        try {
                            FileUtils.deleteDirectory(deleteTarget);
                        } catch (IOException ioe) {
                            getLog().warn("Failed to purge stage artifact from local repository: " + deleteTarget, ioe);
                        }
                    } else if (!deleteTarget.delete()) {
                        getLog().warn("Failed to purge stage artifact from local repository: " + deleteTarget);
                    }
                    itemsPurged = true;
                }
            }
        }
    } catch (DependencyResolutionException dre) {
        throw new MojoExecutionException("Initial dependency resolution to resolve dependencies which may have been provided by the 'stage' repository failed.", dre);
    }


    if (itemsPurged) {
        try {
            getLog().info("Resolving purged dependencies...");
            dependenciesResolver.resolve(new DefaultDependencyResolutionRequest(project, reresolveSession));
            getLog().info("All stage dependencies purged and re-resolved.");
        } catch (DependencyResolutionException e) {
            throw new MojoExecutionException("Post-purge dependency resolution failed!", e);
        }
    }
}