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