    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 */
    017
    018package org.apache.commons.configuration2;
    019
    020import org.apache.commons.configuration2.ex.ConfigurationException;
    021import org.apache.commons.configuration2.io.ConfigurationLogger;
    022import org.apache.commons.configuration2.tree.ImmutableNode;
    023
    024import java.util.ArrayList;
    025import java.util.Collection;
    026import java.util.Collections;
    027import java.util.HashMap;
    028import java.util.List;
    029import java.util.Map;
    030
    031/**
    032 * <p>
    033 * A base class for configuration implementations based on YAML structures.
    034 * </p>
    035 * <p>
    036 * This base class offers functionality related to YAML-like data structures based on maps. Such a map has strings as
    037 * keys and arbitrary objects as values. The class offers methods to transform such a map into a hierarchy of
    038 * {@link ImmutableNode} objects and vice versa.
    039 * </p>
    040 *
    041 * @since 2.2
    042 */
    043public class AbstractYAMLBasedConfiguration extends BaseHierarchicalConfiguration {
    044    /**
    045     * Creates a new instance of {@code AbstractYAMLBasedConfiguration}.
    046     */
    047    protected AbstractYAMLBasedConfiguration() {
    048        initLogger(new ConfigurationLogger(getClass()));
    049    }
    050
    051    /**
    052     * Creates a new instance of {@code AbstractYAMLBasedConfiguration} as a copy of the specified configuration.
    053     *
    054     * @param c the configuration to be copied
    055     */
    056    protected AbstractYAMLBasedConfiguration(final HierarchicalConfiguration<ImmutableNode> c) {
    057        super(c);
    058        initLogger(new ConfigurationLogger(getClass()));
    059    }
    060
    061    /**
    062     * Loads this configuration from the content of the specified map. The data in the map is transformed into a hierarchy
    063     * of {@link ImmutableNode} objects.
    064     *
    065     * @param map the map to be processed
    066     */
    067    protected void load(final Map<String, Object> map) {
    068        final List<ImmutableNode> roots = constructHierarchy("", map);
    069        getNodeModel().setRootNode(roots.get(0));
    070    }
    071
    072    /**
    073     * Constructs a YAML map, i.e. String -&gt; Object from a given configuration node.
    074     *
    075     * @param node The configuration node to create a map from.
    076     * @return A Map that contains the configuration node information.
    077     */
    078    protected Map<String, Object> constructMap(final ImmutableNode node) {
    079        final Map<String, Object> map = new HashMap<>(node.getChildren().size());
    080        for (final ImmutableNode cNode : node) {
    081            final Object value = cNode.getChildren().isEmpty() ? cNode.getValue() : constructMap(cNode);
    082            addEntry(map, cNode.getNodeName(), value);
    083        }
    084        return map;
    085    }
    086
    087    /**
    088     * Adds a key value pair to a map, taking list structures into account. If a key is added which is already present in
    089     * the map, this method ensures that a list is created.
    090     *
    091     * @param map the map
    092     * @param key the key
    093     * @param value the value
    094     */
    095    private static void addEntry(final Map<String, Object> map, final String key, final Object value) {
    096        final Object oldValue = map.get(key);
    097        if (oldValue == null) {
    098            map.put(key, value);
    099        } else if (oldValue instanceof Collection) {
    100            // safe case because the collection was created by ourselves
    101            @SuppressWarnings("unchecked")
    102            final Collection<Object> values = (Collection<Object>) oldValue;
    103            values.add(value);
    104        } else {
    105            final Collection<Object> values = new ArrayList<>();
    106            values.add(oldValue);
    107            values.add(value);
    108            map.put(key, values);
    109        }
    110    }
    111
    112    /**
    113     * Creates a part of the hierarchical nodes structure of the resulting configuration. The passed in element is converted
    114     * into one or multiple configuration nodes. (If list structures are involved, multiple nodes are returned.)
    115     *
    116     * @param key the key of the new node(s)
    117     * @param elem the element to be processed
    118     * @return a list with configuration nodes representing the element
    119     */
    120    private static List<ImmutableNode> constructHierarchy(final String key, final Object elem) {
    121        if (elem instanceof Map) {
    122            return parseMap((Map<String, Object>) elem, key);
    123        }
    124        if (elem instanceof Collection) {
    125            return parseCollection((Collection<Object>) elem, key);
    126        }
    127        return Collections.singletonList(new ImmutableNode.Builder().name(key).value(elem).create());
    128    }
    129
    130    /**
    131     * Parses a map structure. The single keys of the map are processed recursively.
    132     *
    133     * @param map the map to be processed
    134     * @param key the key under which this map is to be stored
    135     * @return a node representing this map
    136     */
    137    private static List<ImmutableNode> parseMap(final Map<String, Object> map, final String key) {
    138        final ImmutableNode.Builder subtree = new ImmutableNode.Builder().name(key);
    139        for (final Map.Entry<String, Object> entry : map.entrySet()) {
    140            final List<ImmutableNode> children = constructHierarchy(entry.getKey(), entry.getValue());
    141            for (final ImmutableNode child : children) {
    142                subtree.addChild(child);
    143            }
    144        }
    145        return Collections.singletonList(subtree.create());
    146    }
    147
    148    /**
    149     * Parses a collection structure. The elements of the collection are processed recursively.
    150     *
    151     * @param col the collection to be processed
    152     * @param key the key under which this collection is to be stored
    153     * @return a node representing this collection
    154     */
    155    private static List<ImmutableNode> parseCollection(final Collection<Object> col, final String key) {
    156        final List<ImmutableNode> nodes = new ArrayList<>(col.size());
    157        for (final Object elem : col) {
    158            nodes.addAll(constructHierarchy(key, elem));
    159        }
    160        return nodes;
    161    }
    162
    163    /**
    164     * Internal helper method to wrap an exception in a {@code ConfigurationException}.
    165     *
    166     * @param e the exception to be wrapped
    167     * @throws ConfigurationException the resulting exception
    168     */
    169    static void rethrowException(final Exception e) throws ConfigurationException {
    170        if (e instanceof ClassCastException) {
    171            throw new ConfigurationException("Error parsing", e);
    172        }
    173        throw new ConfigurationException("Unable to load the configuration", e);
    174    }
    175}