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