HierarchicalConfigurationConverter.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.HashSet;
  22. import java.util.Iterator;
  23. import java.util.List;
  24. import java.util.Set;

  25. import org.apache.commons.configuration2.tree.DefaultConfigurationKey;
  26. import org.apache.commons.configuration2.tree.DefaultExpressionEngine;

  27. /**
  28.  * <p>
  29.  * A base class for converters that transform a normal configuration object into a hierarchical configuration.
  30.  * </p>
  31.  * <p>
  32.  * This class provides a default mechanism for iterating over the keys in a configuration and to throw corresponding
  33.  * element start and end events. By handling these events a hierarchy can be constructed that is equivalent to the keys
  34.  * in the original configuration.
  35.  * </p>
  36.  * <p>
  37.  * Concrete sub classes will implement event handlers that generate SAX events for XML processing or construct a
  38.  * {@code HierarchicalConfiguration} root node. All in all with this class it is possible to treat a default
  39.  * configuration as if it was a hierarchical configuration, which can be sometimes useful.
  40.  * </p>
  41.  *
  42.  * @see HierarchicalConfiguration
  43.  */
  44. abstract class HierarchicalConfigurationConverter {
  45.     /**
  46.      * Fires all necessary element end events for the specified keys. This method is called for each key obtained from the
  47.      * configuration to be converted. It calculates the common part of the actual and the last processed key and thus
  48.      * determines how many elements must be closed.
  49.      *
  50.      * @param keyLast the last processed key
  51.      * @param keyAct the actual key
  52.      */
  53.     protected void closeElements(final DefaultConfigurationKey keyLast, final DefaultConfigurationKey keyAct) {
  54.         final DefaultConfigurationKey keyDiff = keyAct.differenceKey(keyLast);
  55.         final Iterator<String> it = reverseIterator(keyDiff);
  56.         if (it.hasNext()) {
  57.             // Skip first because it has already been closed by fireValue()
  58.             it.next();
  59.         }

  60.         while (it.hasNext()) {
  61.             elementEnd(it.next());
  62.         }
  63.     }

  64.     /**
  65.      * An event handler method that is called when an element ends. For each call of {@code elementStart()} there will be a
  66.      * corresponding call of this method. Concrete sub classes must implement it to perform a proper event handling.
  67.      *
  68.      * @param name the name of the ending element
  69.      */
  70.     protected abstract void elementEnd(String name);

  71.     /**
  72.      * An event handler method that is called when an element starts. Concrete sub classes must implement it to perform a
  73.      * proper event handling.
  74.      *
  75.      * @param name the name of the new element
  76.      * @param value the element's value; can be <strong>null</strong> if the element does not have any value
  77.      */
  78.     protected abstract void elementStart(String name, Object value);

  79.     /**
  80.      * Fires all necessary element start events with the actual element values. This method is called for each key obtained
  81.      * from the configuration to be processed with the last part of the key as argument. The value can be either a single
  82.      * value or a collection.
  83.      *
  84.      * @param name the name of the actual element
  85.      * @param value the element's value
  86.      */
  87.     protected void fireValue(final String name, final Object value) {
  88.         if (value instanceof Collection) {
  89.             final Collection<?> valueCol = (Collection<?>) value;
  90.             valueCol.forEach(v -> fireValue(name, v));
  91.         } else {
  92.             elementStart(name, value);
  93.             elementEnd(name);
  94.         }
  95.     }

  96.     /**
  97.      * Fires all necessary element start events for the specified key. This method is called for each key obtained from the
  98.      * configuration to be converted. It ensures that all elements "between" the last key and the actual key are opened and
  99.      * their values are set.
  100.      *
  101.      * @param keyLast the last processed key
  102.      * @param keyAct the actual key
  103.      * @param config the configuration to process
  104.      * @param keySet the set with the processed keys
  105.      * @return the name of the last element on the path
  106.      */
  107.     protected String openElements(final DefaultConfigurationKey keyLast, final DefaultConfigurationKey keyAct, final Configuration config,
  108.         final Set<String> keySet) {
  109.         final DefaultConfigurationKey.KeyIterator it = keyLast.differenceKey(keyAct).iterator();
  110.         final DefaultConfigurationKey k = keyLast.commonKey(keyAct);
  111.         for (it.nextKey(); it.hasNext(); it.nextKey()) {
  112.             k.append(it.currentKey(true));
  113.             elementStart(it.currentKey(true), config.getProperty(k.toString()));
  114.             keySet.add(k.toString());
  115.         }
  116.         return it.currentKey(true);
  117.     }

  118.     /**
  119.      * Processes the specified configuration object. This method implements the iteration over the configuration's keys. All
  120.      * defined keys are translated into a set of element start and end events represented by calls to the
  121.      * {@code elementStart()} and {@code elementEnd()} methods.
  122.      *
  123.      * @param config the configuration to be processed
  124.      */
  125.     public void process(final Configuration config) {
  126.         if (config != null) {
  127.             final DefaultExpressionEngine exprEngine = DefaultExpressionEngine.INSTANCE;
  128.             final DefaultConfigurationKey keyEmpty = new DefaultConfigurationKey(exprEngine);
  129.             DefaultConfigurationKey keyLast = keyEmpty;
  130.             final Set<String> keySet = new HashSet<>();

  131.             for (final Iterator<String> it = config.getKeys(); it.hasNext();) {
  132.                 final String key = it.next();
  133.                 if (keySet.contains(key)) {
  134.                     // this key has already been processed by openElements
  135.                     continue;
  136.                 }
  137.                 final DefaultConfigurationKey keyAct = new DefaultConfigurationKey(exprEngine, key);
  138.                 closeElements(keyLast, keyAct);
  139.                 final String elem = openElements(keyLast, keyAct, config, keySet);
  140.                 fireValue(elem, config.getProperty(key));
  141.                 keyLast = keyAct;
  142.             }

  143.             // close all open
  144.             closeElements(keyLast, keyEmpty);
  145.         }
  146.     }

  147.     /**
  148.      * Helper method for determining a reverse iterator for the specified key. This implementation returns an iterator that
  149.      * returns the parts of the given key in reverse order, ignoring indices.
  150.      *
  151.      * @param key the key
  152.      * @return a reverse iterator for the parts of this key
  153.      */
  154.     protected Iterator<String> reverseIterator(final DefaultConfigurationKey key) {
  155.         final List<String> list = new ArrayList<>();
  156.         for (final DefaultConfigurationKey.KeyIterator it = key.iterator(); it.hasNext();) {
  157.             list.add(it.nextKey());
  158.         }
  159.         Collections.reverse(list);
  160.         return list.iterator();
  161.     }
  162. }