    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.io.PrintStream;
    020import java.util.Map;
    021
    022/**
    023 * Utility methods.
    024 *
    025 * @since 1.7
    026 */
    027public final class TreeUtils {
    028    /** Prevent creating this class. */
    029    private TreeUtils() {
    030    }
    031
    032    /**
    033     * Print out the data in the configuration.
    034     *
    035     * @param stream The OutputStream.
    036     * @param result The root node of the tree.
    037     */
    038    public static void printTree(final PrintStream stream, final ImmutableNode result) {
    039        if (stream != null) {
    040            printTree(stream, "", result);
    041        }
    042    }
    043
    044    private static void printTree(final PrintStream stream, final String indent, final ImmutableNode result) {
    045        final StringBuilder buffer = new StringBuilder(indent).append("<").append(result.getNodeName());
    046        for (final Map.Entry<String, Object> e : result.getAttributes().entrySet()) {
    047            buffer.append(' ').append(e.getKey()).append("='").append(e.getValue()).append("'");
    048        }
    049        buffer.append(">");
    050        stream.print(buffer.toString());
    051        if (result.getValue() != null) {
    052            stream.print(result.getValue());
    053        }
    054        boolean newline = false;
    055        if (!result.getChildren().isEmpty()) {
    056            stream.print("\n");
    057            for (final ImmutableNode child : result) {
    058                printTree(stream, indent + "  ", child);
    059            }
    060            newline = true;
    061        }
    062        if (newline) {
    063            stream.print(indent);
    064        }
    065        stream.println("</" + result.getNodeName() + ">");
    066    }
    067}