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 import static java.util.Objects.requireNonNull;
25
26 import org.eclipse.aether.graph.DependencyNode;
27 import org.eclipse.aether.graph.DependencyVisitor;
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
35 implements DependencyVisitor
36 {
37
38 private final Map<DependencyNode, Object> visitedNodes;
39
40 private final DependencyVisitor visitor;
41
42 private final Stack<Boolean> visits;
43
44 /**
45 * Creates a new visitor that delegates to the specified visitor.
46 *
47 * @param visitor The visitor to delegate to, must not be {@code null}.
48 */
49 public TreeDependencyVisitor( DependencyVisitor visitor )
50 {
51 this.visitor = requireNonNull( visitor, "dependency visitor delegate cannot be null" );
52 visitedNodes = new IdentityHashMap<>( 512 );
53 visits = new Stack<>();
54 }
55
56 public boolean visitEnter( DependencyNode node )
57 {
58 boolean visited = visitedNodes.put( node, Boolean.TRUE ) != null;
59
60 visits.push( visited );
61
62 if ( visited )
63 {
64 return false;
65 }
66
67 return visitor.visitEnter( node );
68 }
69
70 public boolean visitLeave( DependencyNode node )
71 {
72 Boolean visited = visits.pop();
73
74 if ( visited )
75 {
76 return true;
77 }
78
79 return visitor.visitLeave( node );
80 }
81
82 }