类org.apache.maven.project.DependencyResolutionException源码实例Demo

下面列出了怎么用org.apache.maven.project.DependencyResolutionException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: java-specialagent   文件: MutableMojo.java
static void resolveDependencies(final MavenSession session, final MojoExecution execution, final MojoExecutor executor, final ProjectDependenciesResolver projectDependenciesResolver) throws DependencyResolutionException, LifecycleExecutionException {
//    flushProjectArtifactsCache(executor);

    final MavenProject project = session.getCurrentProject();
    final Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();
    final Map<String,List<MojoExecution>> executions = new LinkedHashMap<>(execution.getForkedExecutions());
    final ExecutionListener executionListener = session.getRequest().getExecutionListener();
    try {
      project.setDependencyArtifacts(null);
      execution.getForkedExecutions().clear();
      session.getRequest().setExecutionListener(null);
      executor.execute(session, Collections.singletonList(execution), new ProjectIndex(session.getProjects()));
    }
    finally {
      execution.getForkedExecutions().putAll(executions);
      session.getRequest().setExecutionListener(executionListener);
      project.setDependencyArtifacts(dependencyArtifacts);
    }

    projectDependenciesResolver.resolve(newDefaultDependencyResolutionRequest(session));
  }
 
源代码2 项目: java-specialagent   文件: CompatibilityTestMojo.java
private void assertCompatibility(final Dependency[] dependencies, final boolean shouldPass) throws DependencyResolutionException, IOException, LifecycleExecutionException, MojoExecutionException {
  final Dependency[] rollback = replaceDependencies(getProject().getDependencies(), dependencies);

  getLog().info("|-- " + print(dependencies));
  resolveDependencies();
  final List<URL> classpath = new ArrayList<>();
  for (final Artifact artifact : getProject().getArtifacts())
    classpath.add(AssembleUtil.toURL(MavenUtil.getPathOf(localRepository.getBasedir(), artifact)));

  if (isDebug())
    getLog().warn(classpath.toString());

  try (final URLClassLoader classLoader = new URLClassLoader(classpath.toArray(new URL[classpath.size()]), null)) {
    final LibraryFingerprint fingerprint = LibraryFingerprint.fromFile(new File(getProject().getBuild().getOutputDirectory(), UtilConstants.FINGERPRINT_FILE).toURI().toURL());
    final List<FingerprintError> errors = fingerprint.isCompatible(classLoader);
    if (errors == null != shouldPass) {
      final String error = print(dependencies) + " should have " + (errors == null ? "failed" : "passed:\n" + AssembleUtil.toIndentedString(errors));
      if (failAtEnd)
        this.errors.add(error);
      else
        throw new MojoExecutionException(error + "\nClasspath:\n" + AssembleUtil.toIndentedString(classpath));
    }
  }

  rollbackDependencies(getProject().getDependencies(), rollback);
}
 
@Test
public void testExecute_shouldPassGoodProject_sessionProperties()
    throws EnforcerRuleException, RepositoryException, DependencyResolutionException {
  setupMockDependencyResolution("com.google.guava:guava:27.0.1-jre");

  rule.execute(mockRuleHelper);

  ArgumentCaptor<DependencyResolutionRequest> argumentCaptor =
      ArgumentCaptor.forClass(DependencyResolutionRequest.class);
  verify(mockProjectDependenciesResolver).resolve(argumentCaptor.capture());
  Map<String, String> propertiesUsedInSession =
      argumentCaptor.getValue().getRepositorySession().getSystemProperties();
  Truth.assertWithMessage(
          "RepositorySystemSession should have variables such as os.detected.classifier")
      .that(propertiesUsedInSession)
      .containsAtLeastEntriesIn(OsProperties.detectOsProperties());
  // There was a problem in resolving profiles because original properties were missing (#817)
  Truth.assertWithMessage("RepositorySystemSession should have original properties")
      .that(propertiesUsedInSession)
      .containsAtLeastEntriesIn(repositorySystemSession.getSystemProperties());
}
 
@Test
public void testArtifactTransferError()
    throws RepositoryException, DependencyResolutionException {
  DependencyNode graph = createResolvedDependencyGraph("org.apache.maven:maven-core:jar:3.5.2");
  DependencyResolutionResult resolutionResult = mock(DependencyResolutionResult.class);
  when(resolutionResult.getDependencyGraph()).thenReturn(graph);
  DependencyResolutionException exception =
      createDummyResolutionException(
          new DefaultArtifact("aopalliance:aopalliance:1.0"), resolutionResult);
  when(mockProjectDependenciesResolver.resolve(any())).thenThrow(exception);

  try {
    rule.execute(mockRuleHelper);
    fail("The rule should throw EnforcerRuleException upon dependency resolution exception");
  } catch (EnforcerRuleException expected) {
    verify(mockLog)
        .warn(
            "aopalliance:aopalliance:jar:1.0 was not resolved. "
                + "Dependency path: a:b:jar:0.1 > "
                + "org.apache.maven:maven-core:jar:3.5.2 (compile) > "
                + "com.google.inject:guice:jar:no_aop:4.0 (compile) > "
                + "aopalliance:aopalliance:jar:1.0 (compile)");
  }
}
 
源代码5 项目: depgraph-maven-plugin   文件: MavenGraphAdapter.java
public void buildDependencyGraph(MavenProject project, ArtifactFilter globalFilter, GraphBuilder<DependencyNode> graphBuilder) {
  DefaultDependencyResolutionRequest request = new DefaultDependencyResolutionRequest();
  request.setMavenProject(project);
  request.setRepositorySession(getVerboseRepositorySession(project));

  DependencyResolutionResult result;
  try {
    result = this.dependenciesResolver.resolve(request);
  } catch (DependencyResolutionException e) {
    throw new DependencyGraphException(e);
  }

  org.eclipse.aether.graph.DependencyNode root = result.getDependencyGraph();
  ArtifactFilter transitiveDependencyFilter = createTransitiveDependencyFilter(project);

  GraphBuildingVisitor visitor = new GraphBuildingVisitor(graphBuilder, globalFilter, transitiveDependencyFilter, this.targetFilter, this.includedResolutions);
  root.accept(visitor);
}
 
private List<String> dependencies(MavenProject project, MavenSession session) {
    try {
        return dependenciesResolver.resolve(new DefaultDependencyResolutionRequest(project, session.getRepositorySession())
                .setResolutionFilter(DEPENDENCY_FILTER))
                .getDependencies()
                .stream()
                .map(d -> d.getArtifact().getFile().toString())
                .collect(Collectors.toList());
    } catch (DependencyResolutionException e) {
        throw new RuntimeException("Dependency resolution failed: " + e.getMessage());
    }
}
 
源代码7 项目: java-specialagent   文件: FingerprintMojo.java
private void createDependenciesTgf() throws DependencyResolutionException, IOException, LifecycleExecutionException, MojoExecutionException, MojoFailureException {
  final File file = new File(getProject().getBuild().getOutputDirectory(), "dependencies.tgf");
  getLog().info("--> dependencies.tgf <--");
  HackMojo.setField(TreeMojo.class, this, "outputType", "tgf");
  HackMojo.setField(TreeMojo.class, this, "outputFile", file);
  super.execute();

  if (isolatedDependencies == null || isolatedDependencies.size() == 0)
    return;

  try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
    for (String line; (line = raf.readLine()) != null;) {
      if ("#".equals(line)) {
        raf.seek(raf.getFilePointer() - 3);
        for (final IsolatedDependency isolatedDependency : isolatedDependencies) {
          if (isolatedDependency.getVersion() != null)
            throw new MojoExecutionException("Version of " + isolatedDependency + " must be specified in <dependencyManagement>");

          isolatedDependency.setVersion(MavenUtil.lookupVersion(getProject(), isolatedDependency));
          raf.write(("\n0 " + isolatedDependency.getGroupId() + ":" + isolatedDependency.getArtifactId() + ":jar:" + isolatedDependency.getVersion() + ":isolated").getBytes());
        }

        raf.write("\n#".getBytes());
        raf.setLength(raf.getFilePointer());

        final Dependency[] rollback = MutableMojo.replaceDependencies(getProject().getDependencies(), MavenDependency.toDependencies(isolatedDependencies));
        MutableMojo.resolveDependencies(getSession(), execution, executor, projectDependenciesResolver);
        MutableMojo.rollbackDependencies(getProject().getDependencies(), rollback);
        MutableMojo.resolveDependencies(getSession(), execution, executor, projectDependenciesResolver);
        return;
      }
    }
  }

  throw new MojoExecutionException("Could not write isolated dependencies into dependencies.tgf");
}
 
源代码8 项目: java-specialagent   文件: FingerprintMojo.java
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
  if (isRunning)
    return;

  isRunning = true;
  if (isSkip()) {
    getLog().info("Skipping plugin execution");
    return;
  }

  if ("pom".equalsIgnoreCase(getProject().getPackaging())) {
    getLog().info("Skipping for \"pom\" module.");
    return;
  }

  try {
    for (final Artifact artifact : getProject().getDependencyArtifacts()) {
      if ("io.opentracing".equals(artifact.getGroupId()) && "opentracing-api".equals(artifact.getArtifactId())) {
        apiVersion = artifact.getVersion();
        break;
      }
    }

    createDependenciesTgf();
    createFingerprintBin();
    createLocalRepoFile();
    createPluginName();
  }
  catch (final DependencyResolutionException | IOException | LifecycleExecutionException e) {
    throw new MojoFailureException(e.getMessage(), e);
  }
  finally {
    isRunning = false;
  }
}
 
源代码9 项目: java-specialagent   文件: CompatibilityTestMojo.java
private void assertCompatibility(final List<CompatibilitySpec> compatibilitySpecs, final boolean shouldPass) throws DependencyResolutionException, IOException, LifecycleExecutionException, MojoExecutionException, InvalidVersionSpecificationException {
  getLog().info("Running " + (shouldPass ? "PASS" : "FAIL") + " compatibility tests...");
  for (final CompatibilitySpec compatibilitySpec : compatibilitySpecs) {
    String versionSpec = null;
    int numSpecs = -1;
    final int size = compatibilitySpec.getDependencies().size();
    final List<Dependency>[] resolvedVersions = new List[size];
    for (int i = 0; i < size; ++i) {
      final ResolvableDependency dependency = compatibilitySpec.getDependencies().get(i);
      final boolean isSingleVersion = dependency.isSingleVersion();
      if (!isSingleVersion) {
        if (versionSpec == null)
          versionSpec = dependency.getVersion();
        else if (!versionSpec.equals(dependency.getVersion()))
          throw new MojoExecutionException("Version across all dependencies in a <pass> or <fail> spec must be equal");
      }

      resolvedVersions[i] = dependency.resolveVersions(getProject(), getLog());
      if (!isSingleVersion) {
        if (numSpecs == -1)
          numSpecs = resolvedVersions[i].size();
        else if (numSpecs != resolvedVersions[i].size())
          throw new MojoExecutionException("Expeted the same number of resolved versions for: " + compatibilitySpec);
      }
    }

    if (numSpecs == -1)
      numSpecs = 1;

    for (int i = 0; i < numSpecs; ++i) {
      final Dependency[] dependencies = new Dependency[resolvedVersions.length];
      for (int j = 0; j < resolvedVersions.length; ++j)
        dependencies[j] = resolvedVersions[j].get(resolvedVersions[j].size() == numSpecs ? i : 0);

      assertCompatibility(dependencies, shouldPass);
    }
  }
}
 
源代码10 项目: java-specialagent   文件: CompatibilityTestMojo.java
@Override
void doExecute() throws MojoExecutionException {
  try {
    if ((passCompatibility != null || failCompatibility != null) && (passes != null || fails != null))
      throw new MojoExecutionException("<{pass/fail}Compatibility> cannot be used in conjuction with <passes> or <fails>");

    if (passCompatibility != null)
      passes = shortFormToLongForm(passCompatibility);

    if (failCompatibility != null)
      fails = shortFormToLongForm(failCompatibility);

    boolean wasRun = false;
    if (passes != null && (wasRun = true))
      assertCompatibility(passes, true);

    if (fails != null && (wasRun = true))
      assertCompatibility(fails, false);

    if (failAtEnd && errors.size() > 0)
      throw new MojoExecutionException("Failed compatibility tests:\n" + AssembleUtil.toIndentedString(errors));

    if (wasRun) {
      // Reset the dependencies back to original
      resolveDependencies();
      return;
    }

    final List<Dependency> fingerprintedDependencies = getFingerprintedDependencies();
    if (fingerprintedDependencies.size() > 0)
      throw new MojoExecutionException("No compatibility tests were run for verions of:\n" + AssembleUtil.toIndentedString(fingerprintedDependencies));
  }
  catch (final DependencyResolutionException | IOException | InvalidVersionSpecificationException | LifecycleExecutionException e) {
    throw new MojoExecutionException(e.getMessage(), e);
  }
}
 
源代码11 项目: cloud-opensource-java   文件: LinkageCheckerRule.java
/** Returns class path built from partial dependency graph of {@code resolutionException}. */
private static ClassPathResult buildClasspathFromException(
    DependencyResolutionException resolutionException) throws EnforcerRuleException {
  DependencyResolutionResult result = resolutionException.getResult();

  for (Throwable cause = resolutionException.getCause();
      cause != null;
      cause = cause.getCause()) {
    if (cause instanceof ArtifactTransferException) {
      
      DependencyNode root = result.getDependencyGraph();
      DependencyGraph graph = new DependencyGraph(root);
      
      ArtifactTransferException artifactException = (ArtifactTransferException) cause;
      Artifact artifact = artifactException.getArtifact();
      String warning = graph.createUnresolvableArtifactProblem(artifact).toString();
      logger.warn(warning);
      break;
    }
  }
  if (result.getResolvedDependencies().isEmpty()) {
    // Nothing is resolved. Probably failed at collection phase before resolve phase.
    throw new EnforcerRuleException("Unable to collect dependencies", resolutionException);
  } else {
    // The exception is acceptable enough to build a class path.
    return buildClassPathResult(result);
  }
}
 
@Before
public void setup()
    throws ExpressionEvaluationException, ComponentLookupException,
    DependencyResolutionException, URISyntaxException {
  repositorySystem = RepositoryUtility.newRepositorySystem();
  repositorySystemSession = RepositoryUtility.newSession(repositorySystem);
  dummyArtifactWithFile = createArtifactWithDummyFile("a:b:0.1");
  setupMock();
}
 
private void setupMock()
    throws ExpressionEvaluationException, ComponentLookupException,
    DependencyResolutionException {
  mockProject = mock(MavenProject.class);
  mockMavenSession = mock(MavenSession.class);
  when(mockMavenSession.getRepositorySession()).thenReturn(repositorySystemSession);
  mockRuleHelper = mock(EnforcerRuleHelper.class);
  mockProjectDependenciesResolver = mock(ProjectDependenciesResolver.class);
  mockDependencyResolutionResult = mock(DependencyResolutionResult.class);
  mockLog = mock(Log.class);
  when(mockRuleHelper.getLog()).thenReturn(mockLog);
  when(mockRuleHelper.getComponent(ProjectDependenciesResolver.class))
      .thenReturn(mockProjectDependenciesResolver);
  when(mockProjectDependenciesResolver.resolve(any(DependencyResolutionRequest.class)))
      .thenReturn(mockDependencyResolutionResult);
  when(mockRuleHelper.evaluate("${session}")).thenReturn(mockMavenSession);
  when(mockRuleHelper.evaluate("${project}")).thenReturn(mockProject);
  mockMojoExecution = mock(MojoExecution.class);
  when(mockMojoExecution.getLifecyclePhase()).thenReturn("verify");
  when(mockRuleHelper.evaluate("${mojoExecution}")).thenReturn(mockMojoExecution);
  org.apache.maven.artifact.DefaultArtifact rootArtifact =
      new org.apache.maven.artifact.DefaultArtifact(
          "com.google.cloud",
          "linkage-checker-rule-test",
          "0.0.1",
          "compile",
          "jar",
          null,
          new DefaultArtifactHandler());
  rootArtifact.setFile(new File("dummy.jar"));
  when(mockProject.getArtifact()).thenReturn(rootArtifact);
}
 
private DependencyResolutionException createDummyResolutionException(
    Artifact missingArtifact, DependencyResolutionResult resolutionResult) {
  Throwable cause3 = new ArtifactNotFoundException(missingArtifact, null);
  Throwable cause2 = new ArtifactResolutionException(null, "dummy 3", cause3);
  Throwable cause1 = new DependencyResolutionException(resolutionResult, "dummy 2", cause2);
  DependencyResolutionException exception =
      new DependencyResolutionException(resolutionResult, "dummy 1", cause1);
  return exception;
}
 
@Test
public void testArtifactTransferError_missingArtifactNotInGraph()
    throws URISyntaxException, DependencyResolutionException, EnforcerRuleException {
  // Creating a dummy tree
  //   com.google.foo:project
  //     +- com.google.foo:child1 (provided)
  //        +- com.google.foo:child2 (optional)
  DefaultDependencyNode child2 =
      new DefaultDependencyNode(
          new Dependency(
              createArtifactWithDummyFile("com.google.foo:child2:1.0.0"), "compile", true));
  DefaultDependencyNode child1 =
      new DefaultDependencyNode(
          new Dependency(createArtifactWithDummyFile("com.google.foo:child1:1.0.0"), "provided"));
  child1.setChildren(ImmutableList.of(child2));
  DefaultDependencyNode root =
      new DefaultDependencyNode(createArtifactWithDummyFile("com.google.foo:project:1.0.0"));
  root.setChildren(ImmutableList.of(child1));

  DependencyResolutionResult resolutionResult = mock(DependencyResolutionResult.class);
  when(resolutionResult.getDependencyGraph()).thenReturn(root);
  when(resolutionResult.getResolvedDependencies())
      .thenReturn(ImmutableList.of(child1.getDependency(), child2.getDependency()));

  // The exception is caused by this node but this node does not appear in the dependency graph.
  DefaultDependencyNode missingArtifactNode =
      new DefaultDependencyNode(
          new Dependency(
              createArtifactWithDummyFile("xerces:xerces-impl:jar:2.6.2"), "compile", true));
  // xerces-impl does not exist in Maven Central
  DependencyResolutionException exception =
      createDummyResolutionException(missingArtifactNode.getArtifact(), resolutionResult);

  when(mockProjectDependenciesResolver.resolve(any())).thenThrow(exception);

  rule.execute(mockRuleHelper);
  verify(mockLog)
      .warn("xerces:xerces-impl:jar:2.6.2 was not resolved. Dependency path is unknown.");
}
 
@Test
void dependencyGraphWithException() throws Exception {
  DependencyResolutionException exception = new DependencyResolutionException(mock(DependencyResolutionResult.class), "boom", new Exception());
  when(this.dependenciesResolver.resolve(any(DependencyResolutionRequest.class))).thenThrow(exception);

  try {
    this.graphAdapter.buildDependencyGraph(this.mavenProject, this.globalFilter, this.graphBuilder);
    fail("Expect exception");
  } catch (DependencyGraphException e) {
    assertEquals(exception, e.getCause());
  }
}
 
源代码17 项目: java-specialagent   文件: MutableMojo.java
void resolveDependencies() throws DependencyResolutionException, LifecycleExecutionException {
  resolveDependencies(session, execution, executor, projectDependenciesResolver);
}
 
@Test
public void testArtifactTransferError_acceptableMissingArtifact()
    throws URISyntaxException, DependencyResolutionException, EnforcerRuleException {
  // Creating a dummy tree
  //   com.google.foo:project
  //     +- com.google.foo:child1 (provided)
  //        +- com.google.foo:child2 (optional)
  //           +- xerces:xerces-impl:jar:2.6.2 (optional)
  DefaultDependencyNode missingArtifactNode =
      new DefaultDependencyNode(
          new Dependency(
              createArtifactWithDummyFile("xerces:xerces-impl:jar:2.6.2"), "compile", true));
  DefaultDependencyNode child2 =
      new DefaultDependencyNode(
          new Dependency(
              createArtifactWithDummyFile("com.google.foo:child2:1.0.0"), "compile", true));
  child2.setChildren(ImmutableList.of(missingArtifactNode));
  DefaultDependencyNode child1 =
      new DefaultDependencyNode(
          new Dependency(createArtifactWithDummyFile("com.google.foo:child1:1.0.0"), "provided"));
  child1.setChildren(ImmutableList.of(child2));
  DefaultDependencyNode root =
      new DefaultDependencyNode(createArtifactWithDummyFile("com.google.foo:project:1.0.0"));
  root.setChildren(ImmutableList.of(child1));

  DependencyResolutionResult resolutionResult = mock(DependencyResolutionResult.class);
  when(resolutionResult.getDependencyGraph()).thenReturn(root);
  when(resolutionResult.getResolvedDependencies())
      .thenReturn(
          ImmutableList.of(
              child1.getDependency(),
              child2.getDependency(),
              missingArtifactNode.getDependency()));

  // xerces-impl does not exist in Maven Central
  DependencyResolutionException exception =
      createDummyResolutionException(missingArtifactNode.getArtifact(), resolutionResult);

  when(mockProjectDependenciesResolver.resolve(any())).thenThrow(exception);

  // Should not throw DependencyResolutionException, because the missing xerces-impl is under both
  // provided and optional dependencies.
  rule.execute(mockRuleHelper);
}
 
@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);
        }
    }
}
 
public DependencyGraphException(DependencyResolutionException cause) {
  super(cause);
}