View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether.util.graph.visitor;
20  
21  import java.util.IdentityHashMap;
22  import java.util.Map;
23  
24  import org.eclipse.aether.graph.DependencyNode;
25  import org.eclipse.aether.graph.DependencyVisitor;
26  
27  import static java.util.Objects.requireNonNull;
28  
29  /**
30   * A dependency visitor that delegates to another visitor if a node hasn't been visited before. In other words, this
31   * visitor provides a tree-view of a dependency graph which generally can have multiple paths to the same node or even
32   * cycles.
33   */
34  public final class TreeDependencyVisitor implements DependencyVisitor {
35  
36      private final Map<DependencyNode, Object> visitedNodes;
37  
38      private final DependencyVisitor visitor;
39  
40      private final Stack<Boolean> visits;
41  
42      /**
43       * Creates a new visitor that delegates to the specified visitor.
44       *
45       * @param visitor The visitor to delegate to, must not be {@code null}.
46       */
47      public TreeDependencyVisitor(DependencyVisitor visitor) {
48          this.visitor = requireNonNull(visitor, "dependency visitor delegate cannot be null");
49          visitedNodes = new IdentityHashMap<>(512);
50          visits = new Stack<>();
51      }
52  
53      @Override
54      public boolean visitEnter(DependencyNode node) {
55          boolean visited = visitedNodes.put(node, Boolean.TRUE) != null;
56  
57          visits.push(visited);
58  
59          if (visited) {
60              return false;
61          }
62  
63          return visitor.visitEnter(node);
64      }
65  
66      @Override
67      public boolean visitLeave(DependencyNode node) {
68          Boolean visited = visits.pop();
69  
70          if (visited) {
71              return true;
72          }
73  
74          return visitor.visitLeave(node);
75      }
76  }