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