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