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.ArrayList;
022import java.util.HashMap;
023import java.util.function.Consumer;
024
025import org.eclipse.aether.graph.DependencyNode;
026
027/**
028 * Processes dependency graph by traversing the graph in level order. This visitor visits each node exactly once
029 * regardless how many paths within the dependency graph lead to the node such that the resulting node sequence is
030 * free of duplicates.
031 *
032 * @since TBD
033 */
034public final class LevelOrderDependencyNodeConsumerVisitor extends AbstractDependencyNodeConsumerVisitor {
035
036    public static final String NAME = "levelOrder";
037
038    private final HashMap<Integer, ArrayList<DependencyNode>> nodesPerLevel;
039
040    private final Stack<Boolean> visits;
041
042    /**
043     * Creates a new level order list generator.
044     */
045    public LevelOrderDependencyNodeConsumerVisitor(Consumer<DependencyNode> nodeConsumer) {
046        super(nodeConsumer);
047        nodesPerLevel = new HashMap<>(16);
048        visits = new Stack<>();
049    }
050
051    @Override
052    public boolean visitEnter(DependencyNode node) {
053        boolean visited = !setVisited(node);
054        visits.push(visited);
055        if (!visited) {
056            nodesPerLevel.computeIfAbsent(visits.size(), k -> new ArrayList<>()).add(node);
057        }
058        return !visited;
059    }
060
061    @Override
062    public boolean visitLeave(DependencyNode node) {
063        Boolean visited = visits.pop();
064        if (visited) {
065            return true;
066        }
067        if (visits.isEmpty()) {
068            for (int l = 1; nodesPerLevel.containsKey(l); l++) {
069                nodesPerLevel.get(l).forEach(nodeConsumer);
070            }
071        }
072        return true;
073    }
074}