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