예제 #1
0
  public List<ArtifactResult> resolveArtifacts(
      RepositorySystemSession session, Collection<? extends ArtifactRequest> requests)
      throws ArtifactResolutionException {
    List<ArtifactResult> results = new ArrayList<ArtifactResult>();

    for (ArtifactRequest request : requests) {
      ArtifactResult result = new ArtifactResult(request);
      results.add(result);

      Artifact artifact = request.getArtifact();
      if ("maven-test".equals(artifact.getGroupId())) {
        String scope = artifact.getArtifactId().substring("scope-".length());

        try {
          artifact =
              artifact.setFile(
                  ProjectClasspathTest.getFileForClasspathResource(
                      ProjectClasspathTest.dir + "transitive-" + scope + "-dep.xml"));
          result.setArtifact(artifact);
        } catch (FileNotFoundException e) {
          throw new IllegalStateException("Missing test POM for " + artifact);
        }
      } else {
        result.addException(new ArtifactNotFoundException(artifact, null));
        throw new ArtifactResolutionException(results);
      }
    }

    return results;
  }
  /**
   * Get the file with Jenkins to run.
   *
   * <p>The file will exist on machine where tests run.
   */
  @Provides
  @Named("jenkins.war")
  public File getJenkinsWar(
      RepositorySystem repositorySystem, RepositorySystemSession repositorySystemSession) {
    try {
      return IOUtil.firstExisting(
          false, System.getenv("JENKINS_WAR"), getWorkspace() + "/jenkins.war", "./jenkins.war");
    } catch (IOException ex) {
      // Fall-through
    }

    String version = System.getenv("JENKINS_VERSION");
    if (version != null && !version.isEmpty()) {
      ArtifactResolverUtil resolverUtil =
          new ArtifactResolverUtil(repositorySystem, repositorySystemSession);
      ArtifactResult resolvedArtifact =
          resolverUtil.resolve(
              new DefaultArtifact("org.jenkins-ci.main", "jenkins-war", "war", version));
      return resolvedArtifact.getArtifact().getFile();
    }

    // TODO add support for 'lts', 'lts-rc', 'latest' and 'latest-rc'

    throw new Error(
        "Could not find jenkins.war, use JENKINS_WAR or JENKINS_VERSION to specify it.");
  }
 /**
  * Provides the path to the form elements plug-in. Uses the Maven repository to obtain the plugin.
  *
  * @return the path to the form elements plug-in
  */
 @Named("form-element-path.hpi")
 @Provides
 public File getFormElementsPathFile(
     RepositorySystem repositorySystem, RepositorySystemSession repositorySystemSession) {
   ArtifactResolverUtil resolverUtil =
       new ArtifactResolverUtil(repositorySystem, repositorySystemSession);
   ArtifactResult resolvedArtifact =
       resolverUtil.resolve(
           new DefaultArtifact("org.jenkins-ci.plugins", "form-element-path", "hpi", "1.4"));
   return resolvedArtifact.getArtifact().getFile();
 }
 public File downloadArtifact(String groupId, String artifactId, String packaging, String version)
     throws ArtifactResolutionException {
   LOGGER.debug("Downloading artifact asd");
   RepositorySystem repositorySystem = newRepositorySystem();
   RepositorySystemSession session = newSession(repositorySystem);
   ArtifactRequest artifactRequest = new ArtifactRequest();
   artifactRequest.setArtifact(
       new DefaultArtifact(groupId, artifactId, packaging.toLowerCase(), version));
   Builder builder =
       new RemoteRepository.Builder("central", "default", "http://repo.maven.apache.org/maven2");
   artifactRequest.addRepository(builder.build());
   ArtifactResult artifactResult = repositorySystem.resolveArtifact(session, artifactRequest);
   return artifactResult.getArtifact().getFile();
 }
  @Override
  public InputStream openStream() throws IOException {
    RepositorySystem repositorySystem;
    RepositoryConnectorProvider repositoryConnectorProvider;
    try {
      repositorySystem = this.plexusContainer.lookup(RepositorySystem.class);
      repositoryConnectorProvider = this.plexusContainer.lookup(RepositoryConnectorProvider.class);
    } catch (ComponentLookupException e) {
      throw new IOException("Failed to get org.sonatype.aether.RepositorySystem component", e);
    }

    RepositorySystemSession session = this.repository.createRepositorySystemSession();

    RepositoryConnector connector;
    try {
      connector =
          repositoryConnectorProvider.newRepositoryConnector(
              session, this.repository.getRemoteRepository());
    } catch (NoRepositoryConnectorException e) {
      throw new IOException("Failed to download artifact [" + this.artifact + "]", e);
    }

    ArtifactDownload download = new ArtifactDownload();
    download.setArtifact(this.artifact);
    download.setRepositories(Arrays.asList(this.repository.getRemoteRepository()));

    try {
      connector.get(Arrays.asList(download), null);
    } finally {
      connector.close();
    }

    // /////////////////////////////////////////////////////////////////////////////:

    ArtifactRequest artifactRequest = new ArtifactRequest();
    artifactRequest.addRepository(this.repository.getRemoteRepository());
    artifactRequest.setArtifact(this.artifact);

    ArtifactResult artifactResult;
    try {
      artifactResult = repositorySystem.resolveArtifact(session, artifactRequest);
    } catch (ArtifactResolutionException e) {
      throw new IOException("Failed to resolve artifact", e);
    }

    File aetherFile = artifactResult.getArtifact().getFile();

    return new AetherExtensionFileInputStream(aetherFile);
  }
  protected File resolveArtifact(Artifact artifact)
      throws MojoExecutionException, DependencyCollectionException {
    ArtifactRequest request = new ArtifactRequest();
    request.setArtifact(artifact);
    request.setRepositories(remoteRepos);

    ArtifactResult result;
    try {
      result = repositorySystem.resolveArtifact(repoSession, request);
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    }

    return result.getArtifact().getFile();
  }
예제 #7
0
 @Override
 public void packageResolveFailed(DependencyResolutionException exception) {
   clearProgressBar();
   Artifact artifact = exception.getResult().getRoot().getArtifact();
   try {
     reader.println(
         String.format(
             "Could not resolve dependencies for %s.%s version %s",
             artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()));
     reader.println("The following artifacts could not be located:");
     for (ArtifactResult result : exception.getResult().getArtifactResults()) {
       if (result.isMissing()) {
         reader.println("* " + result.getRequest().getArtifact());
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
예제 #8
0
  public static Optional<File> resolveArtifact(
      String groupId,
      String artifactId,
      String version,
      Optional<String> type,
      Optional<String> classifier,
      Optional<List<Repository>> customRepositories) {
    Optional<File> result;

    LocalRepository localRepository =
        MavenSettingsUtil.getLocalRepository(MavenSettingsUtil.loadSettings());
    RepositorySystem system = AetherBootstrap.newRepositorySystem();
    RepositorySystemSession session =
        AetherBootstrap.newRepositorySystemSession(
            system, localRepository.getBasedir().getAbsolutePath());

    Artifact artifact =
        new DefaultArtifact(groupId, artifactId, classifier.orNull(), type.orNull(), version);
    ArtifactRequest artifactRequest = new ArtifactRequest();
    artifactRequest.setArtifact(artifact);
    artifactRequest.setRepositories(
        MavenSettingsUtil.getRemoteRepositories(
            MavenSettingsUtil.loadSettings(), customRepositories.orNull()));

    try {
      ArtifactResult artifactResult = system.resolveArtifact(session, artifactRequest);
      artifact = artifactResult.getArtifact();
      if (artifact != null) {
        result = Optional.fromNullable(artifact.getFile());
      } else {
        result = Optional.absent();
      }
    } catch (ArtifactResolutionException e) {
      // TODO add error handling -> maybe throw an exception that indicates the error or return an
      // Optional
      result = Optional.absent();
    }

    return result;
  }
예제 #9
0
  URL createMavenGavURL(String artifactGav) throws MalformedURLException {
    Artifact artifact = new DefaultArtifact(artifactGav);
    if (artifact.getVersion() == null) {
      throw new IllegalArgumentException("Null version");
    }

    VersionScheme versionScheme = new GenericVersionScheme();
    try {
      versionScheme.parseVersion(artifact.getVersion());
    } catch (InvalidVersionSpecificationException e) {
      throw new IllegalArgumentException(e);
    }

    try {
      versionScheme.parseVersionRange(artifact.getVersion());
      throw new IllegalArgumentException(
          artifact.getVersion() + " is a version range. A specific version is needed");
    } catch (InvalidVersionSpecificationException expected) {

    }

    RepositorySystemSession session = newRepositorySystemSession();

    ArtifactRequest artifactRequest = new ArtifactRequest();
    artifactRequest.setArtifact(artifact);
    for (RemoteRepository remoteRepo : remoteRepositories) {
      artifactRequest.addRepository(remoteRepo);
    }

    ArtifactResult artifactResult;
    try {
      artifactResult = REPOSITORY_SYSTEM.resolveArtifact(session, artifactRequest);
    } catch (ArtifactResolutionException e) {
      throw new RuntimeException(e);
    }

    File file = artifactResult.getArtifact().getFile().getAbsoluteFile();
    return file.toURI().toURL();
  }
예제 #10
0
  public static File getSdk(
      String version,
      RepositorySystem repoSystem,
      RepositorySystemSession repoSession,
      List<RemoteRepository>... repos)
      throws MojoExecutionException {

    List<RemoteRepository> allRepos = ImmutableList.copyOf(Iterables.concat(repos));

    ArtifactRequest request =
        new ArtifactRequest(
            new DefaultArtifact(SDK_GROUP_ID, SDK_ARTIFACT_ID, SDK_EXTENSION, version),
            allRepos,
            null);

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

    File sdkArchive = result.getArtifact().getFile();
    File sdkRepoDir = sdkArchive.getParentFile();
    File sdkBaseDir = new File(sdkRepoDir, SDK_ARTIFACT_ID);

    if (sdkBaseDir.exists() && !sdkBaseDir.isDirectory()) {
      throw new MojoExecutionException(
          "Could not unpack the SDK because there is an unexpected file at "
              + sdkBaseDir
              + " which conflicts with where we plan to unpack the SDK.");
    }

    if (!sdkBaseDir.exists()) {
      sdkBaseDir.mkdirs();
    }

    // While processing the zip archive, if we find an initial entry that is a directory, and all
    // entries are a child
    // of this directory, then we append this to the sdkBaseDir we return.
    String sdkBaseDirSuffix = null;

    try {
      ZipFile sdkZipArchive = new ZipFile(sdkArchive);
      Enumeration<? extends ZipEntry> zipEntries = sdkZipArchive.entries();

      if (!zipEntries.hasMoreElements()) {
        throw new MojoExecutionException(
            "The SDK zip archive appears corrupted.  There are no entries in the zip index.");
      }

      ZipEntry firstEntry = zipEntries.nextElement();
      if (firstEntry.isDirectory()) {
        sdkBaseDirSuffix = firstEntry.getName();
      } else {
        // Reinitialize entries
        zipEntries = sdkZipArchive.entries();
      }

      while (zipEntries.hasMoreElements()) {
        ZipEntry zipEntry = zipEntries.nextElement();

        if (!zipEntry.isDirectory()) {
          File zipEntryDestination = new File(sdkBaseDir, zipEntry.getName());

          if (!zipEntry.getName().startsWith(sdkBaseDirSuffix)) {
            // We found an entry that doesn't use this initial base directory, oh well, just set it
            // to null.
            sdkBaseDirSuffix = null;
          }

          if (!zipEntryDestination.exists()) {
            Files.createParentDirs(zipEntryDestination);
            Files.write(
                ByteStreams.toByteArray(sdkZipArchive.getInputStream(zipEntry)),
                zipEntryDestination);
          }
        }
      }

    } catch (IOException e) {
      throw new MojoExecutionException("Could not open SDK zip archive.", e);
    }

    if (sdkBaseDirSuffix == null) {
      return sdkBaseDir;
    }

    return new File(sdkBaseDir, sdkBaseDirSuffix);
  }
예제 #11
0
  List<URL> createMavenGavRecursiveURLs(String artifactGav, String... excludes)
      throws MalformedURLException, DependencyCollectionException, DependencyResolutionException {
    Artifact artifact = new DefaultArtifact(artifactGav);
    if (artifact.getVersion() == null) {
      throw new IllegalArgumentException("Null version");
    }

    VersionScheme versionScheme = new GenericVersionScheme();
    try {
      versionScheme.parseVersion(artifact.getVersion());
    } catch (InvalidVersionSpecificationException e) {
      throw new IllegalArgumentException(e);
    }

    try {
      versionScheme.parseVersionRange(artifact.getVersion());
      throw new IllegalArgumentException(
          artifact.getVersion() + " is a version range. A specific version is needed");
    } catch (InvalidVersionSpecificationException expected) {

    }

    RepositorySystemSession session = newRepositorySystemSession();

    ArtifactRequest artifactRequest = new ArtifactRequest();
    artifactRequest.setArtifact(artifact);
    for (RemoteRepository remoteRepo : remoteRepositories) {
      artifactRequest.addRepository(remoteRepo);
    }

    ArtifactResult artifactResult;
    try {
      artifactResult = REPOSITORY_SYSTEM.resolveArtifact(session, artifactRequest);
    } catch (ArtifactResolutionException e) {
      throw new RuntimeException(e);
    }

    List<URL> urls = new ArrayList<>();
    urls.add(artifactToUrl(artifactResult.getArtifact()));

    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(new Dependency(artifact, "compile"));
    for (RemoteRepository remoteRepo : remoteRepositories) {
      collectRequest.addRepository(remoteRepo);
    }

    DependencyNode node = REPOSITORY_SYSTEM.collectDependencies(session, collectRequest).getRoot();
    DependencyFilter filter = new ExclusionsDependencyFilter(Arrays.asList(excludes));
    DependencyRequest dependencyRequest = new DependencyRequest(node, filter);

    REPOSITORY_SYSTEM.resolveDependencies(session, dependencyRequest);

    PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
    node.accept(nlg);
    for (Artifact cur : nlg.getArtifacts(false)) {
      urls.add(artifactToUrl(cur));
    }

    log.debug("--------------------");
    log.debug(nlg.getClassPath());
    log.debug("--------------------");

    return urls;
  }
  private void resolveOld(
      Artifact artifact,
      List<ArtifactRepository> remoteRepositories,
      RepositorySystemSession session)
      throws ArtifactResolutionException, ArtifactNotFoundException {
    if (artifact == null) {
      return;
    }

    if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) {
      File systemFile = artifact.getFile();

      if (systemFile == null) {
        throw new ArtifactNotFoundException(
            "System artifact: " + artifact + " has no file attached", artifact);
      }

      if (!systemFile.exists()) {
        throw new ArtifactNotFoundException(
            "System artifact: " + artifact + " not found in path: " + systemFile, artifact);
      }

      if (!systemFile.isFile()) {
        throw new ArtifactNotFoundException(
            "System artifact: " + artifact + " is not a file: " + systemFile, artifact);
      }

      artifact.setResolved(true);

      return;
    }

    if (!artifact.isResolved()) {
      ArtifactResult result;

      try {
        ArtifactRequest artifactRequest = new ArtifactRequest();
        artifactRequest.setArtifact(RepositoryUtils.toArtifact(artifact));
        artifactRequest.setRepositories(RepositoryUtils.toRepos(remoteRepositories));

        // Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved
        // or not
        LocalRepositoryManager lrm = session.getLocalRepositoryManager();
        String path = lrm.getPathForLocalArtifact(artifactRequest.getArtifact());
        artifact.setFile(new File(lrm.getRepository().getBasedir(), path));

        result = repoSystem.resolveArtifact(session, artifactRequest);
      } catch (org.eclipse.aether.resolution.ArtifactResolutionException e) {
        if (e.getCause() instanceof org.eclipse.aether.transfer.ArtifactNotFoundException) {
          throw new ArtifactNotFoundException(
              e.getMessage(),
              artifact.getGroupId(),
              artifact.getArtifactId(),
              artifact.getVersion(),
              artifact.getType(),
              artifact.getClassifier(),
              remoteRepositories,
              artifact.getDownloadUrl(),
              artifact.getDependencyTrail(),
              e);
        } else {
          throw new ArtifactResolutionException(e.getMessage(), artifact, remoteRepositories, e);
        }
      }

      artifact.selectVersion(result.getArtifact().getVersion());
      artifact.setFile(result.getArtifact().getFile());
      artifact.setResolved(true);

      if (artifact.isSnapshot()) {
        Matcher matcher = Artifact.VERSION_FILE_PATTERN.matcher(artifact.getVersion());
        if (matcher.matches()) {
          Snapshot snapshot = new Snapshot();
          snapshot.setTimestamp(matcher.group(2));
          try {
            snapshot.setBuildNumber(Integer.parseInt(matcher.group(3)));
            artifact.addMetadata(new SnapshotArtifactRepositoryMetadata(artifact, snapshot));
          } catch (NumberFormatException e) {
            logger.warn(
                "Invalid artifact version " + artifact.getVersion() + ": " + e.getMessage());
          }
        }
      }
    }
  }
  private Set<MavenRepositoryMetadata> getRepositoriesResolvingArtifact(
      final GAV gav, final MavenProject mavenProject) {
    ArtifactResult result = null;
    ArtifactRequest artifactRequest = null;

    final String artifactName = gav.toString();
    final Artifact artifact = new DefaultArtifact(artifactName);
    final Aether aether = new Aether(mavenProject);

    final Set<MavenRepositoryMetadata> repositoriesResolvingArtifact =
        new HashSet<MavenRepositoryMetadata>();
    final Map<MavenRepositorySource, Collection<RemoteRepository>> repositories =
        getRemoteRepositories(mavenProject);

    // Local Repository
    artifactRequest = new ArtifactRequest();
    artifactRequest.setArtifact(artifact);
    try {
      result = aether.getSystem().resolveArtifact(aether.getSession(), artifactRequest);
      if (result != null && result.isResolved()) {
        final MavenRepositoryMetadata artifactRepositoryMetaData =
            makeRepositoryMetaData(result.getRepository(), MavenRepositorySource.LOCAL);
        if (artifactRepositoryMetaData != null) {
          repositoriesResolvingArtifact.add(artifactRepositoryMetaData);
        }
      }
    } catch (ArtifactResolutionException are) {
      // Ignore - this means the Artifact could not be resolved against the given RemoteRepository
    }

    // Remote Repositories
    try {
      for (Map.Entry<MavenRepositorySource, Collection<RemoteRepository>> e :
          repositories.entrySet()) {
        for (ArtifactRepository repository : e.getValue()) {
          artifactRequest = new ArtifactRequest();
          artifactRequest.setArtifact(artifact);
          java.nio.file.Path tempLocalRepositoryBasePath = null;
          try {
            // Maven always tries to resolve against LocalRepository first, which is not much use
            // when we want to check
            // if the Artifact is available on a RemoteRepository. Therefore substitute the default
            // RepositorySystemSession
            // with one that provides a LocalRepositoryManager that always uses an empty transient
            // LocalRepository to ensure
            // Maven does not resolve Artifacts locally.
            artifactRequest.addRepository((RemoteRepository) repository);
            tempLocalRepositoryBasePath = getRepositoryPath(gav);
            result =
                aether
                    .getSystem()
                    .resolveArtifact(
                        new MavenRepositorySystemSessionWrapper(
                            tempLocalRepositoryBasePath.toString(), aether.getSession()),
                        artifactRequest);

            if (result != null && result.isResolved()) {
              final MavenRepositoryMetadata artifactRepositoryMetaData =
                  makeRepositoryMetaData(result.getRepository(), e.getKey());
              if (artifactRepositoryMetaData != null) {
                repositoriesResolvingArtifact.add(artifactRepositoryMetaData);
              }
            }

          } catch (ArtifactResolutionException are) {
            // Ignore - this means the Artifact could not be resolved against the given
            // RemoteRepository
          } finally {
            tearDownMavenRepository(tempLocalRepositoryBasePath);
          }
        }
      }

    } catch (IOException ioe) {
      log.error(
          "Error resolving '"
              + gav.toString()
              + "' against Repositories. Returning empty Collection. ",
          ioe);
    }

    return repositoriesResolvingArtifact;
  }