下面列出了怎么用org.apache.maven.project.DependencyResolutionResult的API类实例代码及写法,或者点击链接到github查看源代码。
@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)");
}
}
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);
}
@BeforeEach
void before() throws Exception {
this.globalFilter = mock(ArtifactFilter.class);
ArtifactFilter transitiveIncludeExcludeFilter = mock(ArtifactFilter.class);
ArtifactFilter targetFilter = mock(ArtifactFilter.class);
when(this.globalFilter.include(any())).thenReturn(true);
when(transitiveIncludeExcludeFilter.include(any())).thenReturn(true);
when(targetFilter.include(any())).thenReturn(true);
DependencyResolutionResult dependencyResolutionResult = mock(DependencyResolutionResult.class);
org.eclipse.aether.graph.DependencyNode dependencyNode = mock(org.eclipse.aether.graph.DependencyNode.class);
when(dependencyResolutionResult.getDependencyGraph()).thenReturn(dependencyNode);
this.dependenciesResolver = mock(ProjectDependenciesResolver.class);
when(this.dependenciesResolver.resolve(any(DependencyResolutionRequest.class))).thenReturn(dependencyResolutionResult);
this.adapter = new MavenGraphAdapter(this.dependenciesResolver, transitiveIncludeExcludeFilter, targetFilter, EnumSet.of(INCLUDED));
this.graphBuilder = GraphBuilder.create(ToStringNodeIdRenderer.INSTANCE);
}
@BeforeEach
void before() throws Exception {
Artifact projectArtifact = mock(Artifact.class);
this.mavenProject = new MavenProject();
this.mavenProject.setArtifact(projectArtifact);
ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
when(projectBuildingRequest.getRepositorySession()).thenReturn(mock(RepositorySystemSession.class));
//noinspection deprecation
this.mavenProject.setProjectBuildingRequest(projectBuildingRequest);
this.globalFilter = mock(ArtifactFilter.class);
ArtifactFilter transitiveIncludeExcludeFilter = mock(ArtifactFilter.class);
ArtifactFilter targetFilter = mock(ArtifactFilter.class);
this.graphBuilder = GraphBuilder.create(ToStringNodeIdRenderer.INSTANCE);
this.dependenciesResolver = mock(ProjectDependenciesResolver.class);
DependencyResolutionResult dependencyResolutionResult = mock(DependencyResolutionResult.class);
when(dependencyResolutionResult.getDependencyGraph()).thenReturn(mock(org.eclipse.aether.graph.DependencyNode.class));
when(this.dependenciesResolver.resolve(any(DependencyResolutionRequest.class))).thenReturn(dependencyResolutionResult);
this.graphAdapter = new MavenGraphAdapter(this.dependenciesResolver, transitiveIncludeExcludeFilter, targetFilter, EnumSet.of(INCLUDED));
}
/** 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);
}
}
private static ClassPathResult buildClassPathResult(DependencyResolutionResult result)
throws EnforcerRuleException {
// The root node must have the project's JAR file
DependencyNode root = result.getDependencyGraph();
File rootFile = root.getArtifact().getFile();
if (rootFile == null) {
throw new EnforcerRuleException("The root project artifact is not associated with a file.");
}
List<Dependency> unresolvedDependencies = result.getUnresolvedDependencies();
Set<Artifact> unresolvedArtifacts =
unresolvedDependencies.stream().map(Dependency::getArtifact).collect(toImmutableSet());
DependencyGraph dependencyGraph = DependencyGraph.from(root);
ImmutableListMultimap.Builder<ClassPathEntry, DependencyPath> builder =
ImmutableListMultimap.builder();
ImmutableList.Builder<UnresolvableArtifactProblem> problems = ImmutableList.builder();
for (DependencyPath path : dependencyGraph.list()) {
Artifact artifact = path.getLeaf();
if (unresolvedArtifacts.contains(artifact)) {
problems.add(new UnresolvableArtifactProblem(artifact));
} else {
builder.put(new ClassPathEntry(artifact), path);
}
}
return new ClassPathResult(builder.build(), problems.build());
}
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());
}
}
@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 boolean _handle(DependencyResolutionResult result) {
Xpp3Dom root = new Xpp3Dom("DependencyResolutionResult");
root.setAttribute("class", result.getClass().getName());
Xpp3Dom dependenciesElt = new Xpp3Dom("resolvedDependencies");
root.addChild(dependenciesElt);
for (Dependency dependency : result.getResolvedDependencies()) {
Artifact artifact = dependency.getArtifact();
if ( !includedScopes.contains(dependency.getScope())) {
continue;
}
if (!includeSnapshots && artifact.isSnapshot()) {
continue;
}
if(!includeReleases && !artifact.isSnapshot()) {
continue;
}
Xpp3Dom dependencyElt = new Xpp3Dom("dependency");
dependencyElt.addChild(newElement("file", artifact.getFile().getAbsolutePath()));
dependencyElt.setAttribute("name", artifact.getFile().getName());
dependencyElt.setAttribute("groupId", artifact.getGroupId());
dependencyElt.setAttribute("artifactId", artifact.getArtifactId());
dependencyElt.setAttribute("version", artifact.getVersion());
dependencyElt.setAttribute("baseVersion", artifact.getBaseVersion());
if (artifact.getClassifier() != null) {
dependencyElt.setAttribute("classifier", artifact.getClassifier());
}
dependencyElt.setAttribute("type", artifact.getExtension());
dependencyElt.setAttribute("id", artifact.getArtifactId());
dependencyElt.setAttribute("extension", artifact.getExtension());
dependencyElt.setAttribute("scope", dependency.getScope());
dependencyElt.setAttribute("optional", Boolean.toString(dependency.isOptional()));
dependencyElt.setAttribute("snapshot", Boolean.toString(artifact.isSnapshot()));
dependenciesElt.addChild(dependencyElt);
}
reporter.print(root);
return true;
}
@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);
}
}
}