001package org.eclipse.aether.util.graph.visitor; 002 003/* 004 * Licensed to the Apache Software Foundation (ASF) under one 005 * or more contributor license agreements. See the NOTICE file 006 * distributed with this work for additional information 007 * regarding copyright ownership. The ASF licenses this file 008 * to you under the Apache License, Version 2.0 (the 009 * "License"); you may not use this file except in compliance 010 * with the License. You may obtain a copy of the License at 011 * 012 * http://www.apache.org/licenses/LICENSE-2.0 013 * 014 * Unless required by applicable law or agreed to in writing, 015 * software distributed under the License is distributed on an 016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 017 * KIND, either express or implied. See the License for the 018 * specific language governing permissions and limitations 019 * under the License. 020 */ 021 022import java.util.IdentityHashMap; 023import java.util.Map; 024import static java.util.Objects.requireNonNull; 025 026import org.eclipse.aether.graph.DependencyNode; 027import org.eclipse.aether.graph.DependencyVisitor; 028 029/** 030 * A dependency visitor that delegates to another visitor if a node hasn't been visited before. In other words, this 031 * visitor provides a tree-view of a dependency graph which generally can have multiple paths to the same node or even 032 * cycles. 033 */ 034public final class TreeDependencyVisitor 035 implements DependencyVisitor 036{ 037 038 private final Map<DependencyNode, Object> visitedNodes; 039 040 private final DependencyVisitor visitor; 041 042 private final Stack<Boolean> visits; 043 044 /** 045 * Creates a new visitor that delegates to the specified visitor. 046 * 047 * @param visitor The visitor to delegate to, must not be {@code null}. 048 */ 049 public TreeDependencyVisitor( DependencyVisitor visitor ) 050 { 051 this.visitor = requireNonNull( visitor, "dependency visitor delegate cannot be null" ); 052 visitedNodes = new IdentityHashMap<>( 512 ); 053 visits = new Stack<>(); 054 } 055 056 public boolean visitEnter( DependencyNode node ) 057 { 058 boolean visited = visitedNodes.put( node, Boolean.TRUE ) != null; 059 060 visits.push( visited ); 061 062 if ( visited ) 063 { 064 return false; 065 } 066 067 return visitor.visitEnter( node ); 068 } 069 070 public boolean visitLeave( DependencyNode node ) 071 { 072 Boolean visited = visits.pop(); 073 074 if ( visited ) 075 { 076 return true; 077 } 078 079 return visitor.visitLeave( node ); 080 } 081 082}