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; 024 025import org.eclipse.aether.graph.DependencyNode; 026import org.eclipse.aether.graph.DependencyVisitor; 027 028/** 029 * A dependency visitor that delegates to another visitor if a node hasn't been visited before. In other words, this 030 * visitor provides a tree-view of a dependency graph which generally can have multiple paths to the same node or even 031 * cycles. 032 */ 033public final class TreeDependencyVisitor 034 implements DependencyVisitor 035{ 036 037 private final Map<DependencyNode, Object> visitedNodes; 038 039 private final DependencyVisitor visitor; 040 041 private final Stack<Boolean> visits; 042 043 /** 044 * Creates a new visitor that delegates to the specified visitor. 045 * 046 * @param visitor The visitor to delegate to, must not be {@code null}. 047 */ 048 public TreeDependencyVisitor( DependencyVisitor visitor ) 049 { 050 if ( visitor == null ) 051 { 052 throw new IllegalArgumentException( "no visitor delegate specified" ); 053 } 054 this.visitor = visitor; 055 visitedNodes = new IdentityHashMap<DependencyNode, Object>( 512 ); 056 visits = new Stack<Boolean>(); 057 } 058 059 public boolean visitEnter( DependencyNode node ) 060 { 061 boolean visited = visitedNodes.put( node, Boolean.TRUE ) != null; 062 063 visits.push( visited ); 064 065 if ( visited ) 066 { 067 return false; 068 } 069 070 return visitor.visitEnter( node ); 071 } 072 073 public boolean visitLeave( DependencyNode node ) 074 { 075 Boolean visited = visits.pop(); 076 077 if ( visited ) 078 { 079 return true; 080 } 081 082 return visitor.visitLeave( node ); 083 } 084 085}