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