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