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 */ 035public final class LevelOrderDependencyNodeConsumerVisitor extends AbstractDependencyNodeConsumerVisitor { 036 037 public static final String NAME = ConfigurationProperties.REPOSITORY_SYSTEM_DEPENDENCY_VISITOR_LEVELORDER; 038 039 private final HashMap<Integer, ArrayList<DependencyNode>> nodesPerLevel; 040 041 private final Stack<Boolean> visits; 042 043 /** 044 * Creates a new level order list generator. 045 */ 046 public LevelOrderDependencyNodeConsumerVisitor(Consumer<DependencyNode> nodeConsumer) { 047 super(nodeConsumer); 048 nodesPerLevel = new HashMap<>(16); 049 visits = new Stack<>(); 050 } 051 052 @Override 053 public boolean visitEnter(DependencyNode node) { 054 boolean visited = !setVisited(node); 055 visits.push(visited); 056 if (!visited) { 057 nodesPerLevel.computeIfAbsent(visits.size(), k -> new ArrayList<>()).add(node); 058 } 059 return !visited; 060 } 061 062 @Override 063 public boolean visitLeave(DependencyNode node) { 064 Boolean visited = visits.pop(); 065 if (visited) { 066 return true; 067 } 068 if (visits.isEmpty()) { 069 for (int l = 1; nodesPerLevel.containsKey(l); l++) { 070 nodesPerLevel.get(l).forEach(nodeConsumer); 071 } 072 } 073 return true; 074 } 075}