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 new EventListener<ConfigurationEvent>()
623        {
624            @Override
625            public void onEvent(final ConfigurationEvent event)
626            {
627                subnodeConfigurationChanged(event);
628            }
629        };
630    }
631
632    /**
633     * Returns a configuration with the same content as this configuration, but
634     * with all variables replaced by their actual values. This implementation
635     * is specific for hierarchical configurations. It clones the current
636     * configuration and runs a specialized visitor on the clone, which performs
637     * interpolation on the single configuration nodes.
638     *
639     * @return a configuration with all variables interpolated
640     * @since 1.5
641     */
642    @Override
643    public Configuration interpolatedConfiguration()
644    {
645        final InterpolatedVisitor visitor = new InterpolatedVisitor();
646        final NodeHandler<ImmutableNode> handler = getModel().getNodeHandler();
647        NodeTreeWalker.INSTANCE
648                .walkDFS(handler.getRootNode(), visitor, handler);
649
650        final BaseHierarchicalConfiguration c =
651                (BaseHierarchicalConfiguration) clone();
652        c.getNodeModel().setRootNode(visitor.getInterpolatedRoot());
653        return c;
654    }
655
656    /**
657     * {@inheritDoc} This implementation creates a new instance of
658     * {@link InMemoryNodeModel}, initialized with this configuration's root
659     * node. This has the effect that although the same nodes are used, the
660     * original and copied configurations are independent on each other.
661     */
662    @Override
663    protected NodeModel<ImmutableNode> cloneNodeModel()
664    {
665        return new InMemoryNodeModel(getModel().getNodeHandler().getRootNode());
666    }
667
668    /**
669     * Creates a list with immutable configurations from the given input list.
670     *
671     * @param subs a list with mutable configurations
672     * @return a list with corresponding immutable configurations
673     */
674    private static List<ImmutableHierarchicalConfiguration> toImmutable(
675            final List<? extends HierarchicalConfiguration<?>> subs)
676    {
677        final List<ImmutableHierarchicalConfiguration> res =
678                new ArrayList<>(subs.size());
679        for (final HierarchicalConfiguration<?> sub : subs)
680        {
681            res.add(ConfigurationUtils.unmodifiableConfiguration(sub));
682        }
683        return res;
684    }
685
686    /**
687     * Creates the {@code NodeModel} for this configuration based on a passed in
688     * source configuration. This implementation creates an
689     * {@link InMemoryNodeModel}. If the passed in source configuration is
690     * defined, its root node also becomes the root node of this configuration.
691     * Otherwise, a new, empty root node is used.
692     *
693     * @param c the configuration that is to be copied
694     * @return the {@code NodeModel} for the new configuration
695     */
696    private static NodeModel<ImmutableNode> createNodeModel(
697            final HierarchicalConfiguration<ImmutableNode> c)
698    {
699        final ImmutableNode root = (c != null) ? obtainRootNode(c) : null;
700        return new InMemoryNodeModel(root);
701    }
702
703    /**
704     * Obtains the root node from a configuration whose data is to be copied. It
705     * has to be ensured that the synchronizer is called correctly.
706     *
707     * @param c the configuration that is to be copied
708     * @return the root node of this configuration
709     */
710    private static ImmutableNode obtainRootNode(
711            final HierarchicalConfiguration<ImmutableNode> c)
712    {
713        return c.getNodeModel().getNodeHandler().getRootNode();
714    }
715
716    /**
717     * A specialized visitor base class that can be used for storing the tree of
718     * configuration nodes. The basic idea is that each node can be associated
719     * with a reference object. This reference object has a concrete meaning in
720     * a derived class, e.g. an entry in a JNDI context or an XML element. When
721     * the configuration tree is set up, the {@code load()} method is
722     * responsible for setting the reference objects. When the configuration
723     * tree is later modified, new nodes do not have a defined reference object.
724     * This visitor class processes all nodes and finds the ones without a
725     * defined reference object. For those nodes the {@code insert()}
726     * method is called, which must be defined in concrete sub classes. This
727     * method can perform all steps to integrate the new node into the original
728     * structure.
729     */
730    protected abstract static class BuilderVisitor extends
731            ConfigurationNodeVisitorAdapter<ImmutableNode>
732    {
733        @Override
734        public void visitBeforeChildren(final ImmutableNode node, final NodeHandler<ImmutableNode> handler)
735        {
736            final ReferenceNodeHandler refHandler = (ReferenceNodeHandler) handler;
737            updateNode(node, refHandler);
738            insertNewChildNodes(node, refHandler);
739        }
740
741        /**
742         * Inserts a new node into the structure constructed by this builder.
743         * This method is called for each node that has been added to the
744         * configuration tree after the configuration has been loaded from its
745         * source. These new nodes have to be inserted into the original
746         * structure. The passed in nodes define the position of the node to be
747         * inserted: its parent and the siblings between to insert.
748         *
749         * @param newNode the node to be inserted
750         * @param parent the parent node
751         * @param sibling1 the sibling after which the node is to be inserted;
752         *        can be <b>null</b> if the new node is going to be the first
753         *        child node
754         * @param sibling2 the sibling before which the node is to be inserted;
755         *        can be <b>null</b> if the new node is going to be the last
756         *        child node
757         * @param refHandler the {@code ReferenceNodeHandler}
758         */
759        protected abstract void insert(ImmutableNode newNode,
760                ImmutableNode parent, ImmutableNode sibling1,
761                ImmutableNode sibling2, ReferenceNodeHandler refHandler);
762
763        /**
764         * Updates a node that already existed in the original hierarchy. This
765         * method is called for each node that has an assigned reference object.
766         * A concrete implementation should update the reference according to
767         * the node's current value.
768         *
769         * @param node the current node to be processed
770         * @param reference the reference object for this node
771         * @param refHandler the {@code ReferenceNodeHandler}
772         */
773        protected abstract void update(ImmutableNode node, Object reference,
774                ReferenceNodeHandler refHandler);
775
776        /**
777         * Updates the value of a node. If this node is associated with a
778         * reference object, the {@code update()} method is called.
779         *
780         * @param node the current node to be processed
781         * @param refHandler the {@code ReferenceNodeHandler}
782         */
783        private void updateNode(final ImmutableNode node,
784                final ReferenceNodeHandler refHandler)
785        {
786            final Object reference = refHandler.getReference(node);
787            if (reference != null)
788            {
789                update(node, reference, refHandler);
790            }
791        }
792
793        /**
794         * Inserts new children that have been added to the specified node.
795         *
796         * @param node the current node to be processed
797         * @param refHandler the {@code ReferenceNodeHandler}
798         */
799        private void insertNewChildNodes(final ImmutableNode node,
800                final ReferenceNodeHandler refHandler)
801        {
802            final Collection<ImmutableNode> subNodes =
803                    new LinkedList<>(refHandler.getChildren(node));
804            final Iterator<ImmutableNode> children = subNodes.iterator();
805            ImmutableNode sibling1;
806            ImmutableNode nd = null;
807
808            while (children.hasNext())
809            {
810                // find the next new node
811                do
812                {
813                    sibling1 = nd;
814                    nd = children.next();
815                } while (refHandler.getReference(nd) != null
816                        && children.hasNext());
817
818                if (refHandler.getReference(nd) == null)
819                {
820                    // find all following new nodes
821                    final List<ImmutableNode> newNodes =
822                            new LinkedList<>();
823                    newNodes.add(nd);
824                    while (children.hasNext())
825                    {
826                        nd = children.next();
827                        if (refHandler.getReference(nd) == null)
828                        {
829                            newNodes.add(nd);
830                        }
831                        else
832                        {
833                            break;
834                        }
835                    }
836
837                    // Insert all new nodes
838                    final ImmutableNode sibling2 =
839                            (refHandler.getReference(nd) == null) ? null : nd;
840                    for (final ImmutableNode insertNode : newNodes)
841                    {
842                        if (refHandler.getReference(insertNode) == null)
843                        {
844                            insert(insertNode, node, sibling1, sibling2,
845                                    refHandler);
846                            sibling1 = insertNode;
847                        }
848                    }
849                }
850            }
851        }
852    }
853
854    /**
855     * A specialized visitor implementation which constructs the root node of a
856     * configuration with all variables replaced by their interpolated values.
857     */
858    private class InterpolatedVisitor extends
859            ConfigurationNodeVisitorAdapter<ImmutableNode>
860    {
861        /** A stack for managing node builder instances. */
862        private final List<ImmutableNode.Builder> builderStack;
863
864        /** The resulting root node. */
865        private ImmutableNode interpolatedRoot;
866
867        /**
868         * Creates a new instance of {@code InterpolatedVisitor}.
869         */
870        public InterpolatedVisitor()
871        {
872            builderStack = new LinkedList<>();
873        }
874
875        /**
876         * Returns the result of this builder: the root node of the interpolated
877         * nodes hierarchy.
878         *
879         * @return the resulting root node
880         */
881        public ImmutableNode getInterpolatedRoot()
882        {
883            return interpolatedRoot;
884        }
885
886        @Override
887        public void visitBeforeChildren(final ImmutableNode node,
888                final NodeHandler<ImmutableNode> handler)
889        {
890            if (isLeafNode(node, handler))
891            {
892                handleLeafNode(node, handler);
893            }
894            else
895            {
896                final ImmutableNode.Builder builder =
897                        new ImmutableNode.Builder(handler.getChildrenCount(
898                                node, null))
899                                .name(handler.nodeName(node))
900                                .value(interpolate(handler.getValue(node)))
901                                .addAttributes(
902                                        interpolateAttributes(node, handler));
903                push(builder);
904            }
905        }
906
907        @Override
908        public void visitAfterChildren(final ImmutableNode node,
909                final NodeHandler<ImmutableNode> handler)
910        {
911            if (!isLeafNode(node, handler))
912            {
913                final ImmutableNode newNode = pop().create();
914                storeInterpolatedNode(newNode);
915            }
916        }
917
918        /**
919         * Pushes a new builder on the stack.
920         *
921         * @param builder the builder
922         */
923        private void push(final ImmutableNode.Builder builder)
924        {
925            builderStack.add(0, builder);
926        }
927
928        /**
929         * Pops the top-level element from the stack.
930         *
931         * @return the element popped from the stack
932         */
933        private ImmutableNode.Builder pop()
934        {
935            return builderStack.remove(0);
936        }
937
938        /**
939         * Returns the top-level element from the stack without removing it.
940         *
941         * @return the top-level element from the stack
942         */
943        private ImmutableNode.Builder peek()
944        {
945            return builderStack.get(0);
946        }
947
948        /**
949         * Returns a flag whether the given node is a leaf. This is the case if
950         * it does not have children.
951         *
952         * @param node the node in question
953         * @param handler the {@code NodeHandler}
954         * @return a flag whether this is a leaf node
955         */
956        private boolean isLeafNode(final ImmutableNode node,
957                final NodeHandler<ImmutableNode> handler)
958        {
959            return handler.getChildren(node).isEmpty();
960        }
961
962        /**
963         * Handles interpolation for a node with no children. If interpolation
964         * does not change this node, it is copied as is to the resulting
965         * structure. Otherwise, a new node is created with the interpolated
966         * values.
967         *
968         * @param node the current node to be processed
969         * @param handler the {@code NodeHandler}
970         */
971        private void handleLeafNode(final ImmutableNode node,
972                final NodeHandler<ImmutableNode> handler)
973        {
974            final Object value = interpolate(node.getValue());
975            final Map<String, Object> interpolatedAttributes =
976                    new HashMap<>();
977            final boolean attributeChanged =
978                    interpolateAttributes(node, handler, interpolatedAttributes);
979            final ImmutableNode newNode =
980                    (valueChanged(value, handler.getValue(node)) || attributeChanged) ? new ImmutableNode.Builder()
981                            .name(handler.nodeName(node)).value(value)
982                            .addAttributes(interpolatedAttributes).create()
983                            : node;
984            storeInterpolatedNode(newNode);
985        }
986
987        /**
988         * Stores a processed node. Per default, the node is added to the
989         * current builder on the stack. If no such builder exists, this is the
990         * result node.
991         *
992         * @param node the node to be stored
993         */
994        private void storeInterpolatedNode(final ImmutableNode node)
995        {
996            if (builderStack.isEmpty())
997            {
998                interpolatedRoot = node;
999            }
1000            else
1001            {
1002                peek().addChild(node);
1003            }
1004        }
1005
1006        /**
1007         * Populates a map with interpolated attributes of the passed in node.
1008         *
1009         * @param node the current node to be processed
1010         * @param handler the {@code NodeHandler}
1011         * @param interpolatedAttributes a map for storing the results
1012         * @return a flag whether an attribute value was changed by
1013         *         interpolation
1014         */
1015        private boolean interpolateAttributes(final ImmutableNode node,
1016                final NodeHandler<ImmutableNode> handler,
1017                final Map<String, Object> interpolatedAttributes)
1018        {
1019            boolean attributeChanged = false;
1020            for (final String attr : handler.getAttributes(node))
1021            {
1022                final Object attrValue =
1023                        interpolate(handler.getAttributeValue(node, attr));
1024                if (valueChanged(attrValue,
1025                        handler.getAttributeValue(node, attr)))
1026                {
1027                    attributeChanged = true;
1028                }
1029                interpolatedAttributes.put(attr, attrValue);
1030            }
1031            return attributeChanged;
1032        }
1033
1034        /**
1035         * Returns a map with interpolated attributes of the passed in node.
1036         *
1037         * @param node the current node to be processed
1038         * @param handler the {@code NodeHandler}
1039         * @return the map with interpolated attributes
1040         */
1041        private Map<String, Object> interpolateAttributes(final ImmutableNode node,
1042                final NodeHandler<ImmutableNode> handler)
1043        {
1044            final Map<String, Object> attributes = new HashMap<>();
1045            interpolateAttributes(node, handler, attributes);
1046            return attributes;
1047        }
1048
1049        /**
1050         * Tests whether a value is changed because of interpolation.
1051         *
1052         * @param interpolatedValue the interpolated value
1053         * @param value the original value
1054         * @return a flag whether the value was changed
1055         */
1056        private boolean valueChanged(final Object interpolatedValue, final Object value)
1057        {
1058            return ObjectUtils.notEqual(interpolatedValue, value);
1059        }
1060    }
1061}