View Javadoc
1   /*
2    * This file is part of dependency-check-maven.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   * Copyright (c) 2022 Jeremy Long. All Rights Reserved.
17   */
18  package org.owasp.dependencycheck.maven;
19  
20  import java.util.ArrayList;
21  import java.util.Collections;
22  import java.util.HashMap;
23  import java.util.List;
24  import java.util.Map;
25  import org.apache.maven.shared.dependency.graph.DependencyNode;
26  import org.apache.maven.shared.dependency.graph.traversal.DependencyNodeVisitor;
27  
28  /**
29   *
30   * @author Jeremy Long
31   */
32  public class CollectingRootDependencyGraphVisitor implements DependencyNodeVisitor {
33  
34      /**
35       * The map of nodes collected by root nodes.
36       */
37      private final Map<DependencyNode, List<DependencyNode>> nodes = new HashMap<>();
38      /**
39       * A reference to the root node of the dependency tree.
40       */
41      private DependencyNode root;
42      /**
43       * Track the depth of the dependency tree.
44       */
45      private int depth = 0;
46  
47      @Override
48      public boolean visit(DependencyNode node) {
49          if (depth == 0) {
50              root = node;
51              if (!nodes.containsKey(root)) {
52                  nodes.put(root, new ArrayList<>());
53              }
54          } else {
55              // collect node
56              nodes.get(root).add(node);
57          }
58          depth += 1;
59          return true;
60      }
61  
62      @Override
63      public boolean endVisit(DependencyNode node) {
64          depth -= 1;
65          return true;
66      }
67  
68      public Map<DependencyNode, List<DependencyNode>> getNodes() {
69          return Collections.unmodifiableMap(nodes);
70      }
71  
72  }