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 */ 017package org.apache.commons.configuration2.builder.combined; 018 019import java.net.URL; 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; 028import java.util.Set; 029 030import org.apache.commons.configuration2.CombinedConfiguration; 031import org.apache.commons.configuration2.Configuration; 032import org.apache.commons.configuration2.ConfigurationLookup; 033import org.apache.commons.configuration2.HierarchicalConfiguration; 034import org.apache.commons.configuration2.SystemConfiguration; 035import org.apache.commons.configuration2.XMLConfiguration; 036import org.apache.commons.configuration2.beanutils.BeanDeclaration; 037import org.apache.commons.configuration2.beanutils.BeanHelper; 038import org.apache.commons.configuration2.beanutils.CombinedBeanDeclaration; 039import org.apache.commons.configuration2.beanutils.XMLBeanDeclaration; 040import org.apache.commons.configuration2.builder.BasicBuilderParameters; 041import org.apache.commons.configuration2.builder.BasicConfigurationBuilder; 042import org.apache.commons.configuration2.builder.BuilderParameters; 043import org.apache.commons.configuration2.builder.ConfigurationBuilder; 044import org.apache.commons.configuration2.builder.ConfigurationBuilderEvent; 045import org.apache.commons.configuration2.builder.FileBasedBuilderParametersImpl; 046import org.apache.commons.configuration2.builder.FileBasedBuilderProperties; 047import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; 048import org.apache.commons.configuration2.builder.XMLBuilderParametersImpl; 049import org.apache.commons.configuration2.builder.XMLBuilderProperties; 050import org.apache.commons.configuration2.event.EventListener; 051import org.apache.commons.configuration2.ex.ConfigurationException; 052import org.apache.commons.configuration2.interpol.ConfigurationInterpolator; 053import org.apache.commons.configuration2.interpol.Lookup; 054import org.apache.commons.configuration2.io.FileSystem; 055import org.apache.commons.configuration2.resolver.CatalogResolver; 056import org.apache.commons.configuration2.tree.DefaultExpressionEngineSymbols; 057import org.apache.commons.configuration2.tree.OverrideCombiner; 058import org.apache.commons.configuration2.tree.UnionCombiner; 059import org.xml.sax.EntityResolver; 060 061/** 062 * <p> 063 * A specialized {@code ConfigurationBuilder} implementation that creates a 064 * {@link CombinedConfiguration} from multiple configuration sources defined by 065 * an XML-based <em>configuration definition file</em>. 066 * </p> 067 * <p> 068 * This class provides an easy and flexible means for loading multiple 069 * configuration sources and combining the results into a single configuration 070 * object. The sources to be loaded are defined in an XML document that can 071 * contain certain tags representing the different supported configuration 072 * classes. If such a tag is found, a corresponding {@code ConfigurationBuilder} 073 * class is instantiated and initialized using the classes of the 074 * {@code beanutils} package (namely 075 * {@link org.apache.commons.configuration2.beanutils.XMLBeanDeclaration 076 * XMLBeanDeclaration} will be used to extract the configuration's 077 * initialization parameters, which allows for complex initialization 078 * scenarios). 079 * </p> 080 * <p> 081 * It is also possible to add custom tags to the configuration definition file. 082 * For this purpose an implementation of 083 * {@link CombinedConfigurationBuilderProvider} has to be created which is 084 * responsible for the creation of a {@code ConfigurationBuilder} associated 085 * with the custom tag. An instance of this class has to be registered at the 086 * {@link CombinedBuilderParametersImpl} object which is used to initialize this 087 * {@code CombinedConfigurationBuilder}. This provider will then be called when 088 * the corresponding custom tag is detected. For many default configuration 089 * classes providers are already registered. 090 * </p> 091 * <p> 092 * The configuration definition file has the following basic structure: 093 * </p> 094 * 095 * <pre> 096 * <configuration systemProperties="properties file name"> 097 * <header> 098 * <!-- Optional meta information about the combined configuration --> 099 * </header> 100 * <override> 101 * <!-- Declarations for override configurations --> 102 * </override> 103 * <additional> 104 * <!-- Declarations for union configurations --> 105 * </additional> 106 * </configuration> 107 * </pre> 108 * 109 * <p> 110 * The name of the root element (here {@code configuration}) is arbitrary. The 111 * optional {@code systemProperties} attribute identifies the path to a property 112 * file containing properties that should be added to the system properties. If 113 * specified on the root element, the system properties are set before the rest 114 * of the configuration is processed. 115 * </p> 116 * <p> 117 * There are two sections (both of them are optional) for declaring 118 * <em>override</em> and <em>additional</em> configurations. Configurations in 119 * the former section are evaluated in the order of their declaration, and 120 * properties of configurations declared earlier hide those of configurations 121 * declared later. Configurations in the latter section are combined to a union 122 * configuration, i.e. all of their properties are added to a large hierarchical 123 * configuration. Configuration declarations that occur as direct children of 124 * the root element are treated as override declarations. 125 * </p> 126 * <p> 127 * Each configuration declaration consists of a tag whose name is associated 128 * with a {@code CombinedConfigurationBuilderProvider}. This can be one of the 129 * predefined tags like {@code properties}, or {@code xml}, or a custom tag, for 130 * which a configuration builder provider was registered (as described above). 131 * Attributes and sub elements with specific initialization parameters can be 132 * added. There are some reserved attributes with a special meaning that can be 133 * used in every configuration declaration: 134 * </p> 135 * <table border="1"> 136 * <caption>Standard attributes for configuration declarations</caption> 137 * <tr> 138 * <th>Attribute</th> 139 * <th>Meaning</th> 140 * </tr> 141 * <tr> 142 * <td valign="top">{@code config-name}</td> 143 * <td>Allows specifying a name for this configuration. This name can be used to 144 * obtain a reference to the configuration from the resulting combined 145 * configuration (see below). It can also be passed to the 146 * {@link #getNamedBuilder(String)} method.</td> 147 * </tr> 148 * <tr> 149 * <td valign="top">{@code config-at}</td> 150 * <td>With this attribute an optional prefix can be specified for the 151 * properties of the corresponding configuration.</td> 152 * </tr> 153 * <tr> 154 * <td valign="top">{@code config-optional}</td> 155 * <td>Declares a configuration source as optional. This means that errors that 156 * occur when creating the configuration are ignored.</td> 157 * </tr> 158 * <tr> 159 * <td valign="top">{@code config-reload}</td> 160 * <td>Many configuration sources support a reloading mechanism. For those 161 * sources it is possible to enable reloading by providing this attribute with a 162 * value of <strong>true</strong>.</td> 163 * </tr> 164 * </table> 165 * <p> 166 * The optional <em>header</em> section can contain some meta data about the 167 * created configuration itself. For instance, it is possible to set further 168 * properties of the {@code NodeCombiner} objects used for constructing the 169 * resulting configuration. 170 * </p> 171 * <p> 172 * The default configuration object returned by this builder is an instance of 173 * the {@link CombinedConfiguration} class. This allows for convenient access to 174 * the configuration objects maintained by the combined configuration (e.g. for 175 * updates of single configuration objects). It has also the advantage that the 176 * properties stored in all declared configuration objects are collected and 177 * transformed into a single hierarchical structure, which can be accessed using 178 * different expression engines. The actual {@code CombinedConfiguration} 179 * implementation can be overridden by specifying the class in the 180 * <em>config-class</em> attribute of the result element. 181 * </p> 182 * <p> 183 * A custom EntityResolver can be used for all XMLConfigurations by adding 184 * </p> 185 * 186 * <pre> 187 * <entity-resolver config-class="EntityResolver fully qualified class name"> 188 * </pre> 189 * 190 * <p> 191 * A specific CatalogResolver can be specified for all XMLConfiguration sources 192 * by adding 193 * </p> 194 * <pre> 195 * <entity-resolver catalogFiles="comma separated list of catalog files"> 196 * </pre> 197 * 198 * <p> 199 * Additional ConfigurationProviders can be added by configuring them in the 200 * <em>header</em> section. 201 * </p> 202 * 203 * <pre> 204 * <providers> 205 * <provider config-tag="tag name" config-class="provider fully qualified class name"/> 206 * </providers> 207 * </pre> 208 * 209 * <p> 210 * Additional variable resolvers can be added by configuring them in the 211 * <em>header</em> section. 212 * </p> 213 * 214 * <pre> 215 * <lookups> 216 * <lookup config-prefix="prefix" config-class="StrLookup fully qualified class name"/> 217 * </lookups> 218 * </pre> 219 * 220 * <p> 221 * All declared override configurations are directly added to the resulting 222 * combined configuration. If they are given names (using the 223 * {@code config-name} attribute), they can directly be accessed using the 224 * {@code getConfiguration(String)} method of {@code CombinedConfiguration}. The 225 * additional configurations are altogether added to another combined 226 * configuration, which uses a union combiner. Then this union configuration is 227 * added to the resulting combined configuration under the name defined by the 228 * {@code ADDITIONAL_NAME} constant. The {@link #getNamedBuilder(String)} method 229 * can be used to access the {@code ConfigurationBuilder} objects for all 230 * configuration sources which have been assigned a name; care has to be taken 231 * that these names are unique. 232 * </p> 233 * 234 * @since 1.3 235 * @author <a 236 * href="http://commons.apache.org/configuration/team-list.html">Commons 237 * Configuration team</a> 238 * @version $Id: CombinedConfigurationBuilder.java 1836754 2018-07-26 19:39:33Z oheger $ 239 */ 240public class CombinedConfigurationBuilder extends BasicConfigurationBuilder<CombinedConfiguration> 241{ 242 /** 243 * Constant for the name of the additional configuration. If the 244 * configuration definition file contains an {@code additional} 245 * section, a special union configuration is created and added under this 246 * name to the resulting combined configuration. 247 */ 248 public static final String ADDITIONAL_NAME = CombinedConfigurationBuilder.class 249 .getName() 250 + "/ADDITIONAL_CONFIG"; 251 252 /** Constant for the name of the configuration bean factory. */ 253 static final String CONFIG_BEAN_FACTORY_NAME = CombinedConfigurationBuilder.class 254 .getName() 255 + ".CONFIG_BEAN_FACTORY_NAME"; 256 257 /** Constant for the reserved name attribute. */ 258 static final String ATTR_NAME = DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_START 259 + XMLBeanDeclaration.RESERVED_PREFIX 260 + "name" 261 + DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_END; 262 263 /** Constant for the name of the at attribute. */ 264 static final String ATTR_ATNAME = "at"; 265 266 /** Constant for the reserved at attribute. */ 267 static final String ATTR_AT_RES = DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_START 268 + XMLBeanDeclaration.RESERVED_PREFIX 269 + ATTR_ATNAME 270 + DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_END; 271 272 /** Constant for the at attribute without the reserved prefix. */ 273 static final String ATTR_AT = DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_START 274 + ATTR_ATNAME + DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_END; 275 276 /** Constant for the name of the optional attribute. */ 277 static final String ATTR_OPTIONALNAME = "optional"; 278 279 /** Constant for the reserved optional attribute. */ 280 static final String ATTR_OPTIONAL_RES = DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_START 281 + XMLBeanDeclaration.RESERVED_PREFIX 282 + ATTR_OPTIONALNAME 283 + DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_END; 284 285 /** Constant for the optional attribute without the reserved prefix. */ 286 static final String ATTR_OPTIONAL = DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_START 287 + ATTR_OPTIONALNAME + DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_END; 288 289 /** Constant for the forceCreate attribute. */ 290 static final String ATTR_FORCECREATE = DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_START 291 + XMLBeanDeclaration.RESERVED_PREFIX 292 + "forceCreate" 293 + DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_END; 294 295 /** Constant for the reload attribute. */ 296 static final String ATTR_RELOAD = DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_START 297 + XMLBeanDeclaration.RESERVED_PREFIX 298 + "reload" 299 + DefaultExpressionEngineSymbols.DEFAULT_ATTRIBUTE_END; 300 301 /** 302 * Constant for the tag attribute for providers. 303 */ 304 static final String KEY_SYSTEM_PROPS = "[@systemProperties]"; 305 306 /** Constant for the name of the header section. */ 307 static final String SEC_HEADER = "header"; 308 309 /** Constant for an expression that selects the union configurations. */ 310 static final String KEY_UNION = "additional"; 311 312 /** An array with the names of top level configuration sections.*/ 313 static final String[] CONFIG_SECTIONS = { 314 "additional", "override", SEC_HEADER 315 }; 316 317 /** 318 * Constant for an expression that selects override configurations in the 319 * override section. 320 */ 321 static final String KEY_OVERRIDE = "override"; 322 323 /** 324 * Constant for the key that points to the list nodes definition of the 325 * override combiner. 326 */ 327 static final String KEY_OVERRIDE_LIST = SEC_HEADER 328 + ".combiner.override.list-nodes.node"; 329 330 /** 331 * Constant for the key that points to the list nodes definition of the 332 * additional combiner. 333 */ 334 static final String KEY_ADDITIONAL_LIST = SEC_HEADER 335 + ".combiner.additional.list-nodes.node"; 336 337 /** 338 * Constant for the key for defining providers in the configuration file. 339 */ 340 static final String KEY_CONFIGURATION_PROVIDERS = SEC_HEADER 341 + ".providers.provider"; 342 343 /** 344 * Constant for the tag attribute for providers. 345 */ 346 static final String KEY_PROVIDER_KEY = XMLBeanDeclaration.ATTR_PREFIX + "tag]"; 347 348 /** 349 * Constant for the key for defining variable resolvers 350 */ 351 static final String KEY_CONFIGURATION_LOOKUPS = SEC_HEADER 352 + ".lookups.lookup"; 353 354 /** 355 * Constant for the key for defining entity resolvers 356 */ 357 static final String KEY_ENTITY_RESOLVER = SEC_HEADER + ".entity-resolver"; 358 359 /** 360 * Constant for the prefix attribute for lookups. 361 */ 362 static final String KEY_LOOKUP_KEY = XMLBeanDeclaration.ATTR_PREFIX + "prefix]"; 363 364 /** 365 * Constant for the FileSystem. 366 */ 367 static final String FILE_SYSTEM = SEC_HEADER + ".fileSystem"; 368 369 /** 370 * Constant for the key of the result declaration. This key can point to a 371 * bean declaration, which defines properties of the resulting combined 372 * configuration. 373 */ 374 static final String KEY_RESULT = SEC_HEADER + ".result"; 375 376 /** Constant for the key of the combiner in the result declaration.*/ 377 static final String KEY_COMBINER = KEY_RESULT + ".nodeCombiner"; 378 379 /** Constant for the XML file extension. */ 380 static final String EXT_XML = "xml"; 381 382 /** Constant for the basic configuration builder class. */ 383 private static final String BASIC_BUILDER = 384 "org.apache.commons.configuration2.builder.BasicConfigurationBuilder"; 385 386 /** Constant for the file-based configuration builder class. */ 387 private static final String FILE_BUILDER = 388 "org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder"; 389 390 /** Constant for the reloading file-based configuration builder class. */ 391 private static final String RELOADING_BUILDER = 392 "org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder"; 393 394 /** Constant for the name of the file-based builder parameters class. */ 395 private static final String FILE_PARAMS = 396 "org.apache.commons.configuration2.builder.FileBasedBuilderParametersImpl"; 397 398 /** Constant for the provider for properties files. */ 399 private static final ConfigurationBuilderProvider PROPERTIES_PROVIDER = 400 new FileExtensionConfigurationBuilderProvider( 401 FILE_BUILDER, 402 RELOADING_BUILDER, 403 "org.apache.commons.configuration2.XMLPropertiesConfiguration", 404 "org.apache.commons.configuration2.PropertiesConfiguration", 405 EXT_XML, Collections.singletonList(FILE_PARAMS)); 406 407 /** Constant for the provider for XML files. */ 408 private static final ConfigurationBuilderProvider XML_PROVIDER = 409 new BaseConfigurationBuilderProvider(FILE_BUILDER, RELOADING_BUILDER, 410 "org.apache.commons.configuration2.XMLConfiguration", 411 Collections.singletonList("org.apache.commons.configuration2.builder.XMLBuilderParametersImpl")); 412 413 /** Constant for the provider for JNDI sources. */ 414 private static final BaseConfigurationBuilderProvider JNDI_PROVIDER = 415 new BaseConfigurationBuilderProvider( 416 BASIC_BUILDER, 417 null, 418 "org.apache.commons.configuration2.JNDIConfiguration", 419 Collections.singletonList("org.apache.commons.configuration2.builder.JndiBuilderParametersImpl")); 420 421 /** Constant for the provider for system properties. */ 422 private static final BaseConfigurationBuilderProvider SYSTEM_PROVIDER = 423 new BaseConfigurationBuilderProvider( 424 BASIC_BUILDER, 425 null, 426 "org.apache.commons.configuration2.SystemConfiguration", 427 Collections.singletonList("org.apache.commons.configuration2.builder.BasicBuilderParameters")); 428 429 /** Constant for the provider for ini files. */ 430 private static final BaseConfigurationBuilderProvider INI_PROVIDER = 431 new BaseConfigurationBuilderProvider(FILE_BUILDER, RELOADING_BUILDER, 432 "org.apache.commons.configuration2.INIConfiguration", 433 Collections.singletonList(FILE_PARAMS)); 434 435 /** Constant for the provider for environment properties. */ 436 private static final BaseConfigurationBuilderProvider ENV_PROVIDER = 437 new BaseConfigurationBuilderProvider( 438 BASIC_BUILDER, 439 null, 440 "org.apache.commons.configuration2.EnvironmentConfiguration", 441 Collections.singletonList("org.apache.commons.configuration2.builder.BasicBuilderParameters")); 442 443 /** Constant for the provider for plist files. */ 444 private static final BaseConfigurationBuilderProvider PLIST_PROVIDER = 445 new FileExtensionConfigurationBuilderProvider( 446 FILE_BUILDER, 447 RELOADING_BUILDER, 448 "org.apache.commons.configuration2.plist.XMLPropertyListConfiguration", 449 "org.apache.commons.configuration2.plist.PropertyListConfiguration", 450 EXT_XML, Collections.singletonList(FILE_PARAMS)); 451 452 /** Constant for the provider for configuration definition files. */ 453 private static final BaseConfigurationBuilderProvider COMBINED_PROVIDER = 454 new CombinedConfigurationBuilderProvider(); 455 456 /** Constant for the provider for multiple XML configurations. */ 457 private static final MultiFileConfigurationBuilderProvider MULTI_XML_PROVIDER = 458 new MultiFileConfigurationBuilderProvider( 459 "org.apache.commons.configuration2.XMLConfiguration", 460 "org.apache.commons.configuration2.builder.XMLBuilderParametersImpl"); 461 462 /** An array with the names of the default tags. */ 463 private static final String[] DEFAULT_TAGS = { 464 "properties", "xml", "hierarchicalXml", "plist", 465 "ini", "system", "env", "jndi", "configuration", "multiFile" 466 }; 467 468 /** An array with the providers for the default tags. */ 469 private static final ConfigurationBuilderProvider[] DEFAULT_PROVIDERS = { 470 PROPERTIES_PROVIDER, XML_PROVIDER, XML_PROVIDER, PLIST_PROVIDER, INI_PROVIDER, 471 SYSTEM_PROVIDER, ENV_PROVIDER, JNDI_PROVIDER, COMBINED_PROVIDER, 472 MULTI_XML_PROVIDER 473 }; 474 475 /** A map with the default configuration builder providers. */ 476 private static final Map<String, ConfigurationBuilderProvider> DEFAULT_PROVIDERS_MAP; 477 478 /** The builder for the definition configuration. */ 479 private ConfigurationBuilder<? extends HierarchicalConfiguration<?>> definitionBuilder; 480 481 /** Stores temporarily the configuration with the builder definitions. */ 482 private HierarchicalConfiguration<?> definitionConfiguration; 483 484 /** The object with data about configuration sources. */ 485 private ConfigurationSourceData sourceData; 486 487 /** Stores the current parameters object. */ 488 private CombinedBuilderParametersImpl currentParameters; 489 490 /** The current XML parameters object. */ 491 private XMLBuilderParametersImpl currentXMLParameters; 492 493 /** The configuration that is currently constructed. */ 494 private CombinedConfiguration currentConfiguration; 495 496 /** 497 * A {@code ConfigurationInterpolator} to be used as parent for all child 498 * configurations to enable cross-source interpolation. 499 */ 500 private ConfigurationInterpolator parentInterpolator; 501 502 /** 503 * Creates a new instance of {@code CombinedConfigurationBuilder}. No parameters 504 * are set. 505 */ 506 public CombinedConfigurationBuilder() 507 { 508 super(CombinedConfiguration.class); 509 } 510 511 /** 512 * 513 * Creates a new instance of {@code CombinedConfigurationBuilder} and sets 514 * the specified initialization parameters. 515 * @param params a map with initialization parameters 516 */ 517 public CombinedConfigurationBuilder(Map<String, Object> params) 518 { 519 super(CombinedConfiguration.class, params); 520 } 521 522 /** 523 * 524 * Creates a new instance of {@code CombinedConfigurationBuilder} and sets 525 * the specified initialization parameters and the <em>allowFailOnInit</em> flag. 526 * @param params a map with initialization parameters 527 * @param allowFailOnInit the <em>allowFailOnInit</em> flag 528 */ 529 public CombinedConfigurationBuilder(Map<String, Object> params, boolean allowFailOnInit) 530 { 531 super(CombinedConfiguration.class, params, allowFailOnInit); 532 } 533 534 /** 535 * Returns the {@code ConfigurationBuilder} which creates the definition 536 * configuration. 537 * 538 * @return the builder for the definition configuration 539 * @throws ConfigurationException if an error occurs 540 */ 541 public synchronized ConfigurationBuilder<? extends HierarchicalConfiguration<?>> getDefinitionBuilder() 542 throws ConfigurationException 543 { 544 if (definitionBuilder == null) 545 { 546 definitionBuilder = setupDefinitionBuilder(getParameters()); 547 addDefinitionBuilderChangeListener(definitionBuilder); 548 } 549 return definitionBuilder; 550 } 551 552 /** 553 * {@inheritDoc} This method is overridden to adapt the return type. 554 */ 555 @Override 556 public CombinedConfigurationBuilder configure(BuilderParameters... params) 557 { 558 super.configure(params); 559 return this; 560 } 561 562 /** 563 * <p> 564 * Returns the configuration builder with the given name. With this method a 565 * builder of a child configuration which was given a name in the 566 * configuration definition file can be accessed directly. 567 * </p> 568 * <p> 569 * <strong>Important note:</strong> This method only returns a meaningful 570 * result after the result configuration has been created by calling 571 * {@code getConfiguration()}. If called before, always an exception is 572 * thrown. 573 * </p> 574 * 575 * @param name the name of the builder in question 576 * @return the child configuration builder with this name 577 * @throws ConfigurationException if information about named builders is not 578 * yet available or no builder with this name exists 579 */ 580 public synchronized ConfigurationBuilder<? extends Configuration> getNamedBuilder( 581 String name) throws ConfigurationException 582 { 583 if (sourceData == null) 584 { 585 throw new ConfigurationException("Information about child builders" 586 + " has not been setup yet! Call getConfiguration() first."); 587 } 588 ConfigurationBuilder<? extends Configuration> builder = 589 sourceData.getNamedBuilder(name); 590 if (builder == null) 591 { 592 throw new ConfigurationException("Builder cannot be resolved: " 593 + name); 594 } 595 return builder; 596 } 597 598 /** 599 * <p> 600 * Returns a set with the names of all child configuration builders. A tag 601 * defining a configuration source in the configuration definition file can 602 * have the {@code config-name} attribute. If this attribute is present, the 603 * corresponding builder is assigned this name and can be directly accessed 604 * through the {@link #getNamedBuilder(String)} method. This method returns 605 * a collection with all available builder names. 606 * </p> 607 * <p> 608 * <strong>Important note:</strong> This method only returns a meaningful 609 * result after the result configuration has been created by calling 610 * {@code getConfiguration()}. If called before, always an empty set is 611 * returned. 612 * </p> 613 * 614 * @return a set with the names of all builders 615 */ 616 public synchronized Set<String> builderNames() 617 { 618 if (sourceData == null) 619 { 620 return Collections.emptySet(); 621 } 622 else 623 { 624 return Collections.unmodifiableSet(sourceData.builderNames()); 625 } 626 } 627 628 /** 629 * {@inheritDoc} This implementation resets some specific internal state of 630 * this builder. 631 */ 632 @Override 633 public synchronized void resetParameters() 634 { 635 super.resetParameters(); 636 definitionBuilder = null; 637 definitionConfiguration = null; 638 currentParameters = null; 639 currentXMLParameters = null; 640 641 if (sourceData != null) 642 { 643 sourceData.cleanUp(); 644 sourceData = null; 645 } 646 } 647 648 /** 649 * Obtains the {@code ConfigurationBuilder} object which provides access to 650 * the configuration containing the definition of the combined configuration 651 * to create. If a definition builder is defined in the parameters, it is 652 * used. Otherwise, we check whether the combined builder parameters object 653 * contains a parameters object for the definition builder. If this is the 654 * case, a builder for an {@code XMLConfiguration} is created and configured 655 * with this object. As a last resort, it is looked for a 656 * {@link FileBasedBuilderParametersImpl} object in the properties. If 657 * found, also a XML configuration builder is created which loads this file. 658 * Note: This method is called from a synchronized block. 659 * 660 * @param params the current parameters for this builder 661 * @return the builder for the definition configuration 662 * @throws ConfigurationException if an error occurs 663 */ 664 protected ConfigurationBuilder<? extends HierarchicalConfiguration<?>> setupDefinitionBuilder( 665 Map<String, Object> params) throws ConfigurationException 666 { 667 CombinedBuilderParametersImpl cbParams = 668 CombinedBuilderParametersImpl.fromParameters(params); 669 if (cbParams != null) 670 { 671 ConfigurationBuilder<? extends HierarchicalConfiguration<?>> defBuilder = 672 cbParams.getDefinitionBuilder(); 673 if (defBuilder != null) 674 { 675 return defBuilder; 676 } 677 678 if (cbParams.getDefinitionBuilderParameters() != null) 679 { 680 return createXMLDefinitionBuilder(cbParams 681 .getDefinitionBuilderParameters()); 682 } 683 } 684 685 BuilderParameters fileParams = 686 FileBasedBuilderParametersImpl.fromParameters(params); 687 if (fileParams != null) 688 { 689 return createXMLDefinitionBuilder(fileParams); 690 } 691 692 throw new ConfigurationException( 693 "No builder for configuration definition specified!"); 694 } 695 696 /** 697 * Creates a default builder for the definition configuration and 698 * initializes it with a parameters object. This method is called if no 699 * definition builder is defined in this builder's parameters. This 700 * implementation creates a default file-based builder which produces an 701 * {@code XMLConfiguration}; it expects a corresponding file specification. 702 * Note: This method is called in a synchronized block. 703 * 704 * @param builderParams the parameters object for the builder 705 * @return the standard builder for the definition configuration 706 */ 707 protected ConfigurationBuilder<? extends HierarchicalConfiguration<?>> createXMLDefinitionBuilder( 708 BuilderParameters builderParams) 709 { 710 return new FileBasedConfigurationBuilder<>( 711 XMLConfiguration.class).configure(builderParams); 712 } 713 714 /** 715 * Returns the configuration containing the definition of the combined 716 * configuration to be created. This method only returns a defined result 717 * during construction of the result configuration. The definition 718 * configuration is obtained from the definition builder at first access and 719 * then stored temporarily to ensure that during result construction always 720 * the same configuration instance is used. (Otherwise, it would be possible 721 * that the definition builder returns a different instance when queried 722 * multiple times.) 723 * 724 * @return the definition configuration 725 * @throws ConfigurationException if an error occurs 726 */ 727 protected HierarchicalConfiguration<?> getDefinitionConfiguration() 728 throws ConfigurationException 729 { 730 if (definitionConfiguration == null) 731 { 732 definitionConfiguration = getDefinitionBuilder().getConfiguration(); 733 } 734 return definitionConfiguration; 735 } 736 737 /** 738 * Returns a collection with the builders for all child configuration 739 * sources. This method can be used by derived classes providing additional 740 * functionality on top of the declared configuration sources. It only 741 * returns a defined value during construction of the result configuration 742 * instance. 743 * 744 * @return a collection with the builders for child configuration sources 745 */ 746 protected synchronized Collection<ConfigurationBuilder<? extends Configuration>> getChildBuilders() 747 { 748 return sourceData.getChildBuilders(); 749 } 750 751 /** 752 * {@inheritDoc} This implementation evaluates the {@code result} property 753 * of the definition configuration. It creates a combined bean declaration 754 * with both the properties specified in the definition file and the 755 * properties defined as initialization parameters. 756 */ 757 @Override 758 protected BeanDeclaration createResultDeclaration(Map<String, Object> params) 759 throws ConfigurationException 760 { 761 BeanDeclaration paramsDecl = super.createResultDeclaration(params); 762 XMLBeanDeclaration resultDecl = 763 new XMLBeanDeclaration(getDefinitionConfiguration(), 764 KEY_RESULT, true, CombinedConfiguration.class.getName()); 765 return new CombinedBeanDeclaration(resultDecl, paramsDecl); 766 } 767 768 /** 769 * {@inheritDoc} This implementation processes the definition configuration 770 * in order to 771 * <ul> 772 * <li>initialize the resulting {@code CombinedConfiguration}</li> 773 * <li>determine the builders for all configuration sources</li> 774 * <li>populate the resulting {@code CombinedConfiguration}</li> 775 * </ul> 776 */ 777 @Override 778 protected void initResultInstance(CombinedConfiguration result) 779 throws ConfigurationException 780 { 781 super.initResultInstance(result); 782 783 currentConfiguration = result; 784 HierarchicalConfiguration<?> config = getDefinitionConfiguration(); 785 if (config.getMaxIndex(KEY_COMBINER) < 0) 786 { 787 // No combiner defined => set default 788 result.setNodeCombiner(new OverrideCombiner()); 789 } 790 791 setUpCurrentParameters(); 792 initNodeCombinerListNodes(result, config, KEY_OVERRIDE_LIST); 793 registerConfiguredProviders(config); 794 setUpCurrentXMLParameters(); 795 currentXMLParameters.setFileSystem(initFileSystem(config)); 796 initSystemProperties(config, getBasePath()); 797 registerConfiguredLookups(config, result); 798 configureEntityResolver(config, currentXMLParameters); 799 setUpParentInterpolator(currentConfiguration, config); 800 801 ConfigurationSourceData data = getSourceData(); 802 boolean createBuilders = data.getChildBuilders().isEmpty(); 803 List<ConfigurationBuilder<? extends Configuration>> overrideBuilders = 804 data.createAndAddConfigurations(result, 805 data.getOverrideSources(), data.overrideBuilders); 806 if (createBuilders) 807 { 808 data.overrideBuilders.addAll(overrideBuilders); 809 } 810 if (!data.getUnionSources().isEmpty()) 811 { 812 CombinedConfiguration addConfig = createAdditionalsConfiguration(result); 813 result.addConfiguration(addConfig, ADDITIONAL_NAME); 814 initNodeCombinerListNodes(addConfig, config, KEY_ADDITIONAL_LIST); 815 List<ConfigurationBuilder<? extends Configuration>> unionBuilders = 816 data.createAndAddConfigurations(addConfig, 817 data.unionDeclarations, data.unionBuilders); 818 if (createBuilders) 819 { 820 data.unionBuilders.addAll(unionBuilders); 821 } 822 } 823 824 result.isEmpty(); // this sets up the node structure 825 currentConfiguration = null; 826 } 827 828 /** 829 * Creates the {@code CombinedConfiguration} for the configuration 830 * sources in the <code><additional></code> section. This method is 831 * called when the builder constructs the final configuration. It creates a 832 * new {@code CombinedConfiguration} and initializes some properties 833 * from the result configuration. 834 * 835 * @param resultConfig the result configuration (this is the configuration 836 * that will be returned by the builder) 837 * @return the {@code CombinedConfiguration} for the additional 838 * configuration sources 839 * @since 1.7 840 */ 841 protected CombinedConfiguration createAdditionalsConfiguration( 842 CombinedConfiguration resultConfig) 843 { 844 CombinedConfiguration addConfig = 845 new CombinedConfiguration(new UnionCombiner()); 846 addConfig.setListDelimiterHandler(resultConfig.getListDelimiterHandler()); 847 return addConfig; 848 } 849 850 /** 851 * Processes custom {@link Lookup} objects that might be declared in the 852 * definition configuration. Each {@code Lookup} object is registered at the 853 * definition configuration and at the result configuration. It is also 854 * added to all child configurations added to the resulting combined 855 * configuration. 856 * 857 * @param defConfig the definition configuration 858 * @param resultConfig the resulting configuration 859 * @throws ConfigurationException if an error occurs 860 */ 861 protected void registerConfiguredLookups( 862 HierarchicalConfiguration<?> defConfig, Configuration resultConfig) 863 throws ConfigurationException 864 { 865 Map<String, Lookup> lookups = new HashMap<>(); 866 867 List<? extends HierarchicalConfiguration<?>> nodes = 868 defConfig.configurationsAt(KEY_CONFIGURATION_LOOKUPS); 869 for (HierarchicalConfiguration<?> config : nodes) 870 { 871 XMLBeanDeclaration decl = new XMLBeanDeclaration(config); 872 String key = config.getString(KEY_LOOKUP_KEY); 873 Lookup lookup = (Lookup) fetchBeanHelper().createBean(decl); 874 lookups.put(key, lookup); 875 } 876 877 if (!lookups.isEmpty()) 878 { 879 ConfigurationInterpolator defCI = defConfig.getInterpolator(); 880 if (defCI != null) 881 { 882 defCI.registerLookups(lookups); 883 } 884 resultConfig.getInterpolator().registerLookups(lookups); 885 } 886 } 887 888 /** 889 * Creates and initializes a default {@code FileSystem} if the definition 890 * configuration contains a corresponding declaration. The file system 891 * returned by this method is used as default for all file-based child 892 * configuration sources. 893 * 894 * @param config the definition configuration 895 * @return the default {@code FileSystem} (may be <b>null</b>) 896 * @throws ConfigurationException if an error occurs 897 */ 898 protected FileSystem initFileSystem(HierarchicalConfiguration<?> config) 899 throws ConfigurationException 900 { 901 if (config.getMaxIndex(FILE_SYSTEM) == 0) 902 { 903 XMLBeanDeclaration decl = 904 new XMLBeanDeclaration(config, FILE_SYSTEM); 905 return (FileSystem) fetchBeanHelper().createBean(decl); 906 } 907 return null; 908 } 909 910 /** 911 * Handles a file with system properties that may be defined in the 912 * definition configuration. If such property file is configured, all of its 913 * properties are added to the system properties. 914 * 915 * @param config the definition configuration 916 * @param basePath the base path defined for this builder (may be 917 * <b>null</b>) 918 * @throws ConfigurationException if an error occurs. 919 */ 920 protected void initSystemProperties(HierarchicalConfiguration<?> config, 921 String basePath) throws ConfigurationException 922 { 923 String fileName = config.getString(KEY_SYSTEM_PROPS); 924 if (fileName != null) 925 { 926 try 927 { 928 SystemConfiguration.setSystemProperties(basePath, fileName); 929 } 930 catch (Exception ex) 931 { 932 throw new ConfigurationException( 933 "Error setting system properties from " + fileName, ex); 934 } 935 } 936 } 937 938 /** 939 * Creates and initializes a default {@code EntityResolver} if the 940 * definition configuration contains a corresponding declaration. 941 * 942 * @param config the definition configuration 943 * @param xmlParams the (already partly initialized) object with XML 944 * parameters; here the new resolver is to be stored 945 * @throws ConfigurationException if an error occurs 946 */ 947 protected void configureEntityResolver(HierarchicalConfiguration<?> config, 948 XMLBuilderParametersImpl xmlParams) throws ConfigurationException 949 { 950 if (config.getMaxIndex(KEY_ENTITY_RESOLVER) == 0) 951 { 952 XMLBeanDeclaration decl = 953 new XMLBeanDeclaration(config, KEY_ENTITY_RESOLVER, true); 954 EntityResolver resolver = 955 (EntityResolver) fetchBeanHelper().createBean(decl, 956 CatalogResolver.class); 957 FileSystem fileSystem = xmlParams.getFileHandler().getFileSystem(); 958 if (fileSystem != null) 959 { 960 BeanHelper.setProperty(resolver, "fileSystem", fileSystem); 961 } 962 String basePath = xmlParams.getFileHandler().getBasePath(); 963 if (basePath != null) 964 { 965 BeanHelper.setProperty(resolver, "baseDir", basePath); 966 } 967 ConfigurationInterpolator ci = new ConfigurationInterpolator(); 968 ci.registerLookups(fetchPrefixLookups()); 969 BeanHelper.setProperty(resolver, "interpolator", ci); 970 971 xmlParams.setEntityResolver(resolver); 972 } 973 } 974 975 /** 976 * Returns the {@code ConfigurationBuilderProvider} for the given tag. This 977 * method is called during creation of the result configuration. (It is not 978 * allowed to call it at another point of time; result is then 979 * unpredictable!) It supports all default providers and custom providers 980 * added through the parameters object as well. 981 * 982 * @param tagName the name of the tag 983 * @return the provider that was registered for this tag or <b>null</b> if 984 * there is none 985 */ 986 protected ConfigurationBuilderProvider providerForTag(String tagName) 987 { 988 return currentParameters.providerForTag(tagName); 989 } 990 991 /** 992 * Initializes a parameters object for a child builder. This combined 993 * configuration builder has a bunch of properties which may be inherited by 994 * child configurations, e.g. the base path, the file system, etc. While 995 * processing the builders for child configurations, this method is called 996 * for each parameters object for a child builder. It initializes some 997 * properties of the passed in parameters objects which are derived from 998 * this parent builder. 999 * 1000 * @param params the parameters object to be initialized 1001 */ 1002 protected void initChildBuilderParameters(BuilderParameters params) 1003 { 1004 initDefaultChildParameters(params); 1005 1006 if (params instanceof BasicBuilderParameters) 1007 { 1008 initChildBasicParameters((BasicBuilderParameters) params); 1009 } 1010 if (params instanceof XMLBuilderProperties<?>) 1011 { 1012 initChildXMLParameters((XMLBuilderProperties<?>) params); 1013 } 1014 if (params instanceof FileBasedBuilderProperties<?>) 1015 { 1016 initChildFileBasedParameters((FileBasedBuilderProperties<?>) params); 1017 } 1018 if (params instanceof CombinedBuilderParametersImpl) 1019 { 1020 initChildCombinedParameters((CombinedBuilderParametersImpl) params); 1021 } 1022 } 1023 1024 /** 1025 * Initializes the event listeners of the specified builder from this 1026 * object. This method is used to inherit all listeners from a parent 1027 * builder. 1028 * 1029 * @param dest the destination builder object which is to be initialized 1030 */ 1031 void initChildEventListeners( 1032 BasicConfigurationBuilder<? extends Configuration> dest) 1033 { 1034 copyEventListeners(dest); 1035 } 1036 1037 /** 1038 * Returns the configuration object that is currently constructed. This 1039 * method can be called during construction of the result configuration. It 1040 * is intended for internal usage, e.g. some specialized builder providers 1041 * need access to this configuration to perform advanced initialization. 1042 * 1043 * @return the configuration that us currently under construction 1044 */ 1045 CombinedConfiguration getConfigurationUnderConstruction() 1046 { 1047 return currentConfiguration; 1048 } 1049 1050 /** 1051 * Initializes a bean using the current {@code BeanHelper}. This is needed 1052 * by builder providers when the configuration objects for sub builders are 1053 * constructed. 1054 * 1055 * @param bean the bean to be initialized 1056 * @param decl the {@code BeanDeclaration} 1057 */ 1058 void initBean(Object bean, BeanDeclaration decl) 1059 { 1060 fetchBeanHelper().initBean(bean, decl); 1061 } 1062 1063 /** 1064 * Initializes the current parameters object. This object has either been 1065 * passed at builder configuration time or it is newly created. In any 1066 * case, it is manipulated during result creation. 1067 */ 1068 private void setUpCurrentParameters() 1069 { 1070 currentParameters = 1071 CombinedBuilderParametersImpl.fromParameters(getParameters(), true); 1072 currentParameters.registerMissingProviders(DEFAULT_PROVIDERS_MAP); 1073 } 1074 1075 /** 1076 * Sets up an XML parameters object which is used to store properties 1077 * related to XML and file-based configurations during creation of the 1078 * result configuration. The properties stored in this object can be 1079 * inherited to child configurations. 1080 * 1081 * @throws ConfigurationException if an error occurs 1082 */ 1083 private void setUpCurrentXMLParameters() throws ConfigurationException 1084 { 1085 currentXMLParameters = new XMLBuilderParametersImpl(); 1086 initDefaultBasePath(); 1087 } 1088 1089 /** 1090 * Sets up a parent {@code ConfigurationInterpolator} object. This object 1091 * has a default {@link Lookup} querying the resulting combined 1092 * configuration. Thus interpolation works globally across all configuration 1093 * sources. 1094 * 1095 * @param resultConfig the result configuration 1096 * @param defConfig the definition configuration 1097 */ 1098 private void setUpParentInterpolator(Configuration resultConfig, 1099 Configuration defConfig) 1100 { 1101 parentInterpolator = new ConfigurationInterpolator(); 1102 parentInterpolator.addDefaultLookup(new ConfigurationLookup( 1103 resultConfig)); 1104 ConfigurationInterpolator defInterpolator = defConfig.getInterpolator(); 1105 if (defInterpolator != null) 1106 { 1107 defInterpolator.setParentInterpolator(parentInterpolator); 1108 } 1109 } 1110 1111 /** 1112 * Initializes the default base path for all file-based child configuration 1113 * sources. The base path can be explicitly defined in the parameters of 1114 * this builder. Otherwise, if the definition builder is a file-based 1115 * builder, it is obtained from there. 1116 * 1117 * @throws ConfigurationException if an error occurs 1118 */ 1119 private void initDefaultBasePath() throws ConfigurationException 1120 { 1121 assert currentParameters != null : "Current parameters undefined!"; 1122 if (currentParameters.getBasePath() != null) 1123 { 1124 currentXMLParameters.setBasePath(currentParameters.getBasePath()); 1125 } 1126 else 1127 { 1128 ConfigurationBuilder<? extends HierarchicalConfiguration<?>> defBuilder = 1129 getDefinitionBuilder(); 1130 if (defBuilder instanceof FileBasedConfigurationBuilder) 1131 { 1132 @SuppressWarnings("rawtypes") 1133 FileBasedConfigurationBuilder fileBuilder = 1134 (FileBasedConfigurationBuilder) defBuilder; 1135 URL url = fileBuilder.getFileHandler().getURL(); 1136 currentXMLParameters.setBasePath((url != null) ? url 1137 .toExternalForm() : fileBuilder.getFileHandler() 1138 .getBasePath()); 1139 } 1140 } 1141 } 1142 1143 /** 1144 * Executes the {@link org.apache.commons.configuration2.builder.DefaultParametersManager 1145 * DefaultParametersManager} stored in the current 1146 * parameters on the passed in parameters object. If default handlers have been 1147 * registered for this type of parameters, an initialization is now 1148 * performed. This method is called before the parameters object is 1149 * initialized from the configuration definition file. So default values 1150 * can be overridden later with concrete property definitions. 1151 * 1152 * @param params the parameters to be initialized 1153 * @throws org.apache.commons.configuration2.ex.ConfigurationRuntimeException if an error 1154 * occurs when copying properties 1155 */ 1156 private void initDefaultChildParameters(BuilderParameters params) 1157 { 1158 currentParameters.getChildDefaultParametersManager() 1159 .initializeParameters(params); 1160 } 1161 1162 /** 1163 * Initializes basic builder parameters for a child configuration with 1164 * default settings set for this builder. This implementation ensures that 1165 * all {@code Lookup} objects are propagated to child configurations and 1166 * interpolation is setup correctly. 1167 * 1168 * @param params the parameters object 1169 */ 1170 private void initChildBasicParameters(BasicBuilderParameters params) 1171 { 1172 params.setPrefixLookups(fetchPrefixLookups()); 1173 params.setParentInterpolator(parentInterpolator); 1174 if (currentParameters.isInheritSettings()) 1175 { 1176 params.inheritFrom(getParameters()); 1177 } 1178 } 1179 1180 /** 1181 * Initializes a parameters object for a file-based configuration with 1182 * properties already set for this parent builder. This method handles 1183 * properties like a default file system or a base path. 1184 * 1185 * @param params the parameters object 1186 */ 1187 private void initChildFileBasedParameters( 1188 FileBasedBuilderProperties<?> params) 1189 { 1190 params.setBasePath(getBasePath()); 1191 params.setFileSystem(currentXMLParameters.getFileHandler() 1192 .getFileSystem()); 1193 } 1194 1195 /** 1196 * Initializes a parameters object for an XML configuration with properties 1197 * already set for this parent builder. 1198 * 1199 * @param params the parameters object 1200 */ 1201 private void initChildXMLParameters(XMLBuilderProperties<?> params) 1202 { 1203 params.setEntityResolver(currentXMLParameters.getEntityResolver()); 1204 } 1205 1206 /** 1207 * Initializes a parameters object for a combined configuration builder with 1208 * properties already set for this parent builder. This implementation deals 1209 * only with a subset of properties. Other properties are already handled by 1210 * the specialized builder provider. 1211 * 1212 * @param params the parameters object 1213 */ 1214 private void initChildCombinedParameters( 1215 CombinedBuilderParametersImpl params) 1216 { 1217 params.registerMissingProviders(currentParameters); 1218 params.setBasePath(getBasePath()); 1219 } 1220 1221 /** 1222 * Obtains the data object for the configuration sources and the 1223 * corresponding builders. This object is created on first access and reset 1224 * when the definition builder sends a change event. This method is called 1225 * in a synchronized block. 1226 * 1227 * @return the object with information about configuration sources 1228 * @throws ConfigurationException if an error occurs 1229 */ 1230 private ConfigurationSourceData getSourceData() 1231 throws ConfigurationException 1232 { 1233 if (sourceData == null) 1234 { 1235 if (currentParameters == null) 1236 { 1237 setUpCurrentParameters(); 1238 setUpCurrentXMLParameters(); 1239 } 1240 sourceData = createSourceData(); 1241 } 1242 return sourceData; 1243 } 1244 1245 /** 1246 * Creates the data object for configuration sources and the corresponding 1247 * builders. 1248 * 1249 * @return the newly created data object 1250 * @throws ConfigurationException if an error occurs 1251 */ 1252 private ConfigurationSourceData createSourceData() 1253 throws ConfigurationException 1254 { 1255 ConfigurationSourceData result = new ConfigurationSourceData(); 1256 result.initFromDefinitionConfiguration(getDefinitionConfiguration()); 1257 return result; 1258 } 1259 1260 /** 1261 * Returns the current base path of this configuration builder. This is used 1262 * for instance by all file-based child configurations. 1263 * 1264 * @return the base path 1265 */ 1266 private String getBasePath() 1267 { 1268 return currentXMLParameters.getFileHandler().getBasePath(); 1269 } 1270 1271 /** 1272 * Registers providers defined in the configuration. 1273 * 1274 * @param defConfig the definition configuration 1275 * @throws ConfigurationException if an error occurs 1276 */ 1277 private void registerConfiguredProviders(HierarchicalConfiguration<?> defConfig) 1278 throws ConfigurationException 1279 { 1280 List<? extends HierarchicalConfiguration<?>> nodes = 1281 defConfig.configurationsAt(KEY_CONFIGURATION_PROVIDERS); 1282 for (HierarchicalConfiguration<?> config : nodes) 1283 { 1284 XMLBeanDeclaration decl = new XMLBeanDeclaration(config); 1285 String key = config.getString(KEY_PROVIDER_KEY); 1286 currentParameters.registerProvider(key, 1287 (ConfigurationBuilderProvider) fetchBeanHelper().createBean(decl)); 1288 } 1289 } 1290 1291 /** 1292 * Adds a listener at the given definition builder which resets this builder 1293 * when a reset of the definition builder happens. This way it is ensured 1294 * that this builder produces a new combined configuration when its 1295 * definition configuration changes. 1296 * 1297 * @param defBuilder the definition builder 1298 */ 1299 private void addDefinitionBuilderChangeListener( 1300 final ConfigurationBuilder<? extends HierarchicalConfiguration<?>> defBuilder) 1301 { 1302 defBuilder.addEventListener(ConfigurationBuilderEvent.RESET, 1303 new EventListener<ConfigurationBuilderEvent>() 1304 { 1305 @Override 1306 public void onEvent(ConfigurationBuilderEvent event) 1307 { 1308 synchronized (CombinedConfigurationBuilder.this) 1309 { 1310 reset(); 1311 definitionBuilder = defBuilder; 1312 } 1313 } 1314 }); 1315 } 1316 1317 /** 1318 * Returns a map with the current prefix lookup objects. This map is 1319 * obtained from the {@code ConfigurationInterpolator} of the configuration 1320 * under construction. 1321 * 1322 * @return the map with current prefix lookups (may be <b>null</b>) 1323 */ 1324 private Map<String, ? extends Lookup> fetchPrefixLookups() 1325 { 1326 CombinedConfiguration cc = getConfigurationUnderConstruction(); 1327 return (cc != null) ? cc.getInterpolator().getLookups() : null; 1328 } 1329 1330 /** 1331 * Creates {@code ConfigurationDeclaration} objects for the specified 1332 * configurations. 1333 * 1334 * @param configs the list with configurations 1335 * @return a collection with corresponding declarations 1336 */ 1337 private Collection<ConfigurationDeclaration> createDeclarations( 1338 Collection<? extends HierarchicalConfiguration<?>> configs) 1339 { 1340 Collection<ConfigurationDeclaration> declarations = 1341 new ArrayList<>(configs.size()); 1342 for (HierarchicalConfiguration<?> c : configs) 1343 { 1344 declarations.add(new ConfigurationDeclaration(this, c)); 1345 } 1346 return declarations; 1347 } 1348 1349 /** 1350 * Initializes the list nodes of the node combiner for the given combined 1351 * configuration. This information can be set in the header section of the 1352 * configuration definition file for both the override and the union 1353 * combiners. 1354 * 1355 * @param cc the combined configuration to initialize 1356 * @param defConfig the definition configuration 1357 * @param key the key for the list nodes 1358 */ 1359 private static void initNodeCombinerListNodes(CombinedConfiguration cc, 1360 HierarchicalConfiguration<?> defConfig, String key) 1361 { 1362 List<Object> listNodes = defConfig.getList(key); 1363 for (Object listNode : listNodes) 1364 { 1365 cc.getNodeCombiner().addListNode((String) listNode); 1366 } 1367 } 1368 1369 /** 1370 * Creates the map with the default configuration builder providers. 1371 * 1372 * @return the map with default providers 1373 */ 1374 private static Map<String, ConfigurationBuilderProvider> createDefaultProviders() 1375 { 1376 Map<String, ConfigurationBuilderProvider> providers = 1377 new HashMap<>(); 1378 for (int i = 0; i < DEFAULT_TAGS.length; i++) 1379 { 1380 providers.put(DEFAULT_TAGS[i], DEFAULT_PROVIDERS[i]); 1381 } 1382 return providers; 1383 } 1384 1385 static 1386 { 1387 DEFAULT_PROVIDERS_MAP = createDefaultProviders(); 1388 } 1389 1390 /** 1391 * A data class for storing information about all configuration sources 1392 * defined for a combined builder. 1393 */ 1394 private class ConfigurationSourceData 1395 { 1396 /** A list with data for all builders for override configurations. */ 1397 private final List<ConfigurationDeclaration> overrideDeclarations; 1398 1399 /** A list with data for all builders for union configurations. */ 1400 private final List<ConfigurationDeclaration> unionDeclarations; 1401 1402 /** A list with the builders for override configurations. */ 1403 private final List<ConfigurationBuilder<? extends Configuration>> overrideBuilders; 1404 1405 /** A list with the builders for union configurations. */ 1406 private final List<ConfigurationBuilder<? extends Configuration>> unionBuilders; 1407 1408 /** A map for direct access to a builder by its name. */ 1409 private final Map<String, ConfigurationBuilder<? extends Configuration>> namedBuilders; 1410 1411 /** A collection with all child builders. */ 1412 private final Collection<ConfigurationBuilder<? extends Configuration>> allBuilders; 1413 1414 /** A listener for reacting on changes of sub builders. */ 1415 private final EventListener<ConfigurationBuilderEvent> changeListener; 1416 1417 /** 1418 * Creates a new instance of {@code ConfigurationSourceData}. 1419 */ 1420 public ConfigurationSourceData() 1421 { 1422 overrideDeclarations = new ArrayList<>(); 1423 unionDeclarations = new ArrayList<>(); 1424 overrideBuilders = new ArrayList<>(); 1425 unionBuilders = new ArrayList<>(); 1426 namedBuilders = new HashMap<>(); 1427 allBuilders = new LinkedList<>(); 1428 changeListener = createBuilderChangeListener(); 1429 } 1430 1431 /** 1432 * Initializes this object from the specified definition configuration. 1433 * 1434 * @param config the definition configuration 1435 * @throws ConfigurationException if an error occurs 1436 */ 1437 public void initFromDefinitionConfiguration( 1438 HierarchicalConfiguration<?> config) throws ConfigurationException 1439 { 1440 overrideDeclarations.addAll(createDeclarations(fetchTopLevelOverrideConfigs(config))); 1441 overrideDeclarations.addAll(createDeclarations(config.childConfigurationsAt(KEY_OVERRIDE))); 1442 unionDeclarations.addAll(createDeclarations(config.childConfigurationsAt(KEY_UNION))); 1443 } 1444 1445 /** 1446 * Processes the declaration of configuration builder providers, creates 1447 * the corresponding builder if necessary, obtains configurations, and 1448 * adds them to the specified result configuration. 1449 * 1450 * @param ccResult the result configuration 1451 * @param srcDecl the collection with the declarations of configuration 1452 * sources to process 1453 * @return a list with configuration builders 1454 * @throws ConfigurationException if an error occurs 1455 */ 1456 public List<ConfigurationBuilder<? extends Configuration>> createAndAddConfigurations( 1457 CombinedConfiguration ccResult, 1458 List<ConfigurationDeclaration> srcDecl, 1459 List<ConfigurationBuilder<? extends Configuration>> builders) 1460 throws ConfigurationException 1461 { 1462 boolean createBuilders = builders.isEmpty(); 1463 List<ConfigurationBuilder<? extends Configuration>> newBuilders; 1464 if (createBuilders) 1465 { 1466 newBuilders = new ArrayList<>(srcDecl.size()); 1467 } 1468 else 1469 { 1470 newBuilders = builders; 1471 } 1472 1473 for (int i = 0; i < srcDecl.size(); i++) 1474 { 1475 ConfigurationBuilder<? extends Configuration> b; 1476 if (createBuilders) 1477 { 1478 b = createConfigurationBuilder(srcDecl.get(i)); 1479 newBuilders.add(b); 1480 } 1481 else 1482 { 1483 b = builders.get(i); 1484 } 1485 addChildConfiguration(ccResult, srcDecl.get(i), b); 1486 } 1487 1488 return newBuilders; 1489 } 1490 1491 /** 1492 * Frees resources used by this object and performs clean up. This 1493 * method is called when the owning builder is reset. 1494 */ 1495 public void cleanUp() 1496 { 1497 for (ConfigurationBuilder<?> b : getChildBuilders()) 1498 { 1499 b.removeEventListener(ConfigurationBuilderEvent.RESET, 1500 changeListener); 1501 } 1502 namedBuilders.clear(); 1503 } 1504 1505 /** 1506 * Returns a collection containing the builders for all child 1507 * configuration sources. 1508 * 1509 * @return the child configuration builders 1510 */ 1511 public Collection<ConfigurationBuilder<? extends Configuration>> getChildBuilders() 1512 { 1513 return allBuilders; 1514 } 1515 1516 /** 1517 * Returns a collection with all configuration source declarations 1518 * defined in the override section. 1519 * 1520 * @return the override configuration builders 1521 */ 1522 public List<ConfigurationDeclaration> getOverrideSources() 1523 { 1524 return overrideDeclarations; 1525 } 1526 1527 /** 1528 * Returns a collection with all configuration source declarations 1529 * defined in the union section. 1530 * 1531 * @return the union configuration builders 1532 */ 1533 public List<ConfigurationDeclaration> getUnionSources() 1534 { 1535 return unionDeclarations; 1536 } 1537 1538 /** 1539 * Returns the {@code ConfigurationBuilder} with the given name. If no 1540 * such builder is defined in the definition configuration, result is 1541 * <b>null</b>. 1542 * 1543 * @param name the name of the builder in question 1544 * @return the builder with this name or <b>null</b> 1545 */ 1546 public ConfigurationBuilder<? extends Configuration> getNamedBuilder( 1547 String name) 1548 { 1549 return namedBuilders.get(name); 1550 } 1551 1552 /** 1553 * Returns a set with the names of all known named builders. 1554 * 1555 * @return the names of the available sub builders 1556 */ 1557 public Set<String> builderNames() 1558 { 1559 return namedBuilders.keySet(); 1560 } 1561 1562 /** 1563 * Creates a configuration builder based on a source declaration in the 1564 * definition configuration. 1565 * 1566 * @param decl the current {@code ConfigurationDeclaration} 1567 * @return the newly created builder 1568 * @throws ConfigurationException if an error occurs 1569 */ 1570 private ConfigurationBuilder<? extends Configuration> createConfigurationBuilder( 1571 ConfigurationDeclaration decl) throws ConfigurationException 1572 { 1573 ConfigurationBuilderProvider provider = 1574 providerForTag(decl.getConfiguration().getRootElementName()); 1575 if (provider == null) 1576 { 1577 throw new ConfigurationException( 1578 "Unsupported configuration source: " 1579 + decl.getConfiguration().getRootElementName()); 1580 } 1581 1582 ConfigurationBuilder<? extends Configuration> builder = 1583 provider.getConfigurationBuilder(decl); 1584 if (decl.getName() != null) 1585 { 1586 namedBuilders.put(decl.getName(), builder); 1587 } 1588 allBuilders.add(builder); 1589 builder.addEventListener(ConfigurationBuilderEvent.RESET, 1590 changeListener); 1591 return builder; 1592 } 1593 1594 /** 1595 * Creates a new configuration using the specified builder and adds it 1596 * to the resulting combined configuration. 1597 * 1598 * @param ccResult the resulting combined configuration 1599 * @param decl the current {@code ConfigurationDeclaration} 1600 * @param builder the configuration builder 1601 * @throws ConfigurationException if an error occurs 1602 */ 1603 private void addChildConfiguration(CombinedConfiguration ccResult, 1604 ConfigurationDeclaration decl, 1605 ConfigurationBuilder<? extends Configuration> builder) 1606 throws ConfigurationException 1607 { 1608 try 1609 { 1610 ccResult.addConfiguration( 1611 builder.getConfiguration(), 1612 decl.getName(), decl.getAt()); 1613 } 1614 catch (ConfigurationException cex) 1615 { 1616 // ignore exceptions for optional configurations 1617 if (!decl.isOptional()) 1618 { 1619 throw cex; 1620 } 1621 } 1622 } 1623 1624 /** 1625 * Creates a listener for builder change events. This listener is 1626 * registered at all builders for child configurations. 1627 */ 1628 private EventListener<ConfigurationBuilderEvent> createBuilderChangeListener() 1629 { 1630 return new EventListener<ConfigurationBuilderEvent>() 1631 { 1632 @Override 1633 public void onEvent(ConfigurationBuilderEvent event) 1634 { 1635 resetResult(); 1636 } 1637 }; 1638 } 1639 1640 /** 1641 * Finds the override configurations that are defined as top level 1642 * elements in the configuration definition file. This method fetches 1643 * the child elements of the root node and removes the nodes that 1644 * represent other configuration sections. The remaining nodes are 1645 * treated as definitions for override configurations. 1646 * 1647 * @param config the definition configuration 1648 * @return a list with sub configurations for the top level override 1649 * configurations 1650 */ 1651 private List<? extends HierarchicalConfiguration<?>> fetchTopLevelOverrideConfigs( 1652 HierarchicalConfiguration<?> config) 1653 { 1654 1655 List<? extends HierarchicalConfiguration<?>> configs = 1656 config.childConfigurationsAt(null); 1657 for (Iterator<? extends HierarchicalConfiguration<?>> it = 1658 configs.iterator(); it.hasNext();) 1659 { 1660 String nodeName = it.next().getRootElementName(); 1661 for (String element : CONFIG_SECTIONS) 1662 { 1663 if (element.equals(nodeName)) 1664 { 1665 it.remove(); 1666 break; 1667 } 1668 } 1669 } 1670 return configs; 1671 } 1672 } 1673}