AbstractYAMLBasedConfiguration.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.configuration2;

  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.stream.Collectors;

  25. import org.apache.commons.configuration2.ex.ConfigurationException;
  26. import org.apache.commons.configuration2.io.ConfigurationLogger;
  27. import org.apache.commons.configuration2.tree.ImmutableNode;

  28. /**
  29.  * <p>
  30.  * A base class for configuration implementations based on YAML structures.
  31.  * </p>
  32.  * <p>
  33.  * This base class offers functionality related to YAML-like data structures based on maps. Such a map has strings as
  34.  * keys and arbitrary objects as values. The class offers methods to transform such a map into a hierarchy of
  35.  * {@link ImmutableNode} objects and vice versa.
  36.  * </p>
  37.  *
  38.  * @since 2.2
  39.  */
  40. public class AbstractYAMLBasedConfiguration extends BaseHierarchicalConfiguration {
  41.     /**
  42.      * Adds a key value pair to a map, taking list structures into account. If a key is added which is already present in
  43.      * the map, this method ensures that a list is created.
  44.      *
  45.      * @param map the map
  46.      * @param key the key
  47.      * @param value the value
  48.      */
  49.     private static void addEntry(final Map<String, Object> map, final String key, final Object value) {
  50.         final Object oldValue = map.get(key);
  51.         if (oldValue == null) {
  52.             map.put(key, value);
  53.         } else if (oldValue instanceof Collection) {
  54.             // safe case because the collection was created by ourselves
  55.             @SuppressWarnings("unchecked")
  56.             final Collection<Object> values = (Collection<Object>) oldValue;
  57.             values.add(value);
  58.         } else {
  59.             final Collection<Object> values = new ArrayList<>();
  60.             values.add(oldValue);
  61.             values.add(value);
  62.             map.put(key, values);
  63.         }
  64.     }

  65.     /**
  66.      * Creates a part of the hierarchical nodes structure of the resulting configuration. The passed in element is converted
  67.      * into one or multiple configuration nodes. (If list structures are involved, multiple nodes are returned.)
  68.      *
  69.      * @param key the key of the new node(s)
  70.      * @param elem the element to be processed
  71.      * @return a list with configuration nodes representing the element
  72.      */
  73.     private static List<ImmutableNode> constructHierarchy(final String key, final Object elem) {
  74.         if (elem instanceof Map) {
  75.             return parseMap((Map<String, Object>) elem, key);
  76.         }
  77.         if (elem instanceof Collection) {
  78.             return parseCollection((Collection<Object>) elem, key);
  79.         }
  80.         return Collections.singletonList(new ImmutableNode.Builder().name(key).value(elem).create());
  81.     }

  82.     /**
  83.      * Parses a collection structure. The elements of the collection are processed recursively.
  84.      *
  85.      * @param col the collection to be processed
  86.      * @param key the key under which this collection is to be stored
  87.      * @return a node representing this collection
  88.      */
  89.     private static List<ImmutableNode> parseCollection(final Collection<Object> col, final String key) {
  90.         return col.stream().flatMap(elem -> constructHierarchy(key, elem).stream()).collect(Collectors.toList());
  91.     }

  92.     /**
  93.      * Parses a map structure. The single keys of the map are processed recursively.
  94.      *
  95.      * @param map the map to be processed
  96.      * @param key the key under which this map is to be stored
  97.      * @return a node representing this map
  98.      */
  99.     private static List<ImmutableNode> parseMap(final Map<String, Object> map, final String key) {
  100.         final ImmutableNode.Builder subtree = new ImmutableNode.Builder().name(key);
  101.         map.forEach((k, v) -> constructHierarchy(k, v).forEach(subtree::addChild));
  102.         return Collections.singletonList(subtree.create());
  103.     }

  104.     /**
  105.      * Internal helper method to wrap an exception in a {@code ConfigurationException}.
  106.      *
  107.      * @param e the exception to be wrapped
  108.      * @throws ConfigurationException the resulting exception
  109.      */
  110.     static void rethrowException(final Exception e) throws ConfigurationException {
  111.         if (e instanceof ClassCastException) {
  112.             throw new ConfigurationException("Error parsing", e);
  113.         }
  114.         throw new ConfigurationException("Unable to load the configuration", e);
  115.     }

  116.     /**
  117.      * Creates a new instance of {@code AbstractYAMLBasedConfiguration}.
  118.      */
  119.     protected AbstractYAMLBasedConfiguration() {
  120.         initLogger(new ConfigurationLogger(getClass()));
  121.     }

  122.     /**
  123.      * Creates a new instance of {@code AbstractYAMLBasedConfiguration} as a copy of the specified configuration.
  124.      *
  125.      * @param c the configuration to be copied
  126.      */
  127.     protected AbstractYAMLBasedConfiguration(final HierarchicalConfiguration<ImmutableNode> c) {
  128.         super(c);
  129.         initLogger(new ConfigurationLogger(getClass()));
  130.     }

  131.     /**
  132.      * Constructs a YAML map, i.e. String -&gt; Object from a given configuration node.
  133.      *
  134.      * @param node The configuration node to create a map from.
  135.      * @return A Map that contains the configuration node information.
  136.      */
  137.     protected Map<String, Object> constructMap(final ImmutableNode node) {
  138.         final Map<String, Object> map = new HashMap<>(node.getChildren().size());
  139.         node.forEach(cNode -> addEntry(map, cNode.getNodeName(), cNode.getChildren().isEmpty() ? cNode.getValue() : constructMap(cNode)));
  140.         return map;
  141.     }

  142.     /**
  143.      * Loads this configuration from the content of the specified map. The data in the map is transformed into a hierarchy
  144.      * of {@link ImmutableNode} objects.
  145.      *
  146.      * @param map the map to be processed
  147.      */
  148.     protected void load(final Map<String, Object> map) {
  149.         final List<ImmutableNode> roots = constructHierarchy("", map);
  150.         getNodeModel().setRootNode(roots.get(0));
  151.     }
  152. }