BaseHierarchicalConfiguration.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.Collection;
  19. import java.util.Collections;
  20. import java.util.HashMap;
  21. import java.util.Iterator;
  22. import java.util.LinkedList;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.stream.Collectors;

  26. import org.apache.commons.configuration2.event.ConfigurationEvent;
  27. import org.apache.commons.configuration2.event.EventListener;
  28. import org.apache.commons.configuration2.ex.ConfigurationRuntimeException;
  29. import org.apache.commons.configuration2.interpol.ConfigurationInterpolator;
  30. import org.apache.commons.configuration2.tree.ConfigurationNodeVisitorAdapter;
  31. import org.apache.commons.configuration2.tree.ImmutableNode;
  32. import org.apache.commons.configuration2.tree.InMemoryNodeModel;
  33. import org.apache.commons.configuration2.tree.InMemoryNodeModelSupport;
  34. import org.apache.commons.configuration2.tree.NodeHandler;
  35. import org.apache.commons.configuration2.tree.NodeModel;
  36. import org.apache.commons.configuration2.tree.NodeSelector;
  37. import org.apache.commons.configuration2.tree.NodeTreeWalker;
  38. import org.apache.commons.configuration2.tree.QueryResult;
  39. import org.apache.commons.configuration2.tree.ReferenceNodeHandler;
  40. import org.apache.commons.configuration2.tree.TrackedNodeModel;
  41. import org.apache.commons.lang3.ObjectUtils;

  42. /**
  43.  * <p>
  44.  * A specialized hierarchical configuration implementation that is based on a structure of {@link ImmutableNode}
  45.  * objects.
  46.  * </p>
  47.  */
  48. public class BaseHierarchicalConfiguration extends AbstractHierarchicalConfiguration<ImmutableNode> implements InMemoryNodeModelSupport {

  49.     /**
  50.      * A specialized visitor base class that can be used for storing the tree of configuration nodes. The basic idea is that
  51.      * each node can be associated with a reference object. This reference object has a concrete meaning in a derived class,
  52.      * for example an entry in a JNDI context or an XML element. When the configuration tree is set up, the {@code load()} method
  53.      * is responsible for setting the reference objects. When the configuration tree is later modified, new nodes do not
  54.      * have a defined reference object. This visitor class processes all nodes and finds the ones without a defined
  55.      * reference object. For those nodes the {@code insert()} method is called, which must be defined in concrete sub
  56.      * classes. This method can perform all steps to integrate the new node into the original structure.
  57.      */
  58.     protected abstract static class BuilderVisitor extends ConfigurationNodeVisitorAdapter<ImmutableNode> {
  59.         /**
  60.          * Inserts a new node into the structure constructed by this builder. This method is called for each node that has been
  61.          * added to the configuration tree after the configuration has been loaded from its source. These new nodes have to be
  62.          * inserted into the original structure. The passed in nodes define the position of the node to be inserted: its parent
  63.          * and the siblings between to insert.
  64.          *
  65.          * @param newNode the node to be inserted
  66.          * @param parent the parent node
  67.          * @param sibling1 the sibling after which the node is to be inserted; can be <strong>null</strong> if the new node is going to be
  68.          *        the first child node
  69.          * @param sibling2 the sibling before which the node is to be inserted; can be <strong>null</strong> if the new node is going to
  70.          *        be the last child node
  71.          * @param refHandler the {@code ReferenceNodeHandler}
  72.          */
  73.         protected abstract void insert(ImmutableNode newNode, ImmutableNode parent, ImmutableNode sibling1, ImmutableNode sibling2,
  74.             ReferenceNodeHandler refHandler);

  75.         /**
  76.          * Inserts new children that have been added to the specified node.
  77.          *
  78.          * @param node the current node to be processed
  79.          * @param refHandler the {@code ReferenceNodeHandler}
  80.          */
  81.         private void insertNewChildNodes(final ImmutableNode node, final ReferenceNodeHandler refHandler) {
  82.             final Collection<ImmutableNode> subNodes = new LinkedList<>(refHandler.getChildren(node));
  83.             final Iterator<ImmutableNode> children = subNodes.iterator();
  84.             ImmutableNode sibling1;
  85.             ImmutableNode nd = null;

  86.             while (children.hasNext()) {
  87.                 // find the next new node
  88.                 do {
  89.                     sibling1 = nd;
  90.                     nd = children.next();
  91.                 } while (refHandler.getReference(nd) != null && children.hasNext());

  92.                 if (refHandler.getReference(nd) == null) {
  93.                     // find all following new nodes
  94.                     final List<ImmutableNode> newNodes = new LinkedList<>();
  95.                     newNodes.add(nd);
  96.                     while (children.hasNext()) {
  97.                         nd = children.next();
  98.                         if (refHandler.getReference(nd) != null) {
  99.                             break;
  100.                         }
  101.                         newNodes.add(nd);
  102.                     }

  103.                     // Insert all new nodes
  104.                     final ImmutableNode sibling2 = refHandler.getReference(nd) == null ? null : nd;
  105.                     for (final ImmutableNode insertNode : newNodes) {
  106.                         if (refHandler.getReference(insertNode) == null) {
  107.                             insert(insertNode, node, sibling1, sibling2, refHandler);
  108.                             sibling1 = insertNode;
  109.                         }
  110.                     }
  111.                 }
  112.             }
  113.         }

  114.         /**
  115.          * Updates a node that already existed in the original hierarchy. This method is called for each node that has an
  116.          * assigned reference object. A concrete implementation should update the reference according to the node's current
  117.          * value.
  118.          *
  119.          * @param node the current node to be processed
  120.          * @param reference the reference object for this node
  121.          * @param refHandler the {@code ReferenceNodeHandler}
  122.          */
  123.         protected abstract void update(ImmutableNode node, Object reference, ReferenceNodeHandler refHandler);

  124.         /**
  125.          * Updates the value of a node. If this node is associated with a reference object, the {@code update()} method is
  126.          * called.
  127.          *
  128.          * @param node the current node to be processed
  129.          * @param refHandler the {@code ReferenceNodeHandler}
  130.          */
  131.         private void updateNode(final ImmutableNode node, final ReferenceNodeHandler refHandler) {
  132.             final Object reference = refHandler.getReference(node);
  133.             if (reference != null) {
  134.                 update(node, reference, refHandler);
  135.             }
  136.         }

  137.         @Override
  138.         public void visitBeforeChildren(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
  139.             final ReferenceNodeHandler refHandler = (ReferenceNodeHandler) handler;
  140.             updateNode(node, refHandler);
  141.             insertNewChildNodes(node, refHandler);
  142.         }
  143.     }

  144.     /**
  145.      * A specialized visitor implementation which constructs the root node of a configuration with all variables replaced by
  146.      * their interpolated values.
  147.      */
  148.     private final class InterpolatedVisitor extends ConfigurationNodeVisitorAdapter<ImmutableNode> {
  149.         /** A stack for managing node builder instances. */
  150.         private final List<ImmutableNode.Builder> builderStack;

  151.         /** The resulting root node. */
  152.         private ImmutableNode interpolatedRoot;

  153.         /**
  154.          * Creates a new instance of {@code InterpolatedVisitor}.
  155.          */
  156.         public InterpolatedVisitor() {
  157.             builderStack = new LinkedList<>();
  158.         }

  159.         /**
  160.          * Gets the result of this builder: the root node of the interpolated nodes hierarchy.
  161.          *
  162.          * @return the resulting root node
  163.          */
  164.         public ImmutableNode getInterpolatedRoot() {
  165.             return interpolatedRoot;
  166.         }

  167.         /**
  168.          * Handles interpolation for a node with no children. If interpolation does not change this node, it is copied as is to
  169.          * the resulting structure. Otherwise, a new node is created with the interpolated values.
  170.          *
  171.          * @param node the current node to be processed
  172.          * @param handler the {@code NodeHandler}
  173.          */
  174.         private void handleLeafNode(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
  175.             final Object value = interpolate(node.getValue());
  176.             final Map<String, Object> interpolatedAttributes = new HashMap<>();
  177.             final boolean attributeChanged = interpolateAttributes(node, handler, interpolatedAttributes);
  178.             final ImmutableNode newNode = valueChanged(value, handler.getValue(node)) || attributeChanged
  179.                 ? new ImmutableNode.Builder().name(handler.nodeName(node)).value(value).addAttributes(interpolatedAttributes).create()
  180.                 : node;
  181.             storeInterpolatedNode(newNode);
  182.         }

  183.         /**
  184.          * Returns a map with interpolated attributes of the passed in node.
  185.          *
  186.          * @param node the current node to be processed
  187.          * @param handler the {@code NodeHandler}
  188.          * @return the map with interpolated attributes
  189.          */
  190.         private Map<String, Object> interpolateAttributes(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
  191.             final Map<String, Object> attributes = new HashMap<>();
  192.             interpolateAttributes(node, handler, attributes);
  193.             return attributes;
  194.         }

  195.         /**
  196.          * Populates a map with interpolated attributes of the passed in node.
  197.          *
  198.          * @param node the current node to be processed
  199.          * @param handler the {@code NodeHandler}
  200.          * @param interpolatedAttributes a map for storing the results
  201.          * @return a flag whether an attribute value was changed by interpolation
  202.          */
  203.         private boolean interpolateAttributes(final ImmutableNode node, final NodeHandler<ImmutableNode> handler,
  204.             final Map<String, Object> interpolatedAttributes) {
  205.             boolean attributeChanged = false;
  206.             for (final String attr : handler.getAttributes(node)) {
  207.                 final Object attrValue = interpolate(handler.getAttributeValue(node, attr));
  208.                 if (valueChanged(attrValue, handler.getAttributeValue(node, attr))) {
  209.                     attributeChanged = true;
  210.                 }
  211.                 interpolatedAttributes.put(attr, attrValue);
  212.             }
  213.             return attributeChanged;
  214.         }

  215.         /**
  216.          * Returns a flag whether the given node is a leaf. This is the case if it does not have children.
  217.          *
  218.          * @param node the node in question
  219.          * @param handler the {@code NodeHandler}
  220.          * @return a flag whether this is a leaf node
  221.          */
  222.         private boolean isLeafNode(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
  223.             return handler.getChildren(node).isEmpty();
  224.         }

  225.         /**
  226.          * Returns the top-level element from the stack without removing it.
  227.          *
  228.          * @return the top-level element from the stack
  229.          */
  230.         private ImmutableNode.Builder peek() {
  231.             return builderStack.get(0);
  232.         }

  233.         /**
  234.          * Pops the top-level element from the stack.
  235.          *
  236.          * @return the element popped from the stack
  237.          */
  238.         private ImmutableNode.Builder pop() {
  239.             return builderStack.remove(0);
  240.         }

  241.         /**
  242.          * Pushes a new builder on the stack.
  243.          *
  244.          * @param builder the builder
  245.          */
  246.         private void push(final ImmutableNode.Builder builder) {
  247.             builderStack.add(0, builder);
  248.         }

  249.         /**
  250.          * Stores a processed node. Per default, the node is added to the current builder on the stack. If no such builder
  251.          * exists, this is the result node.
  252.          *
  253.          * @param node the node to be stored
  254.          */
  255.         private void storeInterpolatedNode(final ImmutableNode node) {
  256.             if (builderStack.isEmpty()) {
  257.                 interpolatedRoot = node;
  258.             } else {
  259.                 peek().addChild(node);
  260.             }
  261.         }

  262.         /**
  263.          * Tests whether a value is changed because of interpolation.
  264.          *
  265.          * @param interpolatedValue the interpolated value
  266.          * @param value the original value
  267.          * @return a flag whether the value was changed
  268.          */
  269.         private boolean valueChanged(final Object interpolatedValue, final Object value) {
  270.             return ObjectUtils.notEqual(interpolatedValue, value);
  271.         }

  272.         @Override
  273.         public void visitAfterChildren(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
  274.             if (!isLeafNode(node, handler)) {
  275.                 final ImmutableNode newNode = pop().create();
  276.                 storeInterpolatedNode(newNode);
  277.             }
  278.         }

  279.         @Override
  280.         public void visitBeforeChildren(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
  281.             if (isLeafNode(node, handler)) {
  282.                 handleLeafNode(node, handler);
  283.             } else {
  284.                 final ImmutableNode.Builder builder = new ImmutableNode.Builder(handler.getChildrenCount(node, null)).name(handler.nodeName(node))
  285.                     .value(interpolate(handler.getValue(node))).addAttributes(interpolateAttributes(node, handler));
  286.                 push(builder);
  287.             }
  288.         }
  289.     }

  290.     /**
  291.      * Creates the {@code NodeModel} for this configuration based on a passed in source configuration. This implementation
  292.      * creates an {@link InMemoryNodeModel}. If the passed in source configuration is defined, its root node also becomes
  293.      * the root node of this configuration. Otherwise, a new, empty root node is used.
  294.      *
  295.      * @param c the configuration that is to be copied
  296.      * @return the {@code NodeModel} for the new configuration
  297.      */
  298.     private static NodeModel<ImmutableNode> createNodeModel(final HierarchicalConfiguration<ImmutableNode> c) {
  299.         return new InMemoryNodeModel(obtainRootNode(c));
  300.     }

  301.     /**
  302.      * Obtains the root node from a configuration whose data is to be copied. It has to be ensured that the synchronizer is
  303.      * called correctly.
  304.      *
  305.      * @param c the configuration that is to be copied
  306.      * @return the root node of this configuration
  307.      */
  308.     private static ImmutableNode obtainRootNode(final HierarchicalConfiguration<ImmutableNode> c) {
  309.         return c != null ? c.getNodeModel().getNodeHandler().getRootNode() : null;
  310.     }

  311.     /**
  312.      * Creates a list with immutable configurations from the given input list.
  313.      *
  314.      * @param subs a list with mutable configurations
  315.      * @return a list with corresponding immutable configurations
  316.      */
  317.     private static List<ImmutableHierarchicalConfiguration> toImmutable(final List<? extends HierarchicalConfiguration<?>> subs) {
  318.         return subs.stream().map(ConfigurationUtils::unmodifiableConfiguration).collect(Collectors.toList());
  319.     }

  320.     /** A listener for reacting on changes caused by sub configurations. */
  321.     private final EventListener<ConfigurationEvent> changeListener;

  322.     /**
  323.      * Creates a new instance of {@code BaseHierarchicalConfiguration}.
  324.      */
  325.     public BaseHierarchicalConfiguration() {
  326.         this((HierarchicalConfiguration<ImmutableNode>) null);
  327.     }

  328.     /**
  329.      * Creates a new instance of {@code BaseHierarchicalConfiguration} and copies all data contained in the specified
  330.      * configuration into the new one.
  331.      *
  332.      * @param c the configuration that is to be copied (if <strong>null</strong>, this constructor will behave like the standard
  333.      *        constructor)
  334.      * @since 1.4
  335.      */
  336.     public BaseHierarchicalConfiguration(final HierarchicalConfiguration<ImmutableNode> c) {
  337.         this(createNodeModel(c));
  338.     }

  339.     /**
  340.      * Creates a new instance of {@code BaseHierarchicalConfiguration} and initializes it with the given {@code NodeModel}.
  341.      *
  342.      * @param model the {@code NodeModel}
  343.      */
  344.     protected BaseHierarchicalConfiguration(final NodeModel<ImmutableNode> model) {
  345.         super(model);
  346.         changeListener = createChangeListener();
  347.     }

  348.     /**
  349.      * {@inheritDoc} This implementation resolves the node(s) selected by the given key. If not a single node is selected,
  350.      * an empty list is returned. Otherwise, sub configurations for each child of the node are created.
  351.      */
  352.     @Override
  353.     public List<HierarchicalConfiguration<ImmutableNode>> childConfigurationsAt(final String key) {
  354.         final List<ImmutableNode> nodes = syncRead(() -> fetchFilteredNodeResults(key), false);
  355.         if (nodes.size() != 1) {
  356.             return Collections.emptyList();
  357.         }
  358.         return nodes.get(0).stream().map(this::createIndependentSubConfigurationForNode).collect(Collectors.toList());
  359.     }

  360.     /**
  361.      * {@inheritDoc} This method works like {@link #childConfigurationsAt(String)}; however, depending on the value of the
  362.      * {@code supportUpdates} flag, connected sub configurations may be created.
  363.      */
  364.     @Override
  365.     public List<HierarchicalConfiguration<ImmutableNode>> childConfigurationsAt(final String key, final boolean supportUpdates) {
  366.         if (!supportUpdates) {
  367.             return childConfigurationsAt(key);
  368.         }

  369.         final InMemoryNodeModel parentModel = getSubConfigurationParentModel();
  370.         return createConnectedSubConfigurations(this, parentModel.trackChildNodes(key, this));
  371.     }

  372.     /**
  373.      * {@inheritDoc} This implementation creates a new instance of {@link InMemoryNodeModel}, initialized with this
  374.      * configuration's root node. This has the effect that although the same nodes are used, the original and copied
  375.      * configurations are independent on each other.
  376.      */
  377.     @Override
  378.     protected NodeModel<ImmutableNode> cloneNodeModel() {
  379.         return new InMemoryNodeModel(getModel().getNodeHandler().getRootNode());
  380.     }

  381.     /**
  382.      * {@inheritDoc} This is a short form for {@code configurationAt(key,
  383.      * <strong>false</strong>)}.
  384.      *
  385.      * @throws ConfigurationRuntimeException if the key does not select a single node
  386.      */
  387.     @Override
  388.     public HierarchicalConfiguration<ImmutableNode> configurationAt(final String key) {
  389.         return configurationAt(key, false);
  390.     }

  391.     /**
  392.      * {@inheritDoc} The result of this implementation depends on the {@code supportUpdates} flag: If it is <strong>false</strong>, a
  393.      * plain {@code BaseHierarchicalConfiguration} is returned using the selected node as root node. This is suitable for
  394.      * read-only access to properties. Because the configuration returned in this case is not connected to the parent
  395.      * configuration, updates on properties made by one configuration are not reflected by the other one. A value of
  396.      * <strong>true</strong> for this parameter causes a tracked node to be created, and result is a {@link SubnodeConfiguration}
  397.      * based on this tracked node. This configuration is really connected to its parent, so that updated properties are
  398.      * visible on both.
  399.      *
  400.      * @see SubnodeConfiguration
  401.      * @throws ConfigurationRuntimeException if the key does not select a single node
  402.      */
  403.     @Override
  404.     public HierarchicalConfiguration<ImmutableNode> configurationAt(final String key, final boolean supportUpdates) {
  405.         return syncRead(() -> supportUpdates ? createConnectedSubConfiguration(key) : createIndependentSubConfiguration(key), false);
  406.     }

  407.     /**
  408.      * {@inheritDoc} This implementation creates sub configurations in the same way as described for
  409.      * {@link #configurationAt(String)}.
  410.      */
  411.     @Override
  412.     public List<HierarchicalConfiguration<ImmutableNode>> configurationsAt(final String key) {
  413.         final List<ImmutableNode> nodes = syncRead(() -> fetchFilteredNodeResults(key), false);
  414.         return nodes.stream().map(this::createIndependentSubConfigurationForNode).collect(Collectors.toList());
  415.     }

  416.     /**
  417.      * {@inheritDoc} This implementation creates tracked nodes for the specified key. Then sub configurations for these
  418.      * nodes are created and returned.
  419.      */
  420.     @Override
  421.     public List<HierarchicalConfiguration<ImmutableNode>> configurationsAt(final String key, final boolean supportUpdates) {
  422.         if (!supportUpdates) {
  423.             return configurationsAt(key);
  424.         }
  425.         final InMemoryNodeModel parentModel = syncRead(this::getSubConfigurationParentModel, false);
  426.         return createConnectedSubConfigurations(this, parentModel.selectAndTrackNodes(key, this));
  427.     }

  428.     /**
  429.      * Creates a listener which reacts on all changes on this configuration or one of its {@code SubnodeConfiguration}
  430.      * instances. If such a change is detected, some updates have to be performed.
  431.      *
  432.      * @return the newly created change listener
  433.      */
  434.     private EventListener<ConfigurationEvent> createChangeListener() {
  435.         return this::subnodeConfigurationChanged;
  436.     }

  437.     /**
  438.      * Creates a sub configuration from the specified key which is connected to this configuration. This implementation
  439.      * creates a {@link SubnodeConfiguration} with a tracked node identified by the passed in key.
  440.      *
  441.      * @param key the key of the sub configuration
  442.      * @return the new sub configuration
  443.      */
  444.     private BaseHierarchicalConfiguration createConnectedSubConfiguration(final String key) {
  445.         final NodeSelector selector = getSubConfigurationNodeSelector(key);
  446.         getSubConfigurationParentModel().trackNode(selector, this);
  447.         return createSubConfigurationForTrackedNode(selector, this);
  448.     }

  449.     /**
  450.      * Creates a list of connected sub configurations based on a passed in list of node selectors.
  451.      *
  452.      * @param parentModelSupport the parent node model support object
  453.      * @param selectors the list of {@code NodeSelector} objects
  454.      * @return the list with sub configurations
  455.      */
  456.     private List<HierarchicalConfiguration<ImmutableNode>> createConnectedSubConfigurations(final InMemoryNodeModelSupport parentModelSupport,
  457.         final Collection<NodeSelector> selectors) {
  458.         return selectors.stream().map(sel -> createSubConfigurationForTrackedNode(sel, parentModelSupport)).collect(Collectors.toList());
  459.     }

  460.     /**
  461.      * Creates a sub configuration from the specified key which is independent on this configuration. This means that the
  462.      * sub configuration operates on a separate node model (although the nodes are initially shared).
  463.      *
  464.      * @param key the key of the sub configuration
  465.      * @return the new sub configuration
  466.      */
  467.     private BaseHierarchicalConfiguration createIndependentSubConfiguration(final String key) {
  468.         final List<ImmutableNode> targetNodes = fetchFilteredNodeResults(key);
  469.         final int size = targetNodes.size();
  470.         if (size != 1) {
  471.             throw new ConfigurationRuntimeException("Passed in key must select exactly one node (found %,d): %s", size, key);
  472.         }
  473.         final BaseHierarchicalConfiguration sub = new BaseHierarchicalConfiguration(new InMemoryNodeModel(targetNodes.get(0)));
  474.         initSubConfiguration(sub);
  475.         return sub;
  476.     }

  477.     /**
  478.      * Returns an initialized sub configuration for this configuration that is based on another
  479.      * {@code BaseHierarchicalConfiguration}. Thus, it is independent from this configuration.
  480.      *
  481.      * @param node the root node for the sub configuration
  482.      * @return the initialized sub configuration
  483.      */
  484.     private BaseHierarchicalConfiguration createIndependentSubConfigurationForNode(final ImmutableNode node) {
  485.         final BaseHierarchicalConfiguration sub = new BaseHierarchicalConfiguration(new InMemoryNodeModel(node));
  486.         initSubConfiguration(sub);
  487.         return sub;
  488.     }

  489.     /**
  490.      * Creates a connected sub configuration based on a selector for a tracked node.
  491.      *
  492.      * @param selector the {@code NodeSelector}
  493.      * @param parentModelSupport the {@code InMemoryNodeModelSupport} object for the parent node model
  494.      * @return the newly created sub configuration
  495.      * @since 2.0
  496.      */
  497.     protected SubnodeConfiguration createSubConfigurationForTrackedNode(final NodeSelector selector, final InMemoryNodeModelSupport parentModelSupport) {
  498.         final SubnodeConfiguration subConfig = new SubnodeConfiguration(this, new TrackedNodeModel(parentModelSupport, selector, true));
  499.         initSubConfigurationForThisParent(subConfig);
  500.         return subConfig;
  501.     }

  502.     /**
  503.      * Creates a root node for a subset configuration based on the passed in query results. This method creates a new root
  504.      * node and adds the children and attributes of all result nodes to it. If only a single node value is defined, it is
  505.      * assigned as value of the new root node.
  506.      *
  507.      * @param results the collection of query results
  508.      * @return the root node for the subset configuration
  509.      */
  510.     private ImmutableNode createSubsetRootNode(final Collection<QueryResult<ImmutableNode>> results) {
  511.         final ImmutableNode.Builder builder = new ImmutableNode.Builder();
  512.         Object value = null;
  513.         int valueCount = 0;

  514.         for (final QueryResult<ImmutableNode> result : results) {
  515.             if (result.isAttributeResult()) {
  516.                 builder.addAttribute(result.getAttributeName(), result.getAttributeValue(getModel().getNodeHandler()));
  517.             } else {
  518.                 if (result.getNode().getValue() != null) {
  519.                     value = result.getNode().getValue();
  520.                     valueCount++;
  521.                 }
  522.                 builder.addChildren(result.getNode().getChildren());
  523.                 builder.addAttributes(result.getNode().getAttributes());
  524.             }
  525.         }

  526.         if (valueCount == 1) {
  527.             builder.value(value);
  528.         }
  529.         return builder.create();
  530.     }

  531.     /**
  532.      * Executes a query on the specified key and filters it for node results.
  533.      *
  534.      * @param key the key
  535.      * @return the filtered list with result nodes
  536.      */
  537.     private List<ImmutableNode> fetchFilteredNodeResults(final String key) {
  538.         final NodeHandler<ImmutableNode> handler = getModel().getNodeHandler();
  539.         return resolveNodeKey(handler.getRootNode(), key, handler);
  540.     }

  541.     /**
  542.      * {@inheritDoc} This implementation returns the {@code InMemoryNodeModel} used by this configuration.
  543.      */
  544.     @Override
  545.     public InMemoryNodeModel getNodeModel() {
  546.         return (InMemoryNodeModel) super.getNodeModel();
  547.     }

  548.     /**
  549.      * Gets the {@code NodeSelector} to be used for a sub configuration based on the passed in key. This method is called
  550.      * whenever a sub configuration is to be created. This base implementation returns a new {@code NodeSelector}
  551.      * initialized with the passed in key. Sub classes may override this method if they have a different strategy for
  552.      * creating a selector.
  553.      *
  554.      * @param key the key of the sub configuration
  555.      * @return a {@code NodeSelector} for initializing a sub configuration
  556.      * @since 2.0
  557.      */
  558.     protected NodeSelector getSubConfigurationNodeSelector(final String key) {
  559.         return new NodeSelector(key);
  560.     }

  561.     /**
  562.      * Gets the {@code InMemoryNodeModel} to be used as parent model for a new sub configuration. This method is called
  563.      * whenever a sub configuration is to be created. This base implementation returns the model of this configuration. Sub
  564.      * classes with different requirements for the parent models of sub configurations have to override it.
  565.      *
  566.      * @return the parent model for a new sub configuration
  567.      */
  568.     protected InMemoryNodeModel getSubConfigurationParentModel() {
  569.         return (InMemoryNodeModel) getModel();
  570.     }

  571.     /**
  572.      * {@inheritDoc} This implementation first delegates to {@code childConfigurationsAt()} to create a list of mutable
  573.      * child configurations. Then a list with immutable wrapper configurations is created.
  574.      */
  575.     @Override
  576.     public List<ImmutableHierarchicalConfiguration> immutableChildConfigurationsAt(final String key) {
  577.         return toImmutable(childConfigurationsAt(key));
  578.     }

  579.     /**
  580.      * {@inheritDoc} This implementation creates a {@code SubnodeConfiguration} by delegating to {@code configurationAt()}.
  581.      * Then an immutable wrapper is created and returned.
  582.      *
  583.      * @throws ConfigurationRuntimeException if the key does not select a single node
  584.      */
  585.     @Override
  586.     public ImmutableHierarchicalConfiguration immutableConfigurationAt(final String key) {
  587.         return ConfigurationUtils.unmodifiableConfiguration(configurationAt(key));
  588.     }

  589.     /**
  590.      * {@inheritDoc} This implementation creates a {@code SubnodeConfiguration} by delegating to {@code configurationAt()}.
  591.      * Then an immutable wrapper is created and returned.
  592.      */
  593.     @Override
  594.     public ImmutableHierarchicalConfiguration immutableConfigurationAt(final String key, final boolean supportUpdates) {
  595.         return ConfigurationUtils.unmodifiableConfiguration(configurationAt(key, supportUpdates));
  596.     }

  597.     /**
  598.      * {@inheritDoc} This implementation first delegates to {@code configurationsAt()} to create a list of
  599.      * {@code SubnodeConfiguration} objects. Then for each element of this list an unmodifiable wrapper is created.
  600.      */
  601.     @Override
  602.     public List<ImmutableHierarchicalConfiguration> immutableConfigurationsAt(final String key) {
  603.         return toImmutable(configurationsAt(key));
  604.     }

  605.     /**
  606.      * Initializes properties of a sub configuration. A sub configuration inherits some settings from its parent, for example the
  607.      * expression engine or the synchronizer. The corresponding values are copied by this method.
  608.      *
  609.      * @param sub the sub configuration to be initialized
  610.      */
  611.     private void initSubConfiguration(final BaseHierarchicalConfiguration sub) {
  612.         sub.setSynchronizer(getSynchronizer());
  613.         sub.setExpressionEngine(getExpressionEngine());
  614.         sub.setListDelimiterHandler(getListDelimiterHandler());
  615.         sub.setThrowExceptionOnMissing(isThrowExceptionOnMissing());
  616.         sub.getInterpolator().setParentInterpolator(getInterpolator());
  617.     }

  618.     /**
  619.      * Initializes a {@code SubnodeConfiguration} object. This method should be called for each sub configuration created
  620.      * for this configuration. It ensures that the sub configuration is correctly connected to its parent instance and that
  621.      * update events are correctly propagated.
  622.      *
  623.      * @param subConfig the sub configuration to be initialized
  624.      * @since 2.0
  625.      */
  626.     protected void initSubConfigurationForThisParent(final SubnodeConfiguration subConfig) {
  627.         initSubConfiguration(subConfig);
  628.         subConfig.addEventListener(ConfigurationEvent.ANY, changeListener);
  629.     }

  630.     /**
  631.      * Returns a configuration with the same content as this configuration, but with all variables replaced by their actual
  632.      * values. This implementation is specific for hierarchical configurations. It clones the current configuration and runs
  633.      * a specialized visitor on the clone, which performs interpolation on the single configuration nodes.
  634.      *
  635.      * @return a configuration with all variables interpolated
  636.      * @since 1.5
  637.      */
  638.     @Override
  639.     public Configuration interpolatedConfiguration() {
  640.         final InterpolatedVisitor visitor = new InterpolatedVisitor();
  641.         final NodeHandler<ImmutableNode> handler = getModel().getNodeHandler();
  642.         NodeTreeWalker.INSTANCE.walkDFS(handler.getRootNode(), visitor, handler);

  643.         final BaseHierarchicalConfiguration c = (BaseHierarchicalConfiguration) clone();
  644.         c.getNodeModel().setRootNode(visitor.getInterpolatedRoot());
  645.         return c;
  646.     }

  647.     /**
  648.      * This method is always called when a subnode configuration created from this configuration has been modified. This
  649.      * implementation transforms the received event into an event of type {@code SUBNODE_CHANGED} and notifies the
  650.      * registered listeners.
  651.      *
  652.      * @param event the event describing the change
  653.      * @since 1.5
  654.      */
  655.     protected void subnodeConfigurationChanged(final ConfigurationEvent event) {
  656.         fireEvent(ConfigurationEvent.SUBNODE_CHANGED, null, event, event.isBeforeUpdate());
  657.     }

  658.     /**
  659.      * Creates a new {@code Configuration} object containing all keys that start with the specified prefix. This
  660.      * implementation will return a {@code BaseHierarchicalConfiguration} object so that the structure of the keys will be
  661.      * saved. The nodes selected by the prefix (it is possible that multiple nodes are selected) are mapped to the root node
  662.      * of the returned configuration, i.e. their children and attributes will become children and attributes of the new root
  663.      * node. However, a value of the root node is only set if exactly one of the selected nodes contain a value (if multiple
  664.      * nodes have a value, there is simply no way to decide how these values are merged together). Note that the returned
  665.      * {@code Configuration} object is not connected to its source configuration: updates on the source configuration are
  666.      * not reflected in the subset and vice versa. The returned configuration uses the same {@code Synchronizer} as this
  667.      * configuration.
  668.      *
  669.      * @param prefix the prefix of the keys for the subset
  670.      * @return a new configuration object representing the selected subset
  671.      */
  672.     @Override
  673.     public Configuration subset(final String prefix) {
  674.         return syncRead(() -> {
  675.             final List<QueryResult<ImmutableNode>> results = fetchNodeList(prefix);
  676.             if (results.isEmpty()) {
  677.                 return new BaseHierarchicalConfiguration();
  678.             }
  679.             final BaseHierarchicalConfiguration parent = this;
  680.             final BaseHierarchicalConfiguration result = new BaseHierarchicalConfiguration() {

  681.                 @Override
  682.                 public ConfigurationInterpolator getInterpolator() {
  683.                     return parent.getInterpolator();
  684.                 }

  685.                 // Override interpolate to always interpolate on the parent
  686.                 @Override
  687.                 protected Object interpolate(final Object value) {
  688.                     return parent.interpolate(value);
  689.                 }
  690.             };
  691.             result.getModel().setRootNode(createSubsetRootNode(results));
  692.             if (result.isEmpty()) {
  693.                 return new BaseHierarchicalConfiguration();
  694.             }
  695.             result.setSynchronizer(getSynchronizer());
  696.             return result;
  697.         }, false);
  698.     }
  699. }