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 171 /** A stack for managing node builder instances. */ 172 private final List<ImmutableNode.Builder> builderStack; 173 174 /** The resulting root node. */ 175 private ImmutableNode interpolatedRoot; 176 177 /** 178 * Creates a new instance of {@code InterpolatedVisitor}. 179 */ 180 public InterpolatedVisitor() { 181 builderStack = new LinkedList<>(); 182 } 183 184 /** 185 * Gets the result of this builder: the root node of the interpolated nodes hierarchy. 186 * 187 * @return the resulting root node 188 */ 189 public ImmutableNode getInterpolatedRoot() { 190 return interpolatedRoot; 191 } 192 193 /** 194 * Handles interpolation for a node with no children. If interpolation does not change this node, it is copied as is to 195 * the resulting structure. Otherwise, a new node is created with the interpolated values. 196 * 197 * @param node the current node to be processed 198 * @param handler the {@code NodeHandler} 199 */ 200 private void handleLeafNode(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) { 201 final Object value = interpolate(node.getValue()); 202 final Map<String, Object> interpolatedAttributes = new HashMap<>(); 203 final boolean attributeChanged = interpolateAttributes(node, handler, interpolatedAttributes); 204 final ImmutableNode newNode = valueChanged(value, handler.getValue(node)) || attributeChanged 205 ? new ImmutableNode.Builder().name(handler.nodeName(node)).value(value).addAttributes(interpolatedAttributes).create() 206 : node; 207 storeInterpolatedNode(newNode); 208 } 209 210 /** 211 * Returns a map with interpolated attributes of the passed in node. 212 * 213 * @param node the current node to be processed 214 * @param handler the {@code NodeHandler} 215 * @return the map with interpolated attributes 216 */ 217 private Map<String, Object> interpolateAttributes(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) { 218 final Map<String, Object> attributes = new HashMap<>(); 219 interpolateAttributes(node, handler, attributes); 220 return attributes; 221 } 222 223 /** 224 * Populates a map with interpolated attributes of the passed in node. 225 * 226 * @param node the current node to be processed 227 * @param handler the {@code NodeHandler} 228 * @param interpolatedAttributes a map for storing the results 229 * @return a flag whether an attribute value was changed by interpolation 230 */ 231 private boolean interpolateAttributes(final ImmutableNode node, final NodeHandler<ImmutableNode> handler, 232 final Map<String, Object> interpolatedAttributes) { 233 boolean attributeChanged = false; 234 for (final String attr : handler.getAttributes(node)) { 235 final Object attrValue = interpolate(handler.getAttributeValue(node, attr)); 236 if (valueChanged(attrValue, handler.getAttributeValue(node, attr))) { 237 attributeChanged = true; 238 } 239 interpolatedAttributes.put(attr, attrValue); 240 } 241 return attributeChanged; 242 } 243 244 /** 245 * Returns a flag whether the given node is a leaf. This is the case if it does not have children. 246 * 247 * @param node the node in question 248 * @param handler the {@code NodeHandler} 249 * @return a flag whether this is a leaf node 250 */ 251 private boolean isLeafNode(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) { 252 return handler.getChildren(node).isEmpty(); 253 } 254 255 /** 256 * Returns the top-level element from the stack without removing it. 257 * 258 * @return the top-level element from the stack 259 */ 260 private ImmutableNode.Builder peek() { 261 return builderStack.get(0); 262 } 263 264 /** 265 * Pops the top-level element from the stack. 266 * 267 * @return the element popped from the stack 268 */ 269 private ImmutableNode.Builder pop() { 270 return builderStack.remove(0); 271 } 272 273 /** 274 * Pushes a new builder on the stack. 275 * 276 * @param builder the builder 277 */ 278 private void push(final ImmutableNode.Builder builder) { 279 builderStack.add(0, builder); 280 } 281 282 /** 283 * Stores a processed node. Per default, the node is added to the current builder on the stack. If no such builder 284 * exists, this is the result node. 285 * 286 * @param node the node to be stored 287 */ 288 private void storeInterpolatedNode(final ImmutableNode node) { 289 if (builderStack.isEmpty()) { 290 interpolatedRoot = node; 291 } else { 292 peek().addChild(node); 293 } 294 } 295 296 /** 297 * Tests whether a value is changed because of interpolation. 298 * 299 * @param interpolatedValue the interpolated value 300 * @param value the original value 301 * @return a flag whether the value was changed 302 */ 303 private boolean valueChanged(final Object interpolatedValue, final Object value) { 304 return ObjectUtils.notEqual(interpolatedValue, value); 305 } 306 307 @Override 308 public void visitAfterChildren(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) { 309 if (!isLeafNode(node, handler)) { 310 final ImmutableNode newNode = pop().create(); 311 storeInterpolatedNode(newNode); 312 } 313 } 314 315 @Override 316 public void visitBeforeChildren(final ImmutableNode node, final NodeHandler<ImmutableNode> handler) { 317 if (isLeafNode(node, handler)) { 318 handleLeafNode(node, handler); 319 } else { 320 final ImmutableNode.Builder builder = new ImmutableNode.Builder(handler.getChildrenCount(node, null)).name(handler.nodeName(node)) 321 .value(interpolate(handler.getValue(node))).addAttributes(interpolateAttributes(node, handler)); 322 push(builder); 323 } 324 } 325 } 326 327 /** 328 * Creates the {@code NodeModel} for this configuration based on a passed in source configuration. This implementation 329 * creates an {@link InMemoryNodeModel}. If the passed in source configuration is defined, its root node also becomes 330 * the root node of this configuration. Otherwise, a new, empty root node is used. 331 * 332 * @param c the configuration that is to be copied 333 * @return the {@code NodeModel} for the new configuration 334 */ 335 private static NodeModel<ImmutableNode> createNodeModel(final HierarchicalConfiguration<ImmutableNode> c) { 336 return new InMemoryNodeModel(obtainRootNode(c)); 337 } 338 339 /** 340 * Obtains the root node from a configuration whose data is to be copied. It has to be ensured that the synchronizer is 341 * called correctly. 342 * 343 * @param c the configuration that is to be copied 344 * @return the root node of this configuration 345 */ 346 private static ImmutableNode obtainRootNode(final HierarchicalConfiguration<ImmutableNode> c) { 347 return c != null ? c.getNodeModel().getNodeHandler().getRootNode() : null; 348 } 349 350 /** 351 * Creates a list with immutable configurations from the given input list. 352 * 353 * @param subs a list with mutable configurations 354 * @return a list with corresponding immutable configurations 355 */ 356 private static List<ImmutableHierarchicalConfiguration> toImmutable(final List<? extends HierarchicalConfiguration<?>> subs) { 357 return subs.stream().map(ConfigurationUtils::unmodifiableConfiguration).collect(Collectors.toList()); 358 } 359 360 /** A listener for reacting on changes caused by sub configurations. */ 361 private final EventListener<ConfigurationEvent> changeListener; 362 363 /** 364 * Creates a new instance of {@code BaseHierarchicalConfiguration}. 365 */ 366 public BaseHierarchicalConfiguration() { 367 this((HierarchicalConfiguration<ImmutableNode>) null); 368 } 369 370 /** 371 * Creates a new instance of {@code BaseHierarchicalConfiguration} and copies all data contained in the specified 372 * configuration into the new one. 373 * 374 * @param c the configuration that is to be copied (if <strong>null</strong>, this constructor will behave like the standard 375 * constructor) 376 * @since 1.4 377 */ 378 public BaseHierarchicalConfiguration(final HierarchicalConfiguration<ImmutableNode> c) { 379 this(createNodeModel(c)); 380 } 381 382 /** 383 * Creates a new instance of {@code BaseHierarchicalConfiguration} and initializes it with the given {@code NodeModel}. 384 * 385 * @param model the {@code NodeModel} 386 */ 387 protected BaseHierarchicalConfiguration(final NodeModel<ImmutableNode> model) { 388 super(model); 389 changeListener = createChangeListener(); 390 } 391 392 /** 393 * {@inheritDoc} This implementation resolves the node(s) selected by the given key. If not a single node is selected, 394 * an empty list is returned. Otherwise, sub configurations for each child of the node are created. 395 */ 396 @Override 397 public List<HierarchicalConfiguration<ImmutableNode>> childConfigurationsAt(final String key) { 398 final List<ImmutableNode> nodes = syncRead(() -> fetchFilteredNodeResults(key), false); 399 if (nodes.size() != 1) { 400 return Collections.emptyList(); 401 } 402 return nodes.get(0).stream().map(this::createIndependentSubConfigurationForNode).collect(Collectors.toList()); 403 } 404 405 /** 406 * {@inheritDoc} This method works like {@link #childConfigurationsAt(String)}; however, depending on the value of the 407 * {@code supportUpdates} flag, connected sub configurations may be created. 408 */ 409 @Override 410 public List<HierarchicalConfiguration<ImmutableNode>> childConfigurationsAt(final String key, final boolean supportUpdates) { 411 if (!supportUpdates) { 412 return childConfigurationsAt(key); 413 } 414 415 final InMemoryNodeModel parentModel = getSubConfigurationParentModel(); 416 return createConnectedSubConfigurations(this, parentModel.trackChildNodes(key, this)); 417 } 418 419 /** 420 * {@inheritDoc} This implementation creates a new instance of {@link InMemoryNodeModel}, initialized with this 421 * configuration's root node. This has the effect that although the same nodes are used, the original and copied 422 * configurations are independent on each other. 423 */ 424 @Override 425 protected NodeModel<ImmutableNode> cloneNodeModel() { 426 return new InMemoryNodeModel(getModel().getNodeHandler().getRootNode()); 427 } 428 429 /** 430 * {@inheritDoc} This is a short form for {@code configurationAt(key, 431 * <strong>false</strong>)}. 432 * 433 * @throws ConfigurationRuntimeException if the key does not select a single node 434 */ 435 @Override 436 public HierarchicalConfiguration<ImmutableNode> configurationAt(final String key) { 437 return configurationAt(key, false); 438 } 439 440 /** 441 * {@inheritDoc} The result of this implementation depends on the {@code supportUpdates} flag: If it is <strong>false</strong>, a 442 * plain {@code BaseHierarchicalConfiguration} is returned using the selected node as root node. This is suitable for 443 * read-only access to properties. Because the configuration returned in this case is not connected to the parent 444 * configuration, updates on properties made by one configuration are not reflected by the other one. A value of 445 * <strong>true</strong> for this parameter causes a tracked node to be created, and result is a {@link SubnodeConfiguration} 446 * based on this tracked node. This configuration is really connected to its parent, so that updated properties are 447 * visible on both. 448 * 449 * @see SubnodeConfiguration 450 * @throws ConfigurationRuntimeException if the key does not select a single node 451 */ 452 @Override 453 public HierarchicalConfiguration<ImmutableNode> configurationAt(final String key, final boolean supportUpdates) { 454 return syncRead(() -> supportUpdates ? createConnectedSubConfiguration(key) : createIndependentSubConfiguration(key), false); 455 } 456 457 /** 458 * {@inheritDoc} This implementation creates sub configurations in the same way as described for 459 * {@link #configurationAt(String)}. 460 */ 461 @Override 462 public List<HierarchicalConfiguration<ImmutableNode>> configurationsAt(final String key) { 463 final List<ImmutableNode> nodes = syncRead(() -> fetchFilteredNodeResults(key), false); 464 return nodes.stream().map(this::createIndependentSubConfigurationForNode).collect(Collectors.toList()); 465 } 466 467 /** 468 * {@inheritDoc} This implementation creates tracked nodes for the specified key. Then sub configurations for these 469 * nodes are created and returned. 470 */ 471 @Override 472 public List<HierarchicalConfiguration<ImmutableNode>> configurationsAt(final String key, final boolean supportUpdates) { 473 if (!supportUpdates) { 474 return configurationsAt(key); 475 } 476 final InMemoryNodeModel parentModel = syncRead(this::getSubConfigurationParentModel, false); 477 return createConnectedSubConfigurations(this, parentModel.selectAndTrackNodes(key, this)); 478 } 479 480 /** 481 * Creates a listener which reacts on all changes on this configuration or one of its {@code SubnodeConfiguration} 482 * instances. If such a change is detected, some updates have to be performed. 483 * 484 * @return the newly created change listener 485 */ 486 private EventListener<ConfigurationEvent> createChangeListener() { 487 return this::subnodeConfigurationChanged; 488 } 489 490 /** 491 * Creates a sub configuration from the specified key which is connected to this configuration. This implementation 492 * creates a {@link SubnodeConfiguration} with a tracked node identified by the passed in key. 493 * 494 * @param key the key of the sub configuration 495 * @return the new sub configuration 496 */ 497 private BaseHierarchicalConfiguration createConnectedSubConfiguration(final String key) { 498 final NodeSelector selector = getSubConfigurationNodeSelector(key); 499 getSubConfigurationParentModel().trackNode(selector, this); 500 return createSubConfigurationForTrackedNode(selector, this); 501 } 502 503 /** 504 * Creates a list of connected sub configurations based on a passed in list of node selectors. 505 * 506 * @param parentModelSupport the parent node model support object 507 * @param selectors the list of {@code NodeSelector} objects 508 * @return the list with sub configurations 509 */ 510 private List<HierarchicalConfiguration<ImmutableNode>> createConnectedSubConfigurations(final InMemoryNodeModelSupport parentModelSupport, 511 final Collection<NodeSelector> selectors) { 512 return selectors.stream().map(sel -> createSubConfigurationForTrackedNode(sel, parentModelSupport)).collect(Collectors.toList()); 513 } 514 515 /** 516 * Creates a sub configuration from the specified key which is independent on this configuration. This means that the 517 * sub configuration operates on a separate node model (although the nodes are initially shared). 518 * 519 * @param key the key of the sub configuration 520 * @return the new sub configuration 521 */ 522 private BaseHierarchicalConfiguration createIndependentSubConfiguration(final String key) { 523 final List<ImmutableNode> targetNodes = fetchFilteredNodeResults(key); 524 final int size = targetNodes.size(); 525 if (size != 1) { 526 throw new ConfigurationRuntimeException("Passed in key must select exactly one node (found %,d): %s", size, key); 527 } 528 final BaseHierarchicalConfiguration sub = new BaseHierarchicalConfiguration(new InMemoryNodeModel(targetNodes.get(0))); 529 initSubConfiguration(sub); 530 return sub; 531 } 532 533 /** 534 * Returns an initialized sub configuration for this configuration that is based on another 535 * {@code BaseHierarchicalConfiguration}. Thus, it is independent from this configuration. 536 * 537 * @param node the root node for the sub configuration 538 * @return the initialized sub configuration 539 */ 540 private BaseHierarchicalConfiguration createIndependentSubConfigurationForNode(final ImmutableNode node) { 541 final BaseHierarchicalConfiguration sub = new BaseHierarchicalConfiguration(new InMemoryNodeModel(node)); 542 initSubConfiguration(sub); 543 return sub; 544 } 545 546 /** 547 * Creates a connected sub configuration based on a selector for a tracked node. 548 * 549 * @param selector the {@code NodeSelector} 550 * @param parentModelSupport the {@code InMemoryNodeModelSupport} object for the parent node model 551 * @return the newly created sub configuration 552 * @since 2.0 553 */ 554 protected SubnodeConfiguration createSubConfigurationForTrackedNode(final NodeSelector selector, final InMemoryNodeModelSupport parentModelSupport) { 555 final SubnodeConfiguration subConfig = new SubnodeConfiguration(this, new TrackedNodeModel(parentModelSupport, selector, true)); 556 initSubConfigurationForThisParent(subConfig); 557 return subConfig; 558 } 559 560 /** 561 * Creates a root node for a subset configuration based on the passed in query results. This method creates a new root 562 * node and adds the children and attributes of all result nodes to it. If only a single node value is defined, it is 563 * assigned as value of the new root node. 564 * 565 * @param results the collection of query results 566 * @return the root node for the subset configuration 567 */ 568 private ImmutableNode createSubsetRootNode(final Collection<QueryResult<ImmutableNode>> results) { 569 final ImmutableNode.Builder builder = new ImmutableNode.Builder(); 570 Object value = null; 571 int valueCount = 0; 572 573 for (final QueryResult<ImmutableNode> result : results) { 574 if (result.isAttributeResult()) { 575 builder.addAttribute(result.getAttributeName(), result.getAttributeValue(getModel().getNodeHandler())); 576 } else { 577 if (result.getNode().getValue() != null) { 578 value = result.getNode().getValue(); 579 valueCount++; 580 } 581 builder.addChildren(result.getNode().getChildren()); 582 builder.addAttributes(result.getNode().getAttributes()); 583 } 584 } 585 586 if (valueCount == 1) { 587 builder.value(value); 588 } 589 return builder.create(); 590 } 591 592 /** 593 * Executes a query on the specified key and filters it for node results. 594 * 595 * @param key the key 596 * @return the filtered list with result nodes 597 */ 598 private List<ImmutableNode> fetchFilteredNodeResults(final String key) { 599 final NodeHandler<ImmutableNode> handler = getModel().getNodeHandler(); 600 return resolveNodeKey(handler.getRootNode(), key, handler); 601 } 602 603 /** 604 * {@inheritDoc} This implementation returns the {@code InMemoryNodeModel} used by this configuration. 605 */ 606 @Override 607 public InMemoryNodeModel getNodeModel() { 608 return (InMemoryNodeModel) super.getNodeModel(); 609 } 610 611 /** 612 * Gets the {@code NodeSelector} to be used for a sub configuration based on the passed in key. This method is called 613 * whenever a sub configuration is to be created. This base implementation returns a new {@code NodeSelector} 614 * initialized with the passed in key. Sub classes may override this method if they have a different strategy for 615 * creating a selector. 616 * 617 * @param key the key of the sub configuration 618 * @return a {@code NodeSelector} for initializing a sub configuration 619 * @since 2.0 620 */ 621 protected NodeSelector getSubConfigurationNodeSelector(final String key) { 622 return new NodeSelector(key); 623 } 624 625 /** 626 * Gets the {@code InMemoryNodeModel} to be used as parent model for a new sub configuration. This method is called 627 * whenever a sub configuration is to be created. This base implementation returns the model of this configuration. Sub 628 * classes with different requirements for the parent models of sub configurations have to override it. 629 * 630 * @return the parent model for a new sub configuration 631 */ 632 protected InMemoryNodeModel getSubConfigurationParentModel() { 633 return (InMemoryNodeModel) getModel(); 634 } 635 636 /** 637 * {@inheritDoc} This implementation first delegates to {@code childConfigurationsAt()} to create a list of mutable 638 * child configurations. Then a list with immutable wrapper configurations is created. 639 */ 640 @Override 641 public List<ImmutableHierarchicalConfiguration> immutableChildConfigurationsAt(final String key) { 642 return toImmutable(childConfigurationsAt(key)); 643 } 644 645 /** 646 * {@inheritDoc} This implementation creates a {@code SubnodeConfiguration} by delegating to {@code configurationAt()}. 647 * Then an immutable wrapper is created and returned. 648 * 649 * @throws ConfigurationRuntimeException if the key does not select a single node 650 */ 651 @Override 652 public ImmutableHierarchicalConfiguration immutableConfigurationAt(final String key) { 653 return ConfigurationUtils.unmodifiableConfiguration(configurationAt(key)); 654 } 655 656 /** 657 * {@inheritDoc} This implementation creates a {@code SubnodeConfiguration} by delegating to {@code configurationAt()}. 658 * Then an immutable wrapper is created and returned. 659 */ 660 @Override 661 public ImmutableHierarchicalConfiguration immutableConfigurationAt(final String key, final boolean supportUpdates) { 662 return ConfigurationUtils.unmodifiableConfiguration(configurationAt(key, supportUpdates)); 663 } 664 665 /** 666 * {@inheritDoc} This implementation first delegates to {@code configurationsAt()} to create a list of 667 * {@code SubnodeConfiguration} objects. Then for each element of this list an unmodifiable wrapper is created. 668 */ 669 @Override 670 public List<ImmutableHierarchicalConfiguration> immutableConfigurationsAt(final String key) { 671 return toImmutable(configurationsAt(key)); 672 } 673 674 /** 675 * Initializes properties of a sub configuration. A sub configuration inherits some settings from its parent, for example the 676 * expression engine or the synchronizer. The corresponding values are copied by this method. 677 * 678 * @param sub the sub configuration to be initialized 679 */ 680 private void initSubConfiguration(final BaseHierarchicalConfiguration sub) { 681 sub.setSynchronizer(getSynchronizer()); 682 sub.setExpressionEngine(getExpressionEngine()); 683 sub.setListDelimiterHandler(getListDelimiterHandler()); 684 sub.setThrowExceptionOnMissing(isThrowExceptionOnMissing()); 685 sub.getInterpolator().setParentInterpolator(getInterpolator()); 686 } 687 688 /** 689 * Initializes a {@code SubnodeConfiguration} object. This method should be called for each sub configuration created 690 * for this configuration. It ensures that the sub configuration is correctly connected to its parent instance and that 691 * update events are correctly propagated. 692 * 693 * @param subConfig the sub configuration to be initialized 694 * @since 2.0 695 */ 696 protected void initSubConfigurationForThisParent(final SubnodeConfiguration subConfig) { 697 initSubConfiguration(subConfig); 698 subConfig.addEventListener(ConfigurationEvent.ANY, changeListener); 699 } 700 701 /** 702 * Returns a configuration with the same content as this configuration, but with all variables replaced by their actual 703 * values. This implementation is specific for hierarchical configurations. It clones the current configuration and runs 704 * a specialized visitor on the clone, which performs interpolation on the single configuration nodes. 705 * 706 * @return a configuration with all variables interpolated 707 * @since 1.5 708 */ 709 @Override 710 public Configuration interpolatedConfiguration() { 711 final InterpolatedVisitor visitor = new InterpolatedVisitor(); 712 final NodeHandler<ImmutableNode> handler = getModel().getNodeHandler(); 713 NodeTreeWalker.INSTANCE.walkDFS(handler.getRootNode(), visitor, handler); 714 715 final BaseHierarchicalConfiguration c = (BaseHierarchicalConfiguration) clone(); 716 c.getNodeModel().setRootNode(visitor.getInterpolatedRoot()); 717 return c; 718 } 719 720 /** 721 * This method is always called when a subnode configuration created from this configuration has been modified. This 722 * implementation transforms the received event into an event of type {@code SUBNODE_CHANGED} and notifies the 723 * registered listeners. 724 * 725 * @param event the event describing the change 726 * @since 1.5 727 */ 728 protected void subnodeConfigurationChanged(final ConfigurationEvent event) { 729 fireEvent(ConfigurationEvent.SUBNODE_CHANGED, null, event, event.isBeforeUpdate()); 730 } 731 732 /** 733 * Creates a new {@code Configuration} object containing all keys that start with the specified prefix. This 734 * implementation will return a {@code BaseHierarchicalConfiguration} object so that the structure of the keys will be 735 * saved. The nodes selected by the prefix (it is possible that multiple nodes are selected) are mapped to the root node 736 * of the returned configuration, i.e. their children and attributes will become children and attributes of the new root 737 * node. However, a value of the root node is only set if exactly one of the selected nodes contain a value (if multiple 738 * nodes have a value, there is simply no way to decide how these values are merged together). Note that the returned 739 * {@code Configuration} object is not connected to its source configuration: updates on the source configuration are 740 * not reflected in the subset and vice versa. The returned configuration uses the same {@code Synchronizer} as this 741 * configuration. 742 * 743 * @param prefix the prefix of the keys for the subset 744 * @return a new configuration object representing the selected subset 745 */ 746 @Override 747 public Configuration subset(final String prefix) { 748 return syncRead(() -> { 749 final List<QueryResult<ImmutableNode>> results = fetchNodeList(prefix); 750 if (results.isEmpty()) { 751 return new BaseHierarchicalConfiguration(); 752 } 753 final BaseHierarchicalConfiguration parent = this; 754 final BaseHierarchicalConfiguration result = new BaseHierarchicalConfiguration() { 755 756 @Override 757 public ConfigurationInterpolator getInterpolator() { 758 return parent.getInterpolator(); 759 } 760 761 // Override interpolate to always interpolate on the parent 762 @Override 763 protected Object interpolate(final Object value) { 764 return parent.interpolate(value); 765 } 766 }; 767 result.getModel().setRootNode(createSubsetRootNode(results)); 768 if (result.isEmpty()) { 769 return new BaseHierarchicalConfiguration(); 770 } 771 result.setSynchronizer(getSynchronizer()); 772 return result; 773 }, false); 774 } 775}