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