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