下面列出了org.springframework.core.io.FileUrlResource#org.eclipse.aether.graph.Dependency 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public List<Dependency> resolveDependenciesFromPOM(File pomFile) throws Exception
{
PlexusContainer plexus = new PlexusContainer();
List<Dependency> result;
try
{
ProjectBuildingRequest request = getBuildingRequest(plexus);
request.setResolveDependencies(true);
ProjectBuilder builder = plexus.lookup(ProjectBuilder.class);
ProjectBuildingResult build = builder.build(pomFile, request);
result = build.getDependencyResolutionResult().getDependencies();
}
finally
{
plexus.shutdown();
}
return result;
}
private List<Artifact> getDeployDependencies(Artifact artifact, List<Exclusion> exclusions, boolean testScope, Map<String, String> properties, DeployType type) {
ArtifactDescriptorRequest descriptorRequest = new ArtifactDescriptorRequest();
descriptorRequest.setRepositories(AetherUtil.newRepositories(deployConfig));
descriptorRequest.setArtifact(artifact);
Model model = AetherUtil.readPom(artifact);
if (model == null) {
throw new IllegalStateException("Unable to read POM for " + artifact.getFile());
}
try {
ArtifactDescriptorResult descriptorResult = system.readArtifactDescriptor(session, descriptorRequest);
return descriptorResult.getDependencies().stream()
.filter(d -> type == DeployType.DEFAULT || (type == DeployType.APPLICATION && !d.getArtifact().getExtension().equals("zip")) || (type == DeployType.ARTIFACT && !d.getArtifact().getExtension().equals("jar")))
.filter(d -> "compile".equalsIgnoreCase(d.getScope()) || ("test".equalsIgnoreCase(d.getScope()) && testScope))
.filter(d -> !exclusions.contains(new Exclusion(d.getArtifact().getGroupId(), d.getArtifact().getArtifactId(), null, null)))
.map(Dependency::getArtifact)
.map(d -> this.checkWithModel(model, d, properties))
.collect(Collectors.toList());
} catch (ArtifactDescriptorException e) {
LOG.error("Unable to resolve dependencies for deploy artifact '{}', unable to auto-discover ", artifact, e);
}
return Collections.emptyList();
}
@Override
public void populateResult(RepositorySystemSession session,
ArtifactDescriptorResult result,
Model model) {
super.populateResult(session, result, model);
Parent parent = model.getParent();
if (parent != null) {
DefaultArtifact art =
new DefaultArtifact(parent.getGroupId(),
parent.getArtifactId(),
"pom",
parent.getVersion());
Dependency dep = new Dependency(art, "compile");
result.addDependency(dep);
}
}
@Test
public void testTreeWithScopeConflict() throws IOException
{
DependencyNode root = new DefaultDependencyNode(
new Dependency( new DefaultArtifact( "com.google", "rootArtifact", "jar", "1.0.0" ), "compile" )
);
DependencyNode left = new DefaultDependencyNode(
new Dependency( new DefaultArtifact( "org.apache", "left", "xml", "0.1-SNAPSHOT" ), "test", true )
);
DependencyNode right = new DefaultDependencyNode(
new Dependency( new DefaultArtifact( "com.google", "rootArtifact", "jar", "1.0.0" ), "test" )
);
root.setChildren( Arrays.asList( left, right ) );
String actual = serializer.serialize( root );
File file = new File(getBasedir(), "/target/test-classes/SerializerTests/ScopeConflict.txt");
String expected = FileUtils.readFileToString(file);
Assert.assertEquals(expected, actual);
}
/** 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;
}
@Override
public boolean selectDependency(Dependency dependency)
{
boolean result = false;
if (!isExcluded(dependency))
{
boolean module = this.classifier.equals(dependency.getArtifact().getClassifier());
String scope = dependency.getScope();
if (dependency.isOptional() && depth > 1)
result = false;
else if ("test".equals(scope))
result = false;
else
result = (module && depth == 1) || (!module && !"provided".equals(scope));
}
return result;
}
private void setupMockDependencyResolution(String... coordinates) throws RepositoryException {
// The root node is Maven artifact "a:b:0.1" that has dependencies specified as `coordinates`.
DependencyNode rootNode = createResolvedDependencyGraph(coordinates);
Traverser<DependencyNode> traverser = Traverser.forGraph(node -> node.getChildren());
// DependencyResolutionResult.getDependencies returns depth-first order
ImmutableList<Dependency> dummyDependencies =
ImmutableList.copyOf(traverser.depthFirstPreOrder(rootNode)).stream()
.map(DependencyNode::getDependency)
.filter(Objects::nonNull)
.collect(toImmutableList());
when(mockDependencyResolutionResult.getDependencies()).thenReturn(dummyDependencies);
when(mockDependencyResolutionResult.getResolvedDependencies())
.thenReturn(
ImmutableList.copyOf(traverser.breadthFirst(rootNode.getChildren())).stream()
.map(DependencyNode::getDependency)
.filter(Objects::nonNull)
.collect(toImmutableList()));
when(mockDependencyResolutionResult.getDependencyGraph()).thenReturn(rootNode);
when(mockProject.getDependencies())
.thenReturn(
dummyDependencies.subList(0, coordinates.length).stream()
.map(LinkageCheckerRuleTest::toDependency)
.collect(Collectors.toList()));
}
@Test
public void testExecute_shouldExcludeTestScope() throws EnforcerRuleException {
org.apache.maven.model.Dependency dependency = new org.apache.maven.model.Dependency();
Artifact artifact = new DefaultArtifact("junit:junit:3.8.2");
dependency.setArtifactId(artifact.getArtifactId());
dependency.setGroupId(artifact.getGroupId());
dependency.setVersion(artifact.getVersion());
dependency.setClassifier(artifact.getClassifier());
dependency.setScope("test");
when(mockDependencyResolutionResult.getDependencyGraph()).thenReturn(
new DefaultDependencyNode(dummyArtifactWithFile)
);
when(mockProject.getDependencies())
.thenReturn(ImmutableList.of(dependency));
rule.execute(mockRuleHelper);
}
@Before
public void setUp() throws Exception {
classLoaderResolver = new ClassLoaderResolver(log, repositorySystem, repositorySystemSession, Collections.<RemoteRepository>emptyList());
when(repositorySystem.collectDependencies(eq(repositorySystemSession), any(CollectRequest.class)))
.thenReturn(new CollectResult(new CollectRequest()).setRoot(root));
when(child.getDependency()).thenReturn(new Dependency(new DefaultArtifact(FOO,
BAR,
QUX,
BAZ,
FOO + BAR,
Collections.<String, String>emptyMap(),
new File(FOO + "/" + BAR)), QUX + BAZ));
when(root.accept(any(DependencyVisitor.class))).then(new Answer<Void>() {
public Void answer(InvocationOnMock invocationOnMock) {
DependencyVisitor dependencyVisitor = invocationOnMock.getArgument(0);
dependencyVisitor.visitEnter(child);
dependencyVisitor.visitLeave(child);
return null;
}
});
}
private boolean isExcludedFromParent(Dependency dependency)
{
boolean result = false;
if (parent != null && parent.getExclusions().size() > 0)
{
for (Exclusion exclusion : parent.getExclusions())
{
if (exclusion != null)
{
if (exclusion.getArtifactId() != null
&& exclusion.getArtifactId().equals(dependency.getArtifact().getArtifactId()))
{
if (exclusion.getGroupId() != null
&& exclusion.getGroupId().equals(dependency.getArtifact().getGroupId()))
{
result = true;
break;
}
}
}
}
}
return result;
}
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;
}
private void processPlatformArtifact(DependencyNode node, Path descriptor) throws BootstrapDependencyProcessingException {
final Properties rtProps = resolveDescriptor(descriptor);
if (rtProps == null) {
return;
}
final String value = rtProps.getProperty(BootstrapConstants.PROP_DEPLOYMENT_ARTIFACT);
appBuilder.handleExtensionProperties(rtProps, node.getArtifact().toString());
if (value == null) {
return;
}
Artifact deploymentArtifact = toArtifact(value);
if (deploymentArtifact.getVersion() == null || deploymentArtifact.getVersion().isEmpty()) {
deploymentArtifact = deploymentArtifact.setVersion(node.getArtifact().getVersion());
}
node.setData(QUARKUS_DEPLOYMENT_ARTIFACT, deploymentArtifact);
runtimeNodes.add(node);
Dependency dependency = new Dependency(node.getArtifact(), JavaScopes.COMPILE);
runtimeExtensionDeps.add(dependency);
managedDeps.add(new Dependency(deploymentArtifact, JavaScopes.COMPILE));
}
@Test
public void testCycleBreaking() throws DependencyResolutionException {
RepositorySystem system = RepositoryUtility.newRepositorySystem();
DefaultRepositorySystemSession session =
RepositoryUtility.createDefaultRepositorySystemSession(system);
// This dependencySelector selects everything except test scope. This creates a dependency tree
// with a cycle of dom4j:dom4j:jar:1.6.1 (optional) and jaxen:jaxen:jar:1.1-beta-6 (optional).
session.setDependencySelector(new ScopeDependencySelector("test"));
session.setDependencyGraphTransformer(
new ChainedDependencyGraphTransformer(
new CycleBreakerGraphTransformer(), // This prevents StackOverflowError
new JavaDependencyContextRefiner()));
// dom4j:1.6.1 is known to have a cycle
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRepositories(ImmutableList.of(RepositoryUtility.CENTRAL));
collectRequest.setRoot(new Dependency(new DefaultArtifact("dom4j:dom4j:1.6.1"), "compile"));
DependencyRequest request = new DependencyRequest(collectRequest, null);
// This should not raise StackOverflowError
system.resolveDependencies(session, request);
}
/**
* jaxen-core is an optional dependency that should be included when building a dependency graph
* of JDOM 1.1, no matter how we build the graph.
*/
@Test
public void testDirectOptional() {
DefaultArtifact jdom = new DefaultArtifact("org.jdom:jdom:1.1");
DependencyGraph fullGraph =
dependencyGraphBuilder.buildFullDependencyGraph(Arrays.asList(jdom));
int jaxenCount = countArtifactId(fullGraph, "jaxen-core");
Assert.assertEquals(1, jaxenCount);
DependencyGraph mavenGraph =
dependencyGraphBuilder
.buildMavenDependencyGraph(new Dependency(jdom, "compile"));
Assert.assertEquals(1, countArtifactId(mavenGraph, "jaxen-core"));
DependencyGraph verboseGraph =
dependencyGraphBuilder
.buildMavenDependencyGraph(new Dependency(jdom, "compile"));
Assert.assertEquals(1, countArtifactId(verboseGraph, "jaxen-core"));
}
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);
}
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);
}
/**
* Turns the list of dependencies into a simple dependency tree
*/
public DependencyResult toDependencyTree(List<Dependency> deps, List<RemoteRepository> mainRepos)
throws BootstrapMavenException {
DependencyResult result = new DependencyResult(
new DependencyRequest().setCollectRequest(new CollectRequest(deps, Collections.emptyList(), mainRepos)));
DefaultDependencyNode root = new DefaultDependencyNode((Dependency) null);
result.setRoot(root);
GenericVersionScheme vs = new GenericVersionScheme();
for (Dependency i : deps) {
DefaultDependencyNode node = new DefaultDependencyNode(i);
try {
node.setVersionConstraint(vs.parseVersionConstraint(i.getArtifact().getVersion()));
node.setVersion(vs.parseVersion(i.getArtifact().getVersion()));
} catch (InvalidVersionSpecificationException e) {
throw new RuntimeException(e);
}
root.getChildren().add(node);
}
return result;
}
@Test
public void testEquals() {
DependencyPath path1 =
new DependencyPath(null)
.append(new Dependency(foo, "compile"))
.append(new Dependency(bar, "compile"));
DependencyPath path2 =
new DependencyPath(null)
.append(new Dependency(foo, "compile"))
.append(new Dependency(bar, "compile"));
DependencyPath path3 =
new DependencyPath(null)
.append(new Dependency(bar, "compile"))
.append(new Dependency(foo, "compile"));
DependencyPath path4 = new DependencyPath(null).append(new Dependency(foo, "compile"));
new EqualsTester()
.addEqualityGroup(path1, path2)
.addEqualityGroup(path3)
.addEqualityGroup(path4)
.testEquals();
}
@Test
public void testGrpcAuth() {
DefaultArtifact grpc = new DefaultArtifact("io.grpc:grpc-auth:1.15.0");
DependencyGraph completeDependencies =
dependencyGraphBuilder
.buildFullDependencyGraph(ImmutableList.of(grpc));
DependencyGraph transitiveDependencies =
dependencyGraphBuilder
.buildMavenDependencyGraph(new Dependency(grpc, "compile"));
Map<String, String> complete = completeDependencies.getHighestVersionMap();
Map<String, String> transitive =
transitiveDependencies.getHighestVersionMap();
Set<String> completeKeyset = complete.keySet();
Set<String> transitiveKeySet = transitive.keySet();
// The complete dependencies sees a path to com.google.j2objc:j2objc-annotations that's
// been removed in newer versions so this is not bidirectional set equality.
Assert.assertTrue(complete.containsKey("com.google.j2objc:j2objc-annotations"));
Truth.assertThat(completeKeyset).containsAtLeastElementsIn(transitiveKeySet);
}
private ImmutableMap<String, Artifact> getRunTimeTransitiveDeps(Iterable<Dependency> mavenCoords)
throws RepositoryException {
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRequestContext(JavaScopes.RUNTIME);
collectRequest.setRepositories(repos);
for (Dependency dep : mavenCoords) {
collectRequest.addDependency(dep);
}
DependencyFilter filter = DependencyFilterUtils.classpathFilter(JavaScopes.RUNTIME);
DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, filter);
DependencyResult dependencyResult = repoSys.resolveDependencies(session, dependencyRequest);
ImmutableSortedMap.Builder<String, Artifact> knownDeps = ImmutableSortedMap.naturalOrder();
for (ArtifactResult artifactResult : dependencyResult.getArtifactResults()) {
Artifact node = artifactResult.getArtifact();
knownDeps.put(buildKey(node), node);
}
return knownDeps.build();
}
public List<File> resolveArtifactsAndDependencies(List<Artifact> artifacts) throws DependencyResolutionException {
List<Dependency> dependencies = new ArrayList<Dependency>();
for (Artifact artifact : artifacts) {
dependencies.add(new Dependency(artifact, JavaScopes.RUNTIME));
}
CollectRequest collectRequest = new CollectRequest((Dependency) null, dependencies, repositories);
DependencyFilter classpathFilter = DependencyFilterUtils.classpathFilter(JavaScopes.RUNTIME);
DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFilter);
DependencyResult result = system.resolveDependencies(session, dependencyRequest);
List<File> files = new ArrayList<File>();
for (ArtifactResult artifactResult : result.getArtifactResults()) {
files.add(artifactResult.getArtifact().getFile());
}
return files;
}
/**
* 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();
}
private static List<Dependency> toAetherDeps(List<AppDependency> directDeps) {
if (directDeps.isEmpty()) {
return Collections.emptyList();
}
final List<Dependency> directMvnDeps = new ArrayList<>(directDeps.size());
for (AppDependency dep : directDeps) {
directMvnDeps.add(new Dependency(toAetherArtifact(dep.getArtifact()), dep.getScope()));
}
return directMvnDeps;
}
private static org.eclipse.aether.graph.DependencyNode createMavenDependencyNode(String artifactId, String scope, org.eclipse.aether.graph.DependencyNode... children) {
Dependency dependency = new Dependency(createArtifact(artifactId), scope);
DefaultDependencyNode node = new DefaultDependencyNode(dependency);
node.setChildren(asList(children));
return node;
}
public CollectResult collectManagedDependencies(Artifact artifact, List<Dependency> deps, List<Dependency> managedDeps,
List<RemoteRepository> mainRepos, String... excludedScopes) throws BootstrapMavenException {
try {
return repoSystem.collectDependencies(repoSession,
newCollectManagedRequest(artifact, deps, managedDeps, mainRepos, excludedScopes));
} catch (DependencyCollectionException e) {
throw new BootstrapMavenException("Failed to collect dependencies for " + artifact, e);
}
}
private boolean notAllowed(Set<NonVersionedArtifact> artifacts, Dependency dependency) {
for (NonVersionedArtifact artifact : artifacts) {
if (matches(dependency, artifact)) {
return false;
}
}
return true;
}
private List<org.eclipse.aether.graph.Dependency> resolveManagedDependencies(String groupId, String artifactId,
String version, List<RemoteRepository> repositories) {
try {
return this.repositorySystem
.readArtifactDescriptor(this.repositorySystemSession, new ArtifactDescriptorRequest(
new DefaultArtifact(groupId, artifactId, "pom", version), repositories, null))
.getManagedDependencies();
}
catch (ArtifactDescriptorException ex) {
throw new RuntimeException(ex);
}
}
private void resolve( ResolveRequest resolveRequest )
{
RepositorySystem system = mavenSystemManager.getRepositorySystem();
RepositorySystemSession session = MavenSystemManager.newRepositorySystemSession( resolveRequest.localRepoDir );
org.eclipse.aether.artifact.Artifact artifact = new DefaultArtifact(
resolveRequest.groupId + ":" + resolveRequest.artifactId + ":" + resolveRequest.version );
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot( new Dependency( artifact, "" ) );
// add remote repositories
for ( RemoteRepository remoteRepository : resolveRequest.remoteRepositories )
{
org.eclipse.aether.repository.RemoteRepository repo = new org.eclipse.aether.repository.RemoteRepository.Builder( remoteRepository.getId( ), "default", remoteRepository.getLocation( ).toString() ).build( );
collectRequest.addRepository(repo);
}
collectRequest.setRequestContext( "project" );
//collectRequest.addRepository( repo );
try
{
CollectResult collectResult = system.collectDependencies( session, collectRequest );
collectResult.getRoot().accept( resolveRequest.dependencyVisitor );
log.debug("Collected dependency results for resolve");
}
catch ( DependencyCollectionException e )
{
log.error( "Error while collecting dependencies (resolve): {}", e.getMessage(), e );
}
}
private ImmutableSetMultimap<Path, Prebuilt> downloadArtifacts(
MutableDirectedGraph<Artifact> graph, ImmutableMap<String, Dependency> specifiedDependencies)
throws ExecutionException, InterruptedException {
ListeningExecutorService exec =
MoreExecutors.listeningDecorator(
Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors(),
new MostExecutors.NamedThreadFactory("artifact download")));
@SuppressWarnings("unchecked")
List<ListenableFuture<Map.Entry<Path, Prebuilt>>> results =
(List<ListenableFuture<Map.Entry<Path, Prebuilt>>>)
(List<?>)
exec.invokeAll(
graph.getNodes().stream()
.map(
artifact ->
(Callable<Map.Entry<Path, Prebuilt>>)
() -> downloadArtifact(artifact, graph, specifiedDependencies))
.collect(ImmutableList.toImmutableList()));
try {
return ImmutableSetMultimap.<Path, Prebuilt>builder()
.orderValuesBy(Ordering.natural())
.putAll(Futures.allAsList(results).get())
.build();
} finally {
exec.shutdown();
}
}
@Test
public void testProjectBuilding() throws Exception
{
File resource = new File(getClass().getResource("lib-1.0.0.Final.pom").getFile());
Assert.assertTrue(resource.exists());
List<Dependency> deps = projectHelper.resolveDependenciesFromPOM(resource);
Assert.assertEquals(13, deps.size());
}