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 java.util.Collection;
021import java.util.Collections;
022import java.util.HashMap;
023import java.util.Iterator;
024import java.util.LinkedList;
025import java.util.List;
026import java.util.Map;
027import java.util.stream.Collectors;
028
029import org.apache.commons.configuration2.event.ConfigurationEvent;
030import org.apache.commons.configuration2.event.EventListener;
031import org.apache.commons.configuration2.ex.ConfigurationRuntimeException;
032import org.apache.commons.configuration2.interpol.ConfigurationInterpolator;
033import org.apache.commons.configuration2.tree.ConfigurationNodeVisitorAdapter;
034import org.apache.commons.configuration2.tree.ImmutableNode;
035import org.apache.commons.configuration2.tree.InMemoryNodeModel;
036import org.apache.commons.configuration2.tree.InMemoryNodeModelSupport;
037import org.apache.commons.configuration2.tree.NodeHandler;
038import org.apache.commons.configuration2.tree.NodeModel;
039import org.apache.commons.configuration2.tree.NodeSelector;
040import org.apache.commons.configuration2.tree.NodeTreeWalker;
041import org.apache.commons.configuration2.tree.QueryResult;
042import org.apache.commons.configuration2.tree.ReferenceNodeHandler;
043import org.apache.commons.configuration2.tree.TrackedNodeModel;
044import org.apache.commons.lang3.ObjectUtils;
045
046/**
047 * <p>
048 * A specialized hierarchical configuration implementation that is based on a structure of {@link ImmutableNode}
049 * objects.
050 * </p>
051 */
052public class BaseHierarchicalConfiguration extends AbstractHierarchicalConfiguration<ImmutableNode> implements InMemoryNodeModelSupport {
053
054    /**
055     * A specialized visitor base class that can be used for storing the tree of configuration nodes. The basic idea is that
056     * each node can be associated with a reference object. This reference object has a concrete meaning in a derived class,
057     * e.g. an entry in a JNDI context or an XML element. When the configuration tree is set up, the {@code load()} method
058     * is responsible for setting the reference objects. When the configuration tree is later modified, new nodes do not
059     * have a defined reference object. This visitor class processes all nodes and finds the ones without a defined
060     * reference object. For those nodes the {@code insert()} method is called, which must be defined in concrete sub
061     * classes. This method can perform all steps to integrate the new node into the original structure.
062     */
063    protected abstract static class BuilderVisitor extends ConfigurationNodeVisitorAdapter<ImmutableNode> {
064        /**
065         * Inserts a new node into the structure constructed by this builder. This method is called for each node that has been
066         * added to the configuration tree after the configuration has been loaded from its source. These new nodes have to be
067         * inserted into the original structure. The passed in nodes define the position of the node to be inserted: its parent
068         * and the siblings between to insert.
069         *
070         * @param newNode the node to be inserted
071         * @param parent the parent node
072         * @param sibling1 the sibling after which the node is to be inserted; can be <b>null</b> if the new node is going to be
073         *        the first child node
074         * @param sibling2 the sibling before which the node is to be inserted; can be <b>null</b> if the new node is going to
075         *        be the last child node
076         * @param refHandler the {@code ReferenceNodeHandler}
077         */
078        protected abstract void insert(ImmutableNode newNode, ImmutableNode parent, ImmutableNode sibling1, ImmutableNode sibling2,
079            ReferenceNodeHandler refHandler);
080
081        /**
082         * Inserts new children that have been added to the specified node.
083         *
084         * @param node the current node to be processed
085         * @param refHandler the {@code ReferenceNodeHandler}
086         */
087        private void insertNewChildNodes(final ImmutableNode node, final ReferenceNodeHandler refHandler) {
088            final Collection<ImmutableNode> subNodes = new LinkedList<>(refHandler.getChildren(node));
089            final Iterator<ImmutableNode> children = subNodes.iterator();
090            ImmutableNode sibling1;
091            ImmutableNode nd = null;
092
093            while (children.hasNext()) {
094                // find the next new node
095                do {
096                    sibling1 = nd;
097                    nd = children.next();
098                } while (refHandler.getReference(nd) != null && children.hasNext());
099
100                if (refHandler.getReference(nd) == null) {
101                    // find all following new nodes
102                    final List<ImmutableNode> newNodes = new LinkedList<>();
103                    newNodes.add(nd);
104                    while (children.hasNext()) {
105                        nd = children.next();
106                        if (refHandler.getReference(nd) != null) {
107                            break;
108                        }
109                        newNodes.add(nd);
110                    }
111
112                    // Insert all new nodes
113                    final ImmutableNode sibling2 = refHandler.getReference(nd) == null ? null : nd;
114                    for (final ImmutableNode insertNode : newNodes) {
115                        if (refHandler.getReference(insertNode) == null) {
116                            insert(insertNode, node, sibling1, sibling2, refHandler);
117                            sibling1 = insertNode;
118                        }
119                    }
120                }
121            }
122        }
123
124        /**
125         * Updates a node that already existed in the original hierarchy. This method is called for each node that has an
126         * assigned reference object. A concrete implementation should update the reference according to the node's current
127         * value.
128         *
129         * @param node the current node to be processed
130         * @param reference the reference object for this node
131         * @param refHandler the {@code ReferenceNodeHandler}
132         */
133        protected abstract void update(ImmutableNode node, Object reference, ReferenceNodeHandler refHandler);
134
135        /**
136         * Updates the value of a node. If this node is associated with a reference object, the {@code update()} method is
137         * called.
138         *
139         * @param node the current node to be processed
140         * @param refHandler the {@code ReferenceNodeHandler}
141         */
142        private void updateNode(final ImmutableNode node, final ReferenceNodeHandler refHandler) {
143            final Object reference = refHandler.getReference(node);
144            if (reference != null) {
145                update(node, reference, refHandler);
146            }
147        }
148
149        @Override
150        public void visitBeforeChildren(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
151            final ReferenceNodeHandler refHandler = (ReferenceNodeHandler) handler;
152            updateNode(node, refHandler);
153            insertNewChildNodes(node, refHandler);
154        }
155    }
156
157    /**
158     * A specialized visitor implementation which constructs the root node of a configuration with all variables replaced by
159     * their interpolated values.
160     */
161    private final class InterpolatedVisitor extends ConfigurationNodeVisitorAdapter<ImmutableNode> {
162        /** A stack for managing node builder instances. */
163        private final List<ImmutableNode.Builder> builderStack;
164
165        /** The resulting root node. */
166        private ImmutableNode interpolatedRoot;
167
168        /**
169         * Creates a new instance of {@code InterpolatedVisitor}.
170         */
171        public InterpolatedVisitor() {
172            builderStack = new LinkedList<>();
173        }
174
175        /**
176         * Gets the result of this builder: the root node of the interpolated nodes hierarchy.
177         *
178         * @return the resulting root node
179         */
180        public ImmutableNode getInterpolatedRoot() {
181            return interpolatedRoot;
182        }
183
184        /**
185         * Handles interpolation for a node with no children. If interpolation does not change this node, it is copied as is to
186         * the resulting structure. Otherwise, a new node is created with the interpolated values.
187         *
188         * @param node the current node to be processed
189         * @param handler the {@code NodeHandler}
190         */
191        private void handleLeafNode(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
192            final Object value = interpolate(node.getValue());
193            final Map<String, Object> interpolatedAttributes = new HashMap<>();
194            final boolean attributeChanged = interpolateAttributes(node, handler, interpolatedAttributes);
195            final ImmutableNode newNode = valueChanged(value, handler.getValue(node)) || attributeChanged
196                ? new ImmutableNode.Builder().name(handler.nodeName(node)).value(value).addAttributes(interpolatedAttributes).create()
197                : node;
198            storeInterpolatedNode(newNode);
199        }
200
201        /**
202         * Returns a map with interpolated attributes of the passed in node.
203         *
204         * @param node the current node to be processed
205         * @param handler the {@code NodeHandler}
206         * @return the map with interpolated attributes
207         */
208        private Map<String, Object> interpolateAttributes(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
209            final Map<String, Object> attributes = new HashMap<>();
210            interpolateAttributes(node, handler, attributes);
211            return attributes;
212        }
213
214        /**
215         * Populates a map with interpolated attributes of the passed in node.
216         *
217         * @param node the current node to be processed
218         * @param handler the {@code NodeHandler}
219         * @param interpolatedAttributes a map for storing the results
220         * @return a flag whether an attribute value was changed by interpolation
221         */
222        private boolean interpolateAttributes(final ImmutableNode node, final NodeHandler<ImmutableNode> handler,
223            final Map<String, Object> interpolatedAttributes) {
224            boolean attributeChanged = false;
225            for (final String attr : handler.getAttributes(node)) {
226                final Object attrValue = interpolate(handler.getAttributeValue(node, attr));
227                if (valueChanged(attrValue, handler.getAttributeValue(node, attr))) {
228                    attributeChanged = true;
229                }
230                interpolatedAttributes.put(attr, attrValue);
231            }
232            return attributeChanged;
233        }
234
235        /**
236         * Returns a flag whether the given node is a leaf. This is the case if it does not have children.
237         *
238         * @param node the node in question
239         * @param handler the {@code NodeHandler}
240         * @return a flag whether this is a leaf node
241         */
242        private boolean isLeafNode(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
243            return handler.getChildren(node).isEmpty();
244        }
245
246        /**
247         * Returns the top-level element from the stack without removing it.
248         *
249         * @return the top-level element from the stack
250         */
251        private ImmutableNode.Builder peek() {
252            return builderStack.get(0);
253        }
254
255        /**
256         * Pops the top-level element from the stack.
257         *
258         * @return the element popped from the stack
259         */
260        private ImmutableNode.Builder pop() {
261            return builderStack.remove(0);
262        }
263
264        /**
265         * Pushes a new builder on the stack.
266         *
267         * @param builder the builder
268         */
269        private void push(final ImmutableNode.Builder builder) {
270            builderStack.add(0, builder);
271        }
272
273        /**
274         * Stores a processed node. Per default, the node is added to the current builder on the stack. If no such builder
275         * exists, this is the result node.
276         *
277         * @param node the node to be stored
278         */
279        private void storeInterpolatedNode(final ImmutableNode node) {
280            if (builderStack.isEmpty()) {
281                interpolatedRoot = node;
282            } else {
283                peek().addChild(node);
284            }
285        }
286
287        /**
288         * Tests whether a value is changed because of interpolation.
289         *
290         * @param interpolatedValue the interpolated value
291         * @param value the original value
292         * @return a flag whether the value was changed
293         */
294        private boolean valueChanged(final Object interpolatedValue, final Object value) {
295            return ObjectUtils.notEqual(interpolatedValue, value);
296        }
297
298        @Override
299        public void visitAfterChildren(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
300            if (!isLeafNode(node, handler)) {
301                final ImmutableNode newNode = pop().create();
302                storeInterpolatedNode(newNode);
303            }
304        }
305
306        @Override
307        public void visitBeforeChildren(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) {
308            if (isLeafNode(node, handler)) {
309                handleLeafNode(node, handler);
310            } else {
311                final ImmutableNode.Builder builder = new ImmutableNode.Builder(handler.getChildrenCount(node, null)).name(handler.nodeName(node))
312                    .value(interpolate(handler.getValue(node))).addAttributes(interpolateAttributes(node, handler));
313                push(builder);
314            }
315        }
316    }
317
318    /**
319     * Creates the {@code NodeModel} for this configuration based on a passed in source configuration. This implementation
320     * creates an {@link InMemoryNodeModel}. If the passed in source configuration is defined, its root node also becomes
321     * the root node of this configuration. Otherwise, a new, empty root node is used.
322     *
323     * @param c the configuration that is to be copied
324     * @return the {@code NodeModel} for the new configuration
325     */
326    private static NodeModel<ImmutableNode> createNodeModel(final HierarchicalConfiguration<ImmutableNode> c) {
327        return new InMemoryNodeModel(obtainRootNode(c));
328    }
329
330    /**
331     * Obtains the root node from a configuration whose data is to be copied. It has to be ensured that the synchronizer is
332     * called correctly.
333     *
334     * @param c the configuration that is to be copied
335     * @return the root node of this configuration
336     */
337    private static ImmutableNode obtainRootNode(final HierarchicalConfiguration<ImmutableNode> c) {
338        return c != null ? c.getNodeModel().getNodeHandler().getRootNode() : null;
339    }
340
341    /**
342     * Creates a list with immutable configurations from the given input list.
343     *
344     * @param subs a list with mutable configurations
345     * @return a list with corresponding immutable configurations
346     */
347    private static List<ImmutableHierarchicalConfiguration> toImmutable(final List<? extends HierarchicalConfiguration<?>> subs) {
348        return subs.stream().map(ConfigurationUtils::unmodifiableConfiguration).collect(Collectors.toList());
349    }
350
351    /** A listener for reacting on changes caused by sub configurations. */
352    private final EventListener<ConfigurationEvent> changeListener;
353
354    /**
355     * Creates a new instance of {@code BaseHierarchicalConfiguration}.
356     */
357    public BaseHierarchicalConfiguration() {
358        this((HierarchicalConfiguration<ImmutableNode>) null);
359    }
360
361    /**
362     * Creates a new instance of {@code BaseHierarchicalConfiguration} and copies all data contained in the specified
363     * configuration into the new one.
364     *
365     * @param c the configuration that is to be copied (if <b>null</b>, this constructor will behave like the standard
366     *        constructor)
367     * @since 1.4
368     */
369    public BaseHierarchicalConfiguration(final HierarchicalConfiguration<ImmutableNode> c) {
370        this(createNodeModel(c));
371    }
372
373    /**
374     * Creates a new instance of {@code BaseHierarchicalConfiguration} and initializes it with the given {@code NodeModel}.
375     *
376     * @param model the {@code NodeModel}
377     */
378    protected BaseHierarchicalConfiguration(final NodeModel<ImmutableNode> model) {
379        super(model);
380        changeListener = createChangeListener();
381    }
382
383    /**
384     * {@inheritDoc} This implementation resolves the node(s) selected by the given key. If not a single node is selected,
385     * an empty list is returned. Otherwise, sub configurations for each child of the node are created.
386     */
387    @Override
388    public List<HierarchicalConfiguration<ImmutableNode>> childConfigurationsAt(final String key) {
389        List<ImmutableNode> nodes;
390        beginRead(false);
391        try {
392            nodes = fetchFilteredNodeResults(key);
393        } finally {
394            endRead();
395        }
396
397        if (nodes.size() != 1) {
398            return Collections.emptyList();
399        }
400
401        return nodes.get(0).stream().map(this::createIndependentSubConfigurationForNode).collect(Collectors.toList());
402    }
403
404    /**
405     * {@inheritDoc} This method works like {@link #childConfigurationsAt(String)}; however, depending on the value of the
406     * {@code supportUpdates} flag, connected sub configurations may be created.
407     */
408    @Override
409    public List<HierarchicalConfiguration<ImmutableNode>> childConfigurationsAt(final String key, final boolean supportUpdates) {
410        if (!supportUpdates) {
411            return childConfigurationsAt(key);
412        }
413
414        final InMemoryNodeModel parentModel = getSubConfigurationParentModel();
415        return createConnectedSubConfigurations(this, parentModel.trackChildNodes(key, this));
416    }
417
418    /**
419     * {@inheritDoc} This implementation creates a new instance of {@link InMemoryNodeModel}, initialized with this
420     * configuration's root node. This has the effect that although the same nodes are used, the original and copied
421     * configurations are independent on each other.
422     */
423    @Override
424    protected NodeModel<ImmutableNode> cloneNodeModel() {
425        return new InMemoryNodeModel(getModel().getNodeHandler().getRootNode());
426    }
427
428    /**
429     * {@inheritDoc} This is a short form for {@code configurationAt(key,
430     * <b>false</b>)}.
431     *
432     * @throws ConfigurationRuntimeException if the key does not select a single node
433     */
434    @Override
435    public HierarchicalConfiguration<ImmutableNode> configurationAt(final String key) {
436        return configurationAt(key, false);
437    }
438
439    /**
440     * {@inheritDoc} The result of this implementation depends on the {@code supportUpdates} flag: If it is <b>false</b>, a
441     * plain {@code BaseHierarchicalConfiguration} is returned using the selected node as root node. This is suitable for
442     * read-only access to properties. Because the configuration returned in this case is not connected to the parent
443     * configuration, updates on properties made by one configuration are not reflected by the other one. A value of
444     * <b>true</b> for this parameter causes a tracked node to be created, and result is a {@link SubnodeConfiguration}
445     * based on this tracked node. This configuration is really connected to its parent, so that updated properties are
446     * visible on both.
447     *
448     * @see SubnodeConfiguration
449     * @throws ConfigurationRuntimeException if the key does not select a single node
450     */
451    @Override
452    public HierarchicalConfiguration<ImmutableNode> configurationAt(final String key, final boolean supportUpdates) {
453        beginRead(false);
454        try {
455            return supportUpdates ? createConnectedSubConfiguration(key) : createIndependentSubConfiguration(key);
456        } finally {
457            endRead();
458        }
459    }
460
461    /**
462     * {@inheritDoc} This implementation creates sub configurations in the same way as described for
463     * {@link #configurationAt(String)}.
464     */
465    @Override
466    public List<HierarchicalConfiguration<ImmutableNode>> configurationsAt(final String key) {
467        List<ImmutableNode> nodes;
468        beginRead(false);
469        try {
470            nodes = fetchFilteredNodeResults(key);
471        } finally {
472            endRead();
473        }
474        return nodes.stream().map(this::createIndependentSubConfigurationForNode).collect(Collectors.toList());
475    }
476
477    /**
478     * {@inheritDoc} This implementation creates tracked nodes for the specified key. Then sub configurations for these
479     * nodes are created and returned.
480     */
481    @Override
482    public List<HierarchicalConfiguration<ImmutableNode>> configurationsAt(final String key, final boolean supportUpdates) {
483        if (!supportUpdates) {
484            return configurationsAt(key);
485        }
486
487        InMemoryNodeModel parentModel;
488        beginRead(false);
489        try {
490            parentModel = getSubConfigurationParentModel();
491        } finally {
492            endRead();
493        }
494
495        final Collection<NodeSelector> selectors = parentModel.selectAndTrackNodes(key, this);
496        return createConnectedSubConfigurations(this, selectors);
497    }
498
499    /**
500     * Creates a listener which reacts on all changes on this configuration or one of its {@code SubnodeConfiguration}
501     * instances. If such a change is detected, some updates have to be performed.
502     *
503     * @return the newly created change listener
504     */
505    private EventListener<ConfigurationEvent> createChangeListener() {
506        return this::subnodeConfigurationChanged;
507    }
508
509    /**
510     * Creates a sub configuration from the specified key which is connected to this configuration. This implementation
511     * creates a {@link SubnodeConfiguration} with a tracked node identified by the passed in key.
512     *
513     * @param key the key of the sub configuration
514     * @return the new sub configuration
515     */
516    private BaseHierarchicalConfiguration createConnectedSubConfiguration(final String key) {
517        final NodeSelector selector = getSubConfigurationNodeSelector(key);
518        getSubConfigurationParentModel().trackNode(selector, this);
519        return createSubConfigurationForTrackedNode(selector, this);
520    }
521
522    /**
523     * Creates a list of connected sub configurations based on a passed in list of node selectors.
524     *
525     * @param parentModelSupport the parent node model support object
526     * @param selectors the list of {@code NodeSelector} objects
527     * @return the list with sub configurations
528     */
529    private List<HierarchicalConfiguration<ImmutableNode>> createConnectedSubConfigurations(final InMemoryNodeModelSupport parentModelSupport,
530        final Collection<NodeSelector> selectors) {
531        return selectors.stream().map(sel -> createSubConfigurationForTrackedNode(sel, parentModelSupport)).collect(Collectors.toList());
532    }
533
534    /**
535     * Creates a sub configuration from the specified key which is independent on this configuration. This means that the
536     * sub configuration operates on a separate node model (although the nodes are initially shared).
537     *
538     * @param key the key of the sub configuration
539     * @return the new sub configuration
540     */
541    private BaseHierarchicalConfiguration createIndependentSubConfiguration(final String key) {
542        final List<ImmutableNode> targetNodes = fetchFilteredNodeResults(key);
543        final int size = targetNodes.size();
544        if (size != 1) {
545            throw new ConfigurationRuntimeException("Passed in key must select exactly one node (found %,d): %s", size, key);
546        }
547        final BaseHierarchicalConfiguration sub = new BaseHierarchicalConfiguration(new InMemoryNodeModel(targetNodes.get(0)));
548        initSubConfiguration(sub);
549        return sub;
550    }
551
552    /**
553     * Returns an initialized sub configuration for this configuration that is based on another
554     * {@code BaseHierarchicalConfiguration}. Thus, it is independent from this configuration.
555     *
556     * @param node the root node for the sub configuration
557     * @return the initialized sub configuration
558     */
559    private BaseHierarchicalConfiguration createIndependentSubConfigurationForNode(final ImmutableNode node) {
560        final BaseHierarchicalConfiguration sub = new BaseHierarchicalConfiguration(new InMemoryNodeModel(node));
561        initSubConfiguration(sub);
562        return sub;
563    }
564
565    /**
566     * Creates a connected sub configuration based on a selector for a tracked node.
567     *
568     * @param selector the {@code NodeSelector}
569     * @param parentModelSupport the {@code InMemoryNodeModelSupport} object for the parent node model
570     * @return the newly created sub configuration
571     * @since 2.0
572     */
573    protected SubnodeConfiguration createSubConfigurationForTrackedNode(final NodeSelector selector, final InMemoryNodeModelSupport parentModelSupport) {
574        final SubnodeConfiguration subConfig = new SubnodeConfiguration(this, new TrackedNodeModel(parentModelSupport, selector, true));
575        initSubConfigurationForThisParent(subConfig);
576        return subConfig;
577    }
578
579    /**
580     * Creates a root node for a subset configuration based on the passed in query results. This method creates a new root
581     * node and adds the children and attributes of all result nodes to it. If only a single node value is defined, it is
582     * assigned as value of the new root node.
583     *
584     * @param results the collection of query results
585     * @return the root node for the subset configuration
586     */
587    private ImmutableNode createSubsetRootNode(final Collection<QueryResult<ImmutableNode>> results) {
588        final ImmutableNode.Builder builder = new ImmutableNode.Builder();
589        Object value = null;
590        int valueCount = 0;
591
592        for (final QueryResult<ImmutableNode> result : results) {
593            if (result.isAttributeResult()) {
594                builder.addAttribute(result.getAttributeName(), result.getAttributeValue(getModel().getNodeHandler()));
595            } else {
596                if (result.getNode().getValue() != null) {
597                    value = result.getNode().getValue();
598                    valueCount++;
599                }
600                builder.addChildren(result.getNode().getChildren());
601                builder.addAttributes(result.getNode().getAttributes());
602            }
603        }
604
605        if (valueCount == 1) {
606            builder.value(value);
607        }
608        return builder.create();
609    }
610
611    /**
612     * Executes a query on the specified key and filters it for node results.
613     *
614     * @param key the key
615     * @return the filtered list with result nodes
616     */
617    private List<ImmutableNode> fetchFilteredNodeResults(final String key) {
618        final NodeHandler<ImmutableNode> handler = getModel().getNodeHandler();
619        return resolveNodeKey(handler.getRootNode(), key, handler);
620    }
621
622    /**
623     * {@inheritDoc} This implementation returns the {@code InMemoryNodeModel} used by this configuration.
624     */
625    @Override
626    public InMemoryNodeModel getNodeModel() {
627        return (InMemoryNodeModel) super.getNodeModel();
628    }
629
630    /**
631     * Gets the {@code NodeSelector} to be used for a sub configuration based on the passed in key. This method is called
632     * whenever a sub configuration is to be created. This base implementation returns a new {@code NodeSelector}
633     * initialized with the passed in key. Sub classes may override this method if they have a different strategy for
634     * creating a selector.
635     *
636     * @param key the key of the sub configuration
637     * @return a {@code NodeSelector} for initializing a sub configuration
638     * @since 2.0
639     */
640    protected NodeSelector getSubConfigurationNodeSelector(final String key) {
641        return new NodeSelector(key);
642    }
643
644    /**
645     * Gets the {@code InMemoryNodeModel} to be used as parent model for a new sub configuration. This method is called
646     * whenever a sub configuration is to be created. This base implementation returns the model of this configuration. Sub
647     * classes with different requirements for the parent models of sub configurations have to override it.
648     *
649     * @return the parent model for a new sub configuration
650     */
651    protected InMemoryNodeModel getSubConfigurationParentModel() {
652        return (InMemoryNodeModel) getModel();
653    }
654
655    /**
656     * {@inheritDoc} This implementation first delegates to {@code childConfigurationsAt()} to create a list of mutable
657     * child configurations. Then a list with immutable wrapper configurations is created.
658     */
659    @Override
660    public List<ImmutableHierarchicalConfiguration> immutableChildConfigurationsAt(final String key) {
661        return toImmutable(childConfigurationsAt(key));
662    }
663
664    /**
665     * {@inheritDoc} This implementation creates a {@code SubnodeConfiguration} by delegating to {@code configurationAt()}.
666     * Then an immutable wrapper is created and returned.
667     *
668     * @throws ConfigurationRuntimeException if the key does not select a single node
669     */
670    @Override
671    public ImmutableHierarchicalConfiguration immutableConfigurationAt(final String key) {
672        return ConfigurationUtils.unmodifiableConfiguration(configurationAt(key));
673    }
674
675    /**
676     * {@inheritDoc} This implementation creates a {@code SubnodeConfiguration} by delegating to {@code configurationAt()}.
677     * Then an immutable wrapper is created and returned.
678     */
679    @Override
680    public ImmutableHierarchicalConfiguration immutableConfigurationAt(final String key, final boolean supportUpdates) {
681        return ConfigurationUtils.unmodifiableConfiguration(configurationAt(key, supportUpdates));
682    }
683
684    /**
685     * {@inheritDoc} This implementation first delegates to {@code configurationsAt()} to create a list of
686     * {@code SubnodeConfiguration} objects. Then for each element of this list an unmodifiable wrapper is created.
687     */
688    @Override
689    public List<ImmutableHierarchicalConfiguration> immutableConfigurationsAt(final String key) {
690        return toImmutable(configurationsAt(key));
691    }
692
693    /**
694     * Initializes properties of a sub configuration. A sub configuration inherits some settings from its parent, e.g. the
695     * expression engine or the synchronizer. The corresponding values are copied by this method.
696     *
697     * @param sub the sub configuration to be initialized
698     */
699    private void initSubConfiguration(final BaseHierarchicalConfiguration sub) {
700        sub.setSynchronizer(getSynchronizer());
701        sub.setExpressionEngine(getExpressionEngine());
702        sub.setListDelimiterHandler(getListDelimiterHandler());
703        sub.setThrowExceptionOnMissing(isThrowExceptionOnMissing());
704        sub.getInterpolator().setParentInterpolator(getInterpolator());
705    }
706
707    /**
708     * Initializes a {@code SubnodeConfiguration} object. This method should be called for each sub configuration created
709     * for this configuration. It ensures that the sub configuration is correctly connected to its parent instance and that
710     * update events are correctly propagated.
711     *
712     * @param subConfig the sub configuration to be initialized
713     * @since 2.0
714     */
715    protected void initSubConfigurationForThisParent(final SubnodeConfiguration subConfig) {
716        initSubConfiguration(subConfig);
717        subConfig.addEventListener(ConfigurationEvent.ANY, changeListener);
718    }
719
720    /**
721     * Returns a configuration with the same content as this configuration, but with all variables replaced by their actual
722     * values. This implementation is specific for hierarchical configurations. It clones the current configuration and runs
723     * a specialized visitor on the clone, which performs interpolation on the single configuration nodes.
724     *
725     * @return a configuration with all variables interpolated
726     * @since 1.5
727     */
728    @Override
729    public Configuration interpolatedConfiguration() {
730        final InterpolatedVisitor visitor = new InterpolatedVisitor();
731        final NodeHandler<ImmutableNode> handler = getModel().getNodeHandler();
732        NodeTreeWalker.INSTANCE.walkDFS(handler.getRootNode(), visitor, handler);
733
734        final BaseHierarchicalConfiguration c = (BaseHierarchicalConfiguration) clone();
735        c.getNodeModel().setRootNode(visitor.getInterpolatedRoot());
736        return c;
737    }
738
739    /**
740     * This method is always called when a subnode configuration created from this configuration has been modified. This
741     * implementation transforms the received event into an event of type {@code SUBNODE_CHANGED} and notifies the
742     * registered listeners.
743     *
744     * @param event the event describing the change
745     * @since 1.5
746     */
747    protected void subnodeConfigurationChanged(final ConfigurationEvent event) {
748        fireEvent(ConfigurationEvent.SUBNODE_CHANGED, null, event, event.isBeforeUpdate());
749    }
750
751    /**
752     * Creates a new {@code Configuration} object containing all keys that start with the specified prefix. This
753     * implementation will return a {@code BaseHierarchicalConfiguration} object so that the structure of the keys will be
754     * saved. The nodes selected by the prefix (it is possible that multiple nodes are selected) are mapped to the root node
755     * of the returned configuration, i.e. their children and attributes will become children and attributes of the new root
756     * node. However, a value of the root node is only set if exactly one of the selected nodes contain a value (if multiple
757     * nodes have a value, there is simply no way to decide how these values are merged together). Note that the returned
758     * {@code Configuration} object is not connected to its source configuration: updates on the source configuration are
759     * not reflected in the subset and vice versa. The returned configuration uses the same {@code Synchronizer} as this
760     * configuration.
761     *
762     * @param prefix the prefix of the keys for the subset
763     * @return a new configuration object representing the selected subset
764     */
765    @Override
766    public Configuration subset(final String prefix) {
767        beginRead(false);
768        try {
769            final List<QueryResult<ImmutableNode>> results = fetchNodeList(prefix);
770            if (results.isEmpty()) {
771                return new BaseHierarchicalConfiguration();
772            }
773
774            final BaseHierarchicalConfiguration parent = this;
775            final BaseHierarchicalConfiguration result = new BaseHierarchicalConfiguration() {
776                @Override
777                public ConfigurationInterpolator getInterpolator() {
778                    return parent.getInterpolator();
779                }
780
781                // Override interpolate to always interpolate on the parent
782                @Override
783                protected Object interpolate(final Object value) {
784                    return parent.interpolate(value);
785                }
786            };
787            result.getModel().setRootNode(createSubsetRootNode(results));
788
789            if (result.isEmpty()) {
790                return new BaseHierarchicalConfiguration();
791            }
792            result.setSynchronizer(getSynchronizer());
793            return result;
794        } finally {
795            endRead();
796        }
797    }
798}