org.apache.maven.shared.dependency.graph.DependencyNode Java Examples

The following examples show how to use org.apache.maven.shared.dependency.graph.DependencyNode. 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: BotsingMojo.java    From botsing with Apache License 2.0 6 votes vote down vote up
public List<Artifact> getDependencyTree(DependencyInputType dependencyType) throws MojoExecutionException {
	try {
		ProjectBuildingRequest buildingRequest = getProjectbuildingRequest(dependencyType);

		// TODO check if it is necessary to specify an artifact filter
		DependencyNode rootNode = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, null,
				reactorProjects);

		List<Artifact> artifactList = new ArrayList<Artifact>();
		addChildDependencies(rootNode, artifactList);

		return artifactList;

	} catch (DependencyGraphBuilderException e) {
		throw new MojoExecutionException("Couldn't download artifact: " + e.getMessage(), e);
	}
}
 
Example #2
Source File: BaseCycloneDxMojo.java    From cyclonedx-maven-plugin with Apache License 2.0 6 votes vote down vote up
protected Set<Dependency> buildDependencyGraph(final Set<String> componentRefs) throws MojoExecutionException {
    final Set<Dependency> dependencies = new LinkedHashSet<>();
    final Collection<String> scope = new HashSet<>();
    if (includeCompileScope) scope.add("compile");
    if (includeProvidedScope) scope.add("provided");
    if (includeRuntimeScope) scope.add("runtime");
    if (includeSystemScope) scope.add("system");
    if (includeTestScope) scope.add("test");
    final ArtifactFilter artifactFilter = new CumulativeScopeArtifactFilter(scope);
    final ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
    buildingRequest.setProject(this.project);
    try {
        final DependencyNode rootNode = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, artifactFilter);
        buildDependencyGraphNode(componentRefs, dependencies, rootNode, null);
        final CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
        rootNode.accept(visitor);
        for (final DependencyNode dependencyNode : visitor.getNodes()) {
            buildDependencyGraphNode(componentRefs, dependencies, dependencyNode, null);
        }
    } catch (DependencyGraphBuilderException e) {
        throw new MojoExecutionException("An error occurred building dependency graph", e);
    }
    return dependencies;
}
 
Example #3
Source File: BanCircularDependencies.java    From extra-enforcer-rules with Apache License 2.0 6 votes vote down vote up
private Set<Artifact> getAllDescendants( DependencyNode node )
{
    Set<Artifact> children = null; 
    if( node.getChildren() != null )
    {
        children = new HashSet<Artifact>();
        for( DependencyNode depNode : node.getChildren() )
        {
            children.add( depNode.getArtifact() );
            Set<Artifact> subNodes = getAllDescendants( depNode );
            if( subNodes != null )
            {
                children.addAll( subNodes );
            }
        }
    }
    return children;
}
 
Example #4
Source File: NarProvidedDependenciesMojo.java    From nifi-maven with Apache License 2.0 6 votes vote down vote up
@Override
public boolean visit(DependencyNode node) {
    // add this node
    hierarchy.push(node);

    // don't print test deps, but still add to hierarchy as they will
    // be removed in endVisit below
    if (isTest(node)) {
        return false;
    }

    // build the padding
    final StringBuilder pad = new StringBuilder();
    for (int i = 0; i < hierarchy.size() - 1; i++) {
        pad.append("   ");
    }
    pad.append("+- ");

    // log it
    output.append(pad).append(node.toNodeString()).append("\n");

    return true;
}
 
Example #5
Source File: NarProvidedDependenciesMojo.java    From nifi-maven with Apache License 2.0 6 votes vote down vote up
@Override
public boolean visit(DependencyNode node) {
    if (isTest(node)) {
        return false;
    }

    final Artifact artifact = node.getArtifact();
    if (!NAR.equals(artifact.getType())) {
        output.append("<dependency>\n");
        output.append("    <groupId>").append(artifact.getGroupId()).append("</groupId>\n");
        output.append("    <artifactId>").append(artifact.getArtifactId()).append("</artifactId>\n");
        output.append("    <version>").append(artifact.getVersion()).append("</version>\n");
        output.append("    <scope>provided</scope>\n");
        output.append("</dependency>\n");
    }

    return true;
}
 
Example #6
Source File: FingerprintMojo.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
    public boolean visit(final DependencyNode node) {
      final List<DependencyNode> children = new ArrayList<>(node.getChildren());
      for (final Iterator<DependencyNode> iterator = children.iterator(); iterator.hasNext();) {
        final DependencyNode child = iterator.next();
        final Artifact artifact = child.getArtifact();
        if ("io.opentracing".equals(artifact.getGroupId())) {
          if (apiVersion != null && !apiVersion.equals(artifact.getVersion()))
            getLog().warn("OT API version (" + apiVersion + ") in SpecialAgent differs from OT API version (" + apiVersion + ") in plugin");

          if ("compile".equals(artifact.getScope())) {
//            getLog().warn("Removing dependency provided by SpecialAgent: " + artifact);
//            iterator.remove();
          }
        }
        else if ("compile".equals(artifact.getScope()) && !getProject().getDependencyArtifacts().contains(artifact)) {
//          getLog().warn("Including dependency for plugin: " + artifact);
        }
      }

      if (children.size() < node.getChildren().size())
        ((DefaultDependencyNode)node).setChildren(children);

      final DependencyNode parent = node.getParent();
      if (parent == null || parent.getOptional() == null || !parent.getOptional() || !"provided".equals(parent.getArtifact().getScope()))
        return target.visit(node);

      return false;
    }
 
Example #7
Source File: BotsingMojo.java    From botsing with Apache License 2.0 5 votes vote down vote up
private void addChildDependencies(DependencyNode node, List<Artifact> list) {
	List<DependencyNode> children = node.getChildren();

	if (children != null) {
		for (DependencyNode child : children) {
			list.add(child.getArtifact());
			addChildDependencies(child, list);
		}
	}
}
 
Example #8
Source File: BaseCycloneDxMojo.java    From cyclonedx-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void buildDependencyGraphNode(final Set<String> componentRefs, final Set<Dependency> dependencies, final DependencyNode artifactNode, final Dependency parent) {
    final String purl = generatePackageUrl(artifactNode.getArtifact());
    final Dependency dependency = new Dependency(purl);
    final String parentRef = (parent != null) ? parent.getRef() : null;
    componentRefs.stream().filter(s -> s != null && s.equals(purl))
            .forEach(s -> addDependencyToGraph(dependencies, parentRef, dependency));
    for (final DependencyNode childrenNode : artifactNode.getChildren()) {
        buildDependencyGraphNode(componentRefs, dependencies, childrenNode, dependency);
    }
}
 
Example #9
Source File: BanCircularDependencies.java    From extra-enforcer-rules with Apache License 2.0 5 votes vote down vote up
protected Set<Artifact> getDependenciesToCheck( MavenProject project )
{
    Set<Artifact> dependencies = null;
    try
    {
        DependencyNode node = graphBuilder.buildDependencyGraph( project, null );
        dependencies  = getAllDescendants( node );
    }
    catch ( DependencyGraphBuilderException e )
    {
        // otherwise we need to change the signature of this protected method
        throw new RuntimeException( e );
    }
    return dependencies;
}
 
Example #10
Source File: DependencyCopy.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(DependencyNode dependencyNode) {
    Artifact artifact = dependencyNode.getArtifact();
    if (artifact == null) {
        return false;
    }
    if (artifact.getScope() == null) {
        // no scope means the current artifact (root).
        // we have to return true to traverse the dependencies.
        return true;
    }

    if (SCOPE_COMPILE.equals(artifact.getScope())) {
        mojo.getLog().debug("Adding " + artifact.toString() + " to the transitive list");
        artifacts.add(artifact);
    }

    if (SCOPE_PROVIDED.equals(artifact.getScope())) {
        mojo.getLog().debug("Adding " + artifact.toString() + " to the transitive list");
        artifacts.add(artifact);
        return false;
    }

    // The scope of the artifact we retrieved in context-aware. For instance,
    // if we have a dependency in the test scope, all its dependencies will be considered as test dependencies.
    // So we can visit the children, as the pruning is made in the if statement above. (this is related to
    // #263).
    return true;
}
 
Example #11
Source File: DependencyCopy.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Collects the transitive dependencies of the current projects.
 *
 * @param mojo  the mojo
 * @param graph the dependency graph builder
 * @return the set of resolved transitive dependencies.
 */
private static Set<Artifact> getTransitiveDependencies(AbstractWisdomMojo mojo, DependencyGraphBuilder graph,
                                                       ArtifactFilter filter) {
    Set<Artifact> artifacts;
    artifacts = new LinkedHashSet<>();
    try {
        Set<Artifact> transitives = new LinkedHashSet<>();
        DependencyNode node = graph.buildDependencyGraph(mojo.project, filter);
        node.accept(new ArtifactVisitor(mojo, transitives));
        mojo.getLog().debug(transitives.size() + " transitive dependencies have been collected : " +
                transitives);

        // Unfortunately, the retrieved artifacts are not resolved, we need to find their 'surrogates' in the
        // resolved list.
        Set<Artifact> resolved = mojo.project.getArtifacts();
        for (Artifact a : transitives) {
            Artifact r = getArtifact(a, resolved);
            if (r == null) {
                mojo.getLog().warn("Cannot find resolved artifact for " + a);
            } else {
                artifacts.add(r);
            }
        }
    } catch (DependencyGraphBuilderException e) {
        mojo.getLog().error("Cannot traverse the project's dependencies to collect transitive dependencies, " +
                "ignoring transitive");
        mojo.getLog().debug("Here is the thrown exception having disabled the transitive dependency collection", e);
        artifacts = mojo.project.getDependencyArtifacts();
    }
    return artifacts;
}
 
Example #12
Source File: FingerprintMojo.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
@Override
public boolean endVisit(final DependencyNode node) {
  return target.endVisit(node);
}
 
Example #13
Source File: DependencyCopyTest.java    From wisdom with Apache License 2.0 4 votes vote down vote up
@Test
public void testCopyLibs() throws Exception {
    AbstractWisdomMojo mojo = new AbstractWisdomMojo() {
        @Override
        public void execute() throws MojoExecutionException, MojoFailureException {
            // Do nothing;
        }
    };
    mojo.basedir = new File("target/junk/project1");
    mojo.basedir.mkdirs();
    mojo.project = new MavenProject();
    mojo.project.setArtifacts(resolved);
    mojo.buildDirectory = new File(mojo.basedir, "target");

    // Create the artifacts
    final Artifact asmArtifact = artifact("asm");
    final Artifact parboiledCoreArtifact = artifact("parboiledCore");
    final Artifact parboiledArtifact = artifact("parboiled");
    final Artifact pegdownArtifact = artifact("pegdown");
    final Artifact projectArtifact = artifact("project");

    // Define the trails
    setTrail(projectArtifact, projectArtifact);
    setTrail(pegdownArtifact, projectArtifact, pegdownArtifact);
    setTrail(parboiledArtifact, projectArtifact, pegdownArtifact, parboiledArtifact);
    setTrail(parboiledCoreArtifact, projectArtifact, pegdownArtifact, parboiledArtifact, parboiledCoreArtifact);
    setTrail(asmArtifact, projectArtifact, pegdownArtifact, asmArtifact);

    DefaultDependencyNode root = new DefaultDependencyNode(null, projectArtifact, null, null, null);
    DefaultDependencyNode pegdown = new DefaultDependencyNode(root, pegdownArtifact, null, null, null);
    DefaultDependencyNode parboiled = new DefaultDependencyNode(pegdown, parboiledArtifact, null, null, null);
    DefaultDependencyNode parboiledCore = new DefaultDependencyNode(parboiled, parboiledCoreArtifact, null,
            null, null);
    DefaultDependencyNode asm = new DefaultDependencyNode(parboiled, asmArtifact, null, null, null);

    root.setChildren(ImmutableList.<DependencyNode>of(pegdown));
    pegdown.setChildren(ImmutableList.<DependencyNode>of(parboiled));
    parboiled.setChildren(ImmutableList.<DependencyNode>of(parboiledCore, asm));
    parboiledCore.setChildren(Collections.<DependencyNode>emptyList());
    asm.setChildren(Collections.<DependencyNode>emptyList());

    DependencyGraphBuilder builder = mock(DependencyGraphBuilder.class);
    when(builder.buildDependencyGraph(mojo.project, null)).thenReturn(root);

    // First execution, with transitive enabled.
    Libraries libraries = new Libraries();
    libraries.setResolveTransitive(true);
    libraries.setIncludes(ImmutableList.of(":pegdown"));
    Set<Artifact> copied = DependencyCopy.copyLibs(mojo, builder, libraries);

    // In that case, everything is copied, so size == 4
    assertThat(copied).hasSize(4);

    // First execution, without transitives.
    libraries.setResolveTransitive(false);
    libraries.setIncludes(ImmutableList.of(":pegdown"));
    copied = DependencyCopy.copyLibs(mojo, builder, libraries);

    // In that case, only pegdown is copied, so size == 1
    assertThat(copied).hasSize(1);

    // Re-enabled the transitive and exclude asm
    libraries.setResolveTransitive(true);
    libraries.setIncludes(ImmutableList.of(":pegdown"));
    libraries.setExcludes(ImmutableList.of(":asm"));
    copied = DependencyCopy.copyLibs(mojo, builder, libraries);

    // In that case, asm is not copied, size = 3
    assertThat(copied).hasSize(3);

    // Ensure that excluded dependencies are not copied, for this we modify the graph adding a dependency on org
    // .apache.felix.ipojo.annotations.
    Artifact annotation = artifact("org.apache.felix.ipojo.annotations");
    when(annotation.getGroupId()).thenReturn("org.apache.felix");
    setTrail(annotation, projectArtifact, pegdownArtifact);
    DefaultDependencyNode ann = new DefaultDependencyNode(parboiled, annotation, null, null, null);
    ann.setChildren(Collections.<DependencyNode>emptyList());
    pegdown.setChildren(ImmutableList.<DependencyNode>of(parboiled, ann));

    // Re-enabled the transitive and exclude asm
    libraries.setResolveTransitive(true);
    libraries.setIncludes(ImmutableList.of(":pegdown"));
    libraries.setExcludes(ImmutableList.of(":asm"));
    copied = DependencyCopy.copyLibs(mojo, builder, libraries);

    // In that case, asm is not copied, annotation either, size = 3
    assertThat(copied).hasSize(3);

}
 
Example #14
Source File: DependencyCopy.java    From wisdom with Apache License 2.0 4 votes vote down vote up
@Override
public boolean endVisit(DependencyNode dependencyNode) {
    return true;
}
 
Example #15
Source File: NarProvidedDependenciesMojo.java    From nifi-maven with Apache License 2.0 4 votes vote down vote up
@Override
public boolean endVisit(DependencyNode node) {
    return true;
}
 
Example #16
Source File: NarProvidedDependenciesMojo.java    From nifi-maven with Apache License 2.0 4 votes vote down vote up
@Override
public boolean endVisit(DependencyNode node) {
    hierarchy.pop();
    return true;
}
 
Example #17
Source File: NarProvidedDependenciesMojo.java    From nifi-maven with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        // find the nar dependency
        Artifact narArtifact = null;
        for (final Artifact artifact : project.getDependencyArtifacts()) {
            if (NAR.equals(artifact.getType())) {
                // ensure the project doesn't have two nar dependencies
                if (narArtifact != null) {
                    throw new MojoExecutionException("Project can only have one NAR dependency.");
                }

                // record the nar dependency
                narArtifact = artifact;
            }
        }

        // ensure there is a nar dependency
        if (narArtifact == null) {
            throw new MojoExecutionException("Project does not have any NAR dependencies.");
        }

        // build the project for the nar artifact
        final ProjectBuildingRequest narRequest = new DefaultProjectBuildingRequest();
        narRequest.setRepositorySession(repoSession);
        narRequest.setSystemProperties(System.getProperties());

        final ProjectBuildingResult narResult = projectBuilder.build(narArtifact, narRequest);
        narRequest.setProject(narResult.getProject());

        // get the artifact handler for excluding dependencies
        final ArtifactHandler narHandler = excludesDependencies(narArtifact);
        narArtifact.setArtifactHandler(narHandler);

        // nar artifacts by nature includes dependencies, however this prevents the
        // transitive dependencies from printing using tools like dependency:tree.
        // here we are overriding the artifact handler for all nars so the
        // dependencies can be listed. this is important because nar dependencies
        // will be used as the parent classloader for this nar and seeing what
        // dependencies are provided is critical.
        final Map<String, ArtifactHandler> narHandlerMap = new HashMap<>();
        narHandlerMap.put(NAR, narHandler);
        artifactHandlerManager.addHandlers(narHandlerMap);

        // get the dependency tree
        final DependencyNode root = dependencyGraphBuilder.buildDependencyGraph(narRequest, null);

        // write the appropriate output
        DependencyNodeVisitor visitor = null;
        if ("tree".equals(mode)) {
            visitor = new TreeWriter();
        } else if ("pom".equals(mode)) {
            visitor = new PomWriter();
        }

        // ensure the mode was specified correctly
        if (visitor == null) {
            throw new MojoExecutionException("The specified mode is invalid. Supported options are 'tree' and 'pom'.");
        }

        // visit and print the results
        root.accept(visitor);
        getLog().info("--- Provided NAR Dependencies ---\n\n" + visitor.toString());
    } catch (ProjectBuildingException | DependencyGraphBuilderException e) {
        throw new MojoExecutionException("Cannot build project dependency tree", e);
    }
}
 
Example #18
Source File: NarProvidedDependenciesMojo.java    From nifi-maven with Apache License 2.0 2 votes vote down vote up
/**
 * Returns whether the specified dependency has test scope.
 *
 * @param node  The dependency
 * @return      What the dependency is a test scoped dep
 */
private boolean isTest(final DependencyNode node) {
    return "test".equals(node.getArtifact().getScope());
}