001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.configuration2.tree;
018
019import java.util.LinkedList;
020import java.util.List;
021
022/**
023 * <p>
024 * A class providing different algorithms for traversing a hierarchy of configuration nodes.
025 * </p>
026 * <p>
027 * The methods provided by this class accept a {@link ConfigurationNodeVisitor} and visit all nodes in a hierarchy
028 * starting from a given root node. Because a {@link NodeHandler} has to be passed in, too, arbitrary types of nodes can
029 * be processed. The {@code walk()} methods differ in the order in which nodes are visited. Details can be found in the
030 * method documentation.
031 * </p>
032 * <p>
033 * An instance of this class does not define any state; therefore, it can be shared and used concurrently. The
034 * {@code INSTANCE} member field can be used for accessing a default instance. If desired (e.g. for testing purposes),
035 * new instances can be created.
036 * </p>
037 *
038 * @since 2.0
039 */
040public class NodeTreeWalker {
041    /** The default instance of this class. */
042    public static final NodeTreeWalker INSTANCE = new NodeTreeWalker();
043
044    /**
045     * Visits all nodes in the hierarchy represented by the given root node in <em>depth first search</em> manner. This
046     * means that first {@link ConfigurationNodeVisitor#visitBeforeChildren(Object, NodeHandler)} is called on a node, then
047     * recursively all of its children are processed, and eventually
048     * {@link ConfigurationNodeVisitor#visitAfterChildren(Object, NodeHandler)} gets invoked.
049     *
050     * @param root the root node of the hierarchy to be processed (may be <b>null</b>, then this call has no effect)
051     * @param visitor the {@code ConfigurationNodeVisitor} (must not be <b>null</b>)
052     * @param handler the {@code NodeHandler} (must not be <b>null</b>)
053     * @param <T> the type of the nodes involved
054     * @throws IllegalArgumentException if a required parameter is <b>null</b>
055     */
056    public <T> void walkDFS(final T root, final ConfigurationNodeVisitor<T> visitor, final NodeHandler<T> handler) {
057        if (checkParameters(root, visitor, handler)) {
058            dfs(root, visitor, handler);
059        }
060    }
061
062    /**
063     * Visits all nodes in the hierarchy represented by the given root node in <em>breadth first search</em> manner. This
064     * means that the nodes are visited in an order corresponding to the distance from the root node: first the root node is
065     * visited, then all direct children of the root node, then all direct children of the first child of the root node,
066     * etc. In this mode of traversal, there is no direct connection between the encounter of a node and its children.
067     * <strong>Therefore, on the visitor object only the {@code visitBeforeChildren()} method gets called!</strong>.
068     *
069     * @param root the root node of the hierarchy to be processed (may be <b>null</b>, then this call has no effect)
070     * @param visitor the {@code ConfigurationNodeVisitor} (must not be <b>null</b>)
071     * @param handler the {@code NodeHandler} (must not be <b>null</b>)
072     * @param <T> the type of the nodes involved
073     * @throws IllegalArgumentException if a required parameter is <b>null</b>
074     */
075    public <T> void walkBFS(final T root, final ConfigurationNodeVisitor<T> visitor, final NodeHandler<T> handler) {
076        if (checkParameters(root, visitor, handler)) {
077            bfs(root, visitor, handler);
078        }
079    }
080
081    /**
082     * Recursive helper method for performing a DFS traversal.
083     *
084     * @param node the current node
085     * @param visitor the visitor
086     * @param handler the handler
087     * @param <T> the type of the nodes involved
088     */
089    private static <T> void dfs(final T node, final ConfigurationNodeVisitor<T> visitor, final NodeHandler<T> handler) {
090        if (!visitor.terminate()) {
091            visitor.visitBeforeChildren(node, handler);
092            for (final T c : handler.getChildren(node)) {
093                dfs(c, visitor, handler);
094            }
095            if (!visitor.terminate()) {
096                visitor.visitAfterChildren(node, handler);
097            }
098        }
099    }
100
101    /**
102     * Helper method for performing a BFS traversal. Implementation node: This method organizes the nodes to be visited in
103     * structures on the heap. Therefore, it can deal with larger structures than would be the case in a recursive approach
104     * (where the stack size limits the size of the structures which can be traversed).
105     *
106     * @param root the root node to be navigated
107     * @param visitor the visitor
108     * @param handler the handler
109     * @param <T> the type of the nodes involved
110     */
111    private static <T> void bfs(final T root, final ConfigurationNodeVisitor<T> visitor, final NodeHandler<T> handler) {
112        final List<T> pendingNodes = new LinkedList<>();
113        pendingNodes.add(root);
114        boolean cancel = false;
115
116        while (!pendingNodes.isEmpty() && !cancel) {
117            final T node = pendingNodes.remove(0);
118            visitor.visitBeforeChildren(node, handler);
119            cancel = visitor.terminate();
120            pendingNodes.addAll(handler.getChildren(node));
121        }
122    }
123
124    /**
125     * Helper method for checking the parameters for the walk() methods. If mandatory parameters are missing, an exception
126     * is thrown. The return value indicates whether an operation can be performed.
127     *
128     * @param root the root node
129     * @param visitor the visitor
130     * @param handler the handler
131     * @param <T> the type of the nodes involved
132     * @return <b>true</b> if a walk operation can be performed, <b>false</b> otherwise
133     * @throws IllegalArgumentException if a required parameter is missing
134     */
135    private static <T> boolean checkParameters(final T root, final ConfigurationNodeVisitor<T> visitor, final NodeHandler<T> handler) {
136        if (visitor == null) {
137            throw new IllegalArgumentException("Visitor must not be null!");
138        }
139        if (handler == null) {
140            throw new IllegalArgumentException("NodeHandler must not be null!");
141        }
142        return root != null;
143    }
144}