001/** 002 * Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com> 003 */ 004package com.typesafe.config; 005 006import com.typesafe.config.impl.ConfigImpl; 007import com.typesafe.config.impl.Parseable; 008 009import java.io.File; 010import java.io.Reader; 011import java.net.MalformedURLException; 012import java.net.URL; 013import java.util.Map; 014import java.util.Optional; 015import java.util.Properties; 016import java.util.concurrent.Callable; 017 018/** 019 * Contains static methods for creating {@link Config} instances. 020 * 021 * <p> 022 * See also {@link ConfigValueFactory} which contains static methods for 023 * converting Java values into a {@link ConfigObject}. You can then convert a 024 * {@code ConfigObject} into a {@code Config} with {@link ConfigObject#toConfig}. 025 * 026 * <p> 027 * The static methods with "load" in the name do some sort of higher-level 028 * operation potentially parsing multiple resources and resolving substitutions, 029 * while the ones with "parse" in the name just create a {@link ConfigValue} 030 * from a resource and nothing else. 031 * 032 * <p> You can find an example app and library <a 033 * href="https://github.com/lightbend/config/tree/master/examples">on 034 * GitHub</a>. Also be sure to read the <a 035 * href="package-summary.html#package_description">package 036 * overview</a> which describes the big picture as shown in those 037 * examples. 038 */ 039public final class ConfigFactory { 040 private static final String STRATEGY_PROPERTY_NAME = "config.strategy"; 041 private static final String OVERRIDE_WITH_ENV_PROPERTY_NAME = "config.override_with_env_vars"; 042 043 private ConfigFactory() { 044 } 045 046 /** 047 * Loads an application's configuration from the given classpath resource or 048 * classpath resource basename, sandwiches it between default reference 049 * config and default overrides, and then resolves it. The classpath 050 * resource is "raw" (it should have no "/" prefix, and is not made relative 051 * to any package, so it's like {@link ClassLoader#getResource} not 052 * {@link Class#getResource}). 053 * 054 * <p> 055 * Resources are loaded from the current thread's 056 * {@link Thread#getContextClassLoader()}. In general, a library needs its 057 * configuration to come from the class loader used to load that library, so 058 * the proper "reference.conf" are present. 059 * 060 * <p> 061 * The loaded object will already be resolved (substitutions have already 062 * been processed). As a result, if you add more fallbacks then they won't 063 * be seen by substitutions. Substitutions are the "${foo.bar}" syntax. If 064 * you want to parse additional files or something then you need to use 065 * {@link #load(Config)}. 066 * 067 * <p> 068 * To load a standalone resource (without the default reference and default 069 * overrides), use {@link #parseResourcesAnySyntax(String)} rather than this 070 * method. To load only the reference config use {@link #defaultReference()} 071 * and to load only the overrides use {@link #defaultOverrides()}. 072 * 073 * @param resourceBasename 074 * name (optionally without extension) of a resource on classpath 075 * @return configuration for an application relative to context class loader 076 */ 077 public static Config load(String resourceBasename) { 078 return load(resourceBasename, ConfigParseOptions.defaults(), 079 ConfigResolveOptions.defaults()); 080 } 081 082 /** 083 * Like {@link #load(String)} but uses the supplied class loader instead of 084 * the current thread's context class loader. 085 * 086 * <p> 087 * To load a standalone resource (without the default reference and default 088 * overrides), use {@link #parseResourcesAnySyntax(ClassLoader, String)} 089 * rather than this method. To load only the reference config use 090 * {@link #defaultReference(ClassLoader)} and to load only the overrides use 091 * {@link #defaultOverrides(ClassLoader)}. 092 * 093 * @param loader class loader to look for resources in 094 * @param resourceBasename basename (no .conf/.json/.properties suffix) 095 * @return configuration for an application relative to given class loader 096 */ 097 public static Config load(ClassLoader loader, String resourceBasename) { 098 return load(resourceBasename, ConfigParseOptions.defaults().setClassLoader(loader), 099 ConfigResolveOptions.defaults()); 100 } 101 102 /** 103 * Like {@link #load(String)} but allows you to specify parse and resolve 104 * options. 105 * 106 * @param resourceBasename 107 * the classpath resource name with optional extension 108 * @param parseOptions 109 * options to use when parsing the resource 110 * @param resolveOptions 111 * options to use when resolving the stack 112 * @return configuration for an application 113 */ 114 public static Config load(String resourceBasename, ConfigParseOptions parseOptions, 115 ConfigResolveOptions resolveOptions) { 116 ConfigParseOptions withLoader = ensureClassLoader(parseOptions, "load"); 117 Config appConfig = ConfigFactory.parseResourcesAnySyntax(resourceBasename, withLoader); 118 return load(withLoader.getClassLoader(), appConfig, resolveOptions); 119 } 120 121 /** 122 * Like {@link #load(String,ConfigParseOptions,ConfigResolveOptions)} but 123 * has a class loader parameter that overrides any from the 124 * {@code ConfigParseOptions}. 125 * 126 * @param loader 127 * class loader in which to find resources (overrides loader in 128 * parse options) 129 * @param resourceBasename 130 * the classpath resource name with optional extension 131 * @param parseOptions 132 * options to use when parsing the resource (class loader 133 * overridden) 134 * @param resolveOptions 135 * options to use when resolving the stack 136 * @return configuration for an application 137 */ 138 public static Config load(ClassLoader loader, String resourceBasename, 139 ConfigParseOptions parseOptions, ConfigResolveOptions resolveOptions) { 140 return load(resourceBasename, parseOptions.setClassLoader(loader), resolveOptions); 141 } 142 143 private static ClassLoader checkedContextClassLoader(String methodName) { 144 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 145 if (loader == null) 146 throw new ConfigException.BugOrBroken("Context class loader is not set for the current thread; " 147 + "if Thread.currentThread().getContextClassLoader() returns null, you must pass a ClassLoader " 148 + "explicitly to ConfigFactory." + methodName); 149 else 150 return loader; 151 } 152 153 private static ConfigParseOptions ensureClassLoader(ConfigParseOptions options, String methodName) { 154 if (options.getClassLoader() == null) 155 return options.setClassLoader(checkedContextClassLoader(methodName)); 156 else 157 return options; 158 } 159 160 /** 161 * Assembles a standard configuration using a custom <code>Config</code> 162 * object rather than loading "application.conf". The <code>Config</code> 163 * object will be sandwiched between the default reference config and 164 * default overrides and then resolved. 165 * 166 * @param config 167 * the application's portion of the configuration 168 * @return resolved configuration with overrides and fallbacks added 169 */ 170 public static Config load(Config config) { 171 return load(checkedContextClassLoader("load"), config); 172 } 173 174 /** 175 * Like {@link #load(Config)} but allows you to specify 176 * the class loader for looking up resources. 177 * 178 * @param loader 179 * the class loader to use to find resources 180 * @param config 181 * the application's portion of the configuration 182 * @return resolved configuration with overrides and fallbacks added 183 */ 184 public static Config load(ClassLoader loader, Config config) { 185 return load(loader, config, ConfigResolveOptions.defaults()); 186 } 187 188 /** 189 * Like {@link #load(Config)} but allows you to specify 190 * {@link ConfigResolveOptions}. 191 * 192 * @param config 193 * the application's portion of the configuration 194 * @param resolveOptions 195 * options for resolving the assembled config stack 196 * @return resolved configuration with overrides and fallbacks added 197 */ 198 public static Config load(Config config, ConfigResolveOptions resolveOptions) { 199 return load(checkedContextClassLoader("load"), config, resolveOptions); 200 } 201 202 /** 203 * Like {@link #load(Config,ConfigResolveOptions)} but allows you to specify 204 * a class loader other than the context class loader. 205 * 206 * @param loader 207 * class loader to use when looking up override and reference 208 * configs 209 * @param config 210 * the application's portion of the configuration 211 * @param resolveOptions 212 * options for resolving the assembled config stack 213 * @return resolved configuration with overrides and fallbacks added 214 */ 215 public static Config load(ClassLoader loader, Config config, ConfigResolveOptions resolveOptions) { 216 return defaultOverrides(loader).withFallback(config) 217 .withFallback(ConfigImpl.defaultReferenceUnresolved(loader)) 218 .resolve(resolveOptions); 219 } 220 221 222 223 /** 224 * Loads a default configuration, equivalent to {@link #load(Config) 225 * load(defaultApplication())} in most cases. This configuration should be used by 226 * libraries and frameworks unless an application provides a different one. 227 * <p> 228 * This method may return a cached singleton so will not see changes to 229 * system properties or config files. (Use {@link #invalidateCaches()} to 230 * force it to reload.) 231 * 232 * @return configuration for an application 233 */ 234 public static Config load() { 235 ClassLoader loader = checkedContextClassLoader("load"); 236 return load(loader); 237 } 238 239 /** 240 * Like {@link #load()} but allows specifying parse options. 241 * 242 * @param parseOptions 243 * Options for parsing resources 244 * @return configuration for an application 245 */ 246 public static Config load(ConfigParseOptions parseOptions) { 247 return load(parseOptions, ConfigResolveOptions.defaults()); 248 } 249 250 /** 251 * Like {@link #load()} but allows specifying a class loader other than the 252 * thread's current context class loader. 253 * 254 * @param loader 255 * class loader for finding resources 256 * @return configuration for an application 257 */ 258 public static Config load(final ClassLoader loader) { 259 final ConfigParseOptions withLoader = ConfigParseOptions.defaults().setClassLoader(loader); 260 return ConfigImpl.computeCachedConfig(loader, "load", new Callable<Config>() { 261 @Override 262 public Config call() { 263 return load(loader, defaultApplication(withLoader)); 264 } 265 }); 266 } 267 268 /** 269 * Like {@link #load()} but allows specifying a class loader other than the 270 * thread's current context class loader and also specify parse options. 271 * 272 * @param loader 273 * class loader for finding resources (overrides any loader in parseOptions) 274 * @param parseOptions 275 * Options for parsing resources 276 * @return configuration for an application 277 */ 278 public static Config load(ClassLoader loader, ConfigParseOptions parseOptions) { 279 return load(parseOptions.setClassLoader(loader)); 280 } 281 282 /** 283 * Like {@link #load()} but allows specifying a class loader other than the 284 * thread's current context class loader and also specify resolve options. 285 * 286 * @param loader 287 * class loader for finding resources 288 * @param resolveOptions 289 * options for resolving the assembled config stack 290 * @return configuration for an application 291 */ 292 public static Config load(ClassLoader loader, ConfigResolveOptions resolveOptions) { 293 return load(loader, ConfigParseOptions.defaults(), resolveOptions); 294 } 295 296 297 /** 298 * Like {@link #load()} but allows specifying a class loader other than the 299 * thread's current context class loader, parse options, and resolve options. 300 * 301 * @param loader 302 * class loader for finding resources (overrides any loader in parseOptions) 303 * @param parseOptions 304 * Options for parsing resources 305 * @param resolveOptions 306 * options for resolving the assembled config stack 307 * @return configuration for an application 308 */ 309 public static Config load(ClassLoader loader, ConfigParseOptions parseOptions, ConfigResolveOptions resolveOptions) { 310 final ConfigParseOptions withLoader = ensureClassLoader(parseOptions, "load"); 311 return load(loader, defaultApplication(withLoader), resolveOptions); 312 } 313 314 /** 315 * Like {@link #load()} but allows specifying parse options and resolve 316 * options. 317 * 318 * @param parseOptions 319 * Options for parsing resources 320 * @param resolveOptions 321 * options for resolving the assembled config stack 322 * @return configuration for an application 323 * 324 * @since 1.3.0 325 */ 326 public static Config load(ConfigParseOptions parseOptions, final ConfigResolveOptions resolveOptions) { 327 final ConfigParseOptions withLoader = ensureClassLoader(parseOptions, "load"); 328 return load(defaultApplication(withLoader), resolveOptions); 329 } 330 331 /** 332 * Obtains the default reference configuration, which is currently created 333 * by merging all resources "reference.conf" found on the classpath and 334 * overriding the result with system properties. The returned reference 335 * configuration will already have substitutions resolved. 336 * 337 * <p> 338 * Libraries and frameworks should ship with a "reference.conf" in their 339 * jar. 340 * 341 * <p> 342 * The reference config must be looked up in the class loader that contains 343 * the libraries that you want to use with this config, so the 344 * "reference.conf" for each library can be found. Use 345 * {@link #defaultReference(ClassLoader)} if the context class loader is not 346 * suitable. 347 * 348 * <p> 349 * The {@link #load()} methods merge this configuration for you 350 * automatically. 351 * 352 * <p> 353 * Future versions may look for reference configuration in more places. It 354 * is not guaranteed that this method <em>only</em> looks at 355 * "reference.conf". 356 * 357 * @return the default reference config for context class loader 358 */ 359 public static Config defaultReference() { 360 return defaultReference(checkedContextClassLoader("defaultReference")); 361 } 362 363 /** 364 * Like {@link #defaultReference()} but allows you to specify a class loader 365 * to use rather than the current context class loader. 366 * 367 * @param loader class loader to look for resources in 368 * @return the default reference config for this class loader 369 */ 370 public static Config defaultReference(ClassLoader loader) { 371 return ConfigImpl.defaultReference(loader); 372 } 373 374 /** 375 * Obtains the default reference configuration, which is currently created 376 * by merging all resources "reference.conf" found on the classpath and 377 * overriding the result with system properties. 378 * 379 * <p> 380 * While the returned reference configuration is guaranteed to be 381 * resolvable (that is, there will be no substitutions that cannot be 382 * resolved), it is returned in an unresolved state for the purpose of 383 * allowing substitutions to be overridden by a config layer that falls 384 * back to this one. 385 * 386 * <p> 387 * Libraries and frameworks should ship with a "reference.conf" in their 388 * jar. 389 * 390 * <p> 391 * The reference config must be looked up in the class loader that contains 392 * the libraries that you want to use with this config, so the 393 * "reference.conf" for each library can be found. Use 394 * {@link #defaultReference(ClassLoader)} if the context class loader is not 395 * suitable. 396 * 397 * <p> 398 * The {@link #load()} methods merge this configuration for you 399 * automatically. 400 * 401 * <p> 402 * Future versions may look for reference configuration in more places. It 403 * is not guaranteed that this method <em>only</em> looks at 404 * "reference.conf". 405 * 406 * @return the unresolved default reference config for the context class 407 * loader 408 */ 409 public static Config defaultReferenceUnresolved() { 410 return defaultReferenceUnresolved(checkedContextClassLoader("defaultReferenceUnresolved")); 411 } 412 413 /** 414 * Like {@link #defaultReferenceUnresolved()} but allows you to specify a 415 * class loader to use rather than the current context class loader. 416 * 417 * @param loader class loader to look for resources in 418 * @return the unresolved default reference config for this class loader 419 */ 420 public static Config defaultReferenceUnresolved(ClassLoader loader) { 421 return ConfigImpl.defaultReferenceUnresolved(loader); 422 } 423 424 /** 425 * Obtains the default override configuration, which currently consists of 426 * system properties. The returned override configuration will already have 427 * substitutions resolved. 428 * 429 * <p> 430 * The {@link #load()} methods merge this configuration for you 431 * automatically. 432 * 433 * <p> 434 * Future versions may get overrides in more places. It is not guaranteed 435 * that this method <em>only</em> uses system properties. 436 * 437 * @return the default override configuration 438 */ 439 public static Config defaultOverrides() { 440 if (getOverrideWithEnv()) { 441 return systemEnvironmentOverrides().withFallback(systemProperties()); 442 } else { 443 return systemProperties(); 444 } 445 } 446 447 /** 448 * Like {@link #defaultOverrides()} but allows you to specify a class loader 449 * to use rather than the current context class loader. 450 * 451 * @param loader class loader to look for resources in 452 * @return the default override configuration 453 */ 454 public static Config defaultOverrides(ClassLoader loader) { 455 return defaultOverrides(); 456 } 457 458 /** 459 * Obtains the default application-specific configuration, 460 * which defaults to parsing <code>application.conf</code>, 461 * <code>application.json</code>, and 462 * <code>application.properties</code> on the classpath, but 463 * can also be rerouted using the <code>config.file</code>, 464 * <code>config.resource</code>, and <code>config.url</code> 465 * system properties. 466 * 467 * <p> The no-arguments {@link #load()} method automatically 468 * stacks the {@link #defaultReference()}, {@link 469 * #defaultApplication()}, and {@link #defaultOverrides()} 470 * configs. You would use <code>defaultApplication()</code> 471 * directly only if you're somehow customizing behavior by 472 * reimplementing <code>load()</code>. 473 * 474 * <p>The configuration returned by 475 * <code>defaultApplication()</code> will not be resolved 476 * already, in contrast to <code>defaultReference()</code> and 477 * <code>defaultOverrides()</code>. This is because 478 * application.conf would normally be resolved <em>after</em> 479 * merging with the reference and override configs. 480 * 481 * <p> 482 * If the system properties <code>config.resource</code>, 483 * <code>config.file</code>, or <code>config.url</code> are set, then the 484 * classpath resource, file, or URL specified in those properties will be 485 * used rather than the default 486 * <code>application.{conf,json,properties}</code> classpath resources. 487 * These system properties should not be set in code (after all, you can 488 * just parse whatever you want manually and then use {@link #load(Config)} 489 * if you don't want to use <code>application.conf</code>). The properties 490 * are intended for use by the person or script launching the application. 491 * For example someone might have a <code>production.conf</code> that 492 * include <code>application.conf</code> but then change a couple of values. 493 * When launching the app they could specify 494 * <code>-Dconfig.resource=production.conf</code> to get production mode. 495 * 496 * <p> 497 * If no system properties are set to change the location of the default 498 * configuration, <code>defaultApplication()</code> is equivalent to 499 * <code>ConfigFactory.parseResources("application")</code>. 500 * 501 * @since 1.3.0 502 * 503 * @return the default application.conf or system-property-configured configuration 504 */ 505 public static Config defaultApplication() { 506 return defaultApplication(ConfigParseOptions.defaults()); 507 } 508 509 /** 510 * Like {@link #defaultApplication()} but allows you to specify a class loader 511 * to use rather than the current context class loader. 512 * 513 * @since 1.3.0 514 * 515 * @param loader class loader to look for resources in 516 * @return the default application configuration 517 */ 518 public static Config defaultApplication(ClassLoader loader) { 519 return defaultApplication(ConfigParseOptions.defaults().setClassLoader(loader)); 520 } 521 522 /** 523 * Like {@link #defaultApplication()} but allows you to specify parse options. 524 * 525 * @since 1.3.0 526 * 527 * @param options the options 528 * @return the default application configuration 529 */ 530 public static Config defaultApplication(ConfigParseOptions options) { 531 return getConfigLoadingStrategy().parseApplicationConfig(ensureClassLoader(options, "defaultApplication")); 532 } 533 534 /** 535 * Reloads any cached configs, picking up changes to system properties for 536 * example. Because a {@link Config} is immutable, anyone with a reference 537 * to the old configs will still have the same outdated objects. However, 538 * new calls to {@link #load()} or {@link #defaultOverrides()} or 539 * {@link #defaultReference} may return a new object. 540 * <p> 541 * This method is primarily intended for use in unit tests, for example, 542 * that may want to update a system property then confirm that it's used 543 * correctly. In many cases, use of this method may indicate there's a 544 * better way to set up your code. 545 * <p> 546 * Caches may be reloaded immediately or lazily; once you call this method, 547 * the reload can occur at any time, even during the invalidation process. 548 * So FIRST make the changes you'd like the caches to notice, then SECOND 549 * call this method to invalidate caches. Don't expect that invalidating, 550 * making changes, then calling {@link #load()}, will work. Make changes 551 * before you invalidate. 552 */ 553 public static void invalidateCaches() { 554 // We rely on this having the side effect that it drops 555 // all caches 556 ConfigImpl.reloadSystemPropertiesConfig(); 557 ConfigImpl.reloadEnvVariablesConfig(); 558 ConfigImpl.reloadEnvVariablesOverridesConfig(); 559 } 560 561 /** 562 * Gets an empty configuration. See also {@link #empty(String)} to create an 563 * empty configuration with a description, which may improve user-visible 564 * error messages. 565 * 566 * @return an empty configuration 567 */ 568 public static Config empty() { 569 return empty(null); 570 } 571 572 /** 573 * Gets an empty configuration with a description to be used to create a 574 * {@link ConfigOrigin} for this <code>Config</code>. The description should 575 * be very short and say what the configuration is, like "default settings" 576 * or "foo settings" or something. (Presumably you will merge some actual 577 * settings into this empty config using {@link Config#withFallback}, making 578 * the description more useful.) 579 * 580 * @param originDescription 581 * description of the config 582 * @return an empty configuration 583 */ 584 public static Config empty(String originDescription) { 585 return ConfigImpl.emptyConfig(originDescription); 586 } 587 588 /** 589 * Gets a <code>Config</code> containing the system properties from 590 * {@link java.lang.System#getProperties()}, parsed and converted as with 591 * {@link #parseProperties}. 592 * <p> 593 * This method can return a global immutable singleton, so it's preferred 594 * over parsing system properties yourself. 595 * <p> 596 * {@link #load} will include the system properties as overrides already, as 597 * will {@link #defaultReference} and {@link #defaultOverrides}. 598 * 599 * <p> 600 * Because this returns a singleton, it will not notice changes to system 601 * properties made after the first time this method is called. Use 602 * {@link #invalidateCaches()} to force the singleton to reload if you 603 * modify system properties. 604 * 605 * @return system properties parsed into a <code>Config</code> 606 */ 607 public static Config systemProperties() { 608 return ConfigImpl.systemPropertiesAsConfig(); 609 } 610 611 /** 612 * Gets a <code>Config</code> containing the system's environment variables 613 * used to override configuration keys. 614 * Environment variables taken in considerations are starting with 615 * {@code CONFIG_FORCE_} 616 * 617 * <p> 618 * Environment variables are mangled in the following way after stripping the prefix "CONFIG_FORCE_": 619 * <table border="1"> 620 * <tr> 621 * <th bgcolor="silver">Env Var</th> 622 * <th bgcolor="silver">Config</th> 623 * </tr> 624 * <tr> 625 * <td>_ [1 underscore]</td> 626 * <td>. [dot]</td> 627 * </tr> 628 * <tr> 629 * <td>__ [2 underscore]</td> 630 * <td>- [dash]</td> 631 * </tr> 632 * <tr> 633 * <td>___ [3 underscore]</td> 634 * <td>_ [underscore]</td> 635 * </tr> 636 * </table> 637 * 638 * <p> 639 * A variable like: {@code CONFIG_FORCE_a_b__c___d} 640 * is translated to a config key: {@code a.b-c_d} 641 * 642 * <p> 643 * This method can return a global immutable singleton, so it's preferred 644 * over parsing system properties yourself. 645 * <p> 646 * {@link #defaultOverrides} will include the system environment variables as 647 * overrides if `config.override_with_env_vars` is set to `true`. 648 * 649 * @return system environment variable overrides parsed into a <code>Config</code> 650 */ 651 public static Config systemEnvironmentOverrides() { 652 return ConfigImpl.envVariablesOverridesAsConfig(); 653 } 654 655 /** 656 * Gets a <code>Config</code> containing the system's environment variables. 657 * This method can return a global immutable singleton. 658 * 659 * <p> 660 * Environment variables are used as fallbacks when resolving substitutions 661 * whether or not this object is included in the config being resolved, so 662 * you probably don't need to use this method for most purposes. It can be a 663 * nicer API for accessing environment variables than raw 664 * {@link java.lang.System#getenv(String)} though, since you can use methods 665 * such as {@link Config#getInt}. 666 * 667 * @return system environment variables parsed into a <code>Config</code> 668 */ 669 public static Config systemEnvironment() { 670 return ConfigImpl.envVariablesAsConfig(); 671 } 672 673 /** 674 * Converts a Java {@link java.util.Properties} object to a 675 * {@link ConfigObject} using the rules documented in the <a 676 * href="https://github.com/lightbend/config/blob/master/HOCON.md">HOCON 677 * spec</a>. The keys in the <code>Properties</code> object are split on the 678 * period character '.' and treated as paths. The values will all end up as 679 * string values. If you have both "a=foo" and "a.b=bar" in your properties 680 * file, so "a" is both the object containing "b" and the string "foo", then 681 * the string value is dropped. 682 * 683 * <p> 684 * If you want to have <code>System.getProperties()</code> as a 685 * ConfigObject, it's better to use the {@link #systemProperties()} method 686 * which returns a cached global singleton. 687 * 688 * @param properties 689 * a Java Properties object 690 * @param options 691 * the parse options 692 * @return the parsed configuration 693 */ 694 public static Config parseProperties(Properties properties, 695 ConfigParseOptions options) { 696 return Parseable.newProperties(properties, options).parse().toConfig(); 697 } 698 699 /** 700 * Like {@link #parseProperties(Properties, ConfigParseOptions)} but uses default 701 * parse options. 702 * @param properties 703 * a Java Properties object 704 * @return the parsed configuration 705 */ 706 public static Config parseProperties(Properties properties) { 707 return parseProperties(properties, ConfigParseOptions.defaults()); 708 } 709 710 /** 711 * Parses a Reader into a Config instance. Does not call 712 * {@link Config#resolve} or merge the parsed stream with any 713 * other configuration; this method parses a single stream and 714 * does nothing else. It does process "include" statements in 715 * the parsed stream, and may end up doing other IO due to those 716 * statements. 717 * 718 * @param reader 719 * the reader to parse 720 * @param options 721 * parse options to control how the reader is interpreted 722 * @return the parsed configuration 723 * @throws ConfigException on IO or parse errors 724 */ 725 public static Config parseReader(Reader reader, ConfigParseOptions options) { 726 return Parseable.newReader(reader, options).parse().toConfig(); 727 } 728 729 /** 730 * Parses a reader into a Config instance as with 731 * {@link #parseReader(Reader,ConfigParseOptions)} but always uses the 732 * default parse options. 733 * 734 * @param reader 735 * the reader to parse 736 * @return the parsed configuration 737 * @throws ConfigException on IO or parse errors 738 */ 739 public static Config parseReader(Reader reader) { 740 return parseReader(reader, ConfigParseOptions.defaults()); 741 } 742 743 /** 744 * Parses a URL into a Config instance. Does not call 745 * {@link Config#resolve} or merge the parsed stream with any 746 * other configuration; this method parses a single stream and 747 * does nothing else. It does process "include" statements in 748 * the parsed stream, and may end up doing other IO due to those 749 * statements. 750 * 751 * @param url 752 * the url to parse 753 * @param options 754 * parse options to control how the url is interpreted 755 * @return the parsed configuration 756 * @throws ConfigException on IO or parse errors 757 */ 758 public static Config parseURL(URL url, ConfigParseOptions options) { 759 return Parseable.newURL(url, options).parse().toConfig(); 760 } 761 762 /** 763 * Parses a url into a Config instance as with 764 * {@link #parseURL(URL,ConfigParseOptions)} but always uses the 765 * default parse options. 766 * 767 * @param url 768 * the url to parse 769 * @return the parsed configuration 770 * @throws ConfigException on IO or parse errors 771 */ 772 public static Config parseURL(URL url) { 773 return parseURL(url, ConfigParseOptions.defaults()); 774 } 775 776 /** 777 * Parses a file into a Config instance. Does not call 778 * {@link Config#resolve} or merge the file with any other 779 * configuration; this method parses a single file and does 780 * nothing else. It does process "include" statements in the 781 * parsed file, and may end up doing other IO due to those 782 * statements. 783 * 784 * @param file 785 * the file to parse 786 * @param options 787 * parse options to control how the file is interpreted 788 * @return the parsed configuration 789 * @throws ConfigException on IO or parse errors 790 */ 791 public static Config parseFile(File file, ConfigParseOptions options) { 792 return Parseable.newFile(file, options).parse().toConfig(); 793 } 794 795 /** 796 * Parses a file into a Config instance as with 797 * {@link #parseFile(File,ConfigParseOptions)} but always uses the 798 * default parse options. 799 * 800 * @param file 801 * the file to parse 802 * @return the parsed configuration 803 * @throws ConfigException on IO or parse errors 804 */ 805 public static Config parseFile(File file) { 806 return parseFile(file, ConfigParseOptions.defaults()); 807 } 808 809 /** 810 * Parses a file with a flexible extension. If the <code>fileBasename</code> 811 * already ends in a known extension, this method parses it according to 812 * that extension (the file's syntax must match its extension). If the 813 * <code>fileBasename</code> does not end in an extension, it parses files 814 * with all known extensions and merges whatever is found. 815 * 816 * <p> 817 * In the current implementation, the extension ".conf" forces 818 * {@link ConfigSyntax#CONF}, ".json" forces {@link ConfigSyntax#JSON}, and 819 * ".properties" forces {@link ConfigSyntax#PROPERTIES}. When merging files, 820 * ".conf" falls back to ".json" falls back to ".properties". 821 * 822 * <p> 823 * Future versions of the implementation may add additional syntaxes or 824 * additional extensions. However, the ordering (fallback priority) of the 825 * three current extensions will remain the same. 826 * 827 * <p> 828 * If <code>options</code> forces a specific syntax, this method only parses 829 * files with an extension matching that syntax. 830 * 831 * <p> 832 * If {@link ConfigParseOptions#getAllowMissing options.getAllowMissing()} 833 * is true, then no files have to exist; if false, then at least one file 834 * has to exist. 835 * 836 * @param fileBasename 837 * a filename with or without extension 838 * @param options 839 * parse options 840 * @return the parsed configuration 841 */ 842 public static Config parseFileAnySyntax(File fileBasename, 843 ConfigParseOptions options) { 844 return ConfigImpl.parseFileAnySyntax(fileBasename, options).toConfig(); 845 } 846 847 /** 848 * Like {@link #parseFileAnySyntax(File,ConfigParseOptions)} but always uses 849 * default parse options. 850 * 851 * @param fileBasename 852 * a filename with or without extension 853 * @return the parsed configuration 854 */ 855 public static Config parseFileAnySyntax(File fileBasename) { 856 return parseFileAnySyntax(fileBasename, ConfigParseOptions.defaults()); 857 } 858 859 /** 860 * Parses all resources on the classpath with the given name and merges them 861 * into a single <code>Config</code>. 862 * 863 * <p> 864 * If the resource name does not begin with a "/", it will have the supplied 865 * class's package added to it, in the same way as 866 * {@link java.lang.Class#getResource}. 867 * 868 * <p> 869 * Duplicate resources with the same name are merged such that ones returned 870 * earlier from {@link ClassLoader#getResources} fall back to (have higher 871 * priority than) the ones returned later. This implies that resources 872 * earlier in the classpath override those later in the classpath when they 873 * configure the same setting. However, in practice real applications may 874 * not be consistent about classpath ordering, so be careful. It may be best 875 * to avoid assuming too much. 876 * 877 * @param klass 878 * <code>klass.getClassLoader()</code> will be used to load 879 * resources, and non-absolute resource names will have this 880 * class's package added 881 * @param resource 882 * resource to look up, relative to <code>klass</code>'s package 883 * or absolute starting with a "/" 884 * @param options 885 * parse options 886 * @return the parsed configuration 887 */ 888 public static Config parseResources(Class<?> klass, String resource, 889 ConfigParseOptions options) { 890 return Parseable.newResources(klass, resource, options).parse() 891 .toConfig(); 892 } 893 894 /** 895 * Like {@link #parseResources(Class,String,ConfigParseOptions)} but always uses 896 * default parse options. 897 * 898 * @param klass 899 * <code>klass.getClassLoader()</code> will be used to load 900 * resources, and non-absolute resource names will have this 901 * class's package added 902 * @param resource 903 * resource to look up, relative to <code>klass</code>'s package 904 * or absolute starting with a "/" 905 * @return the parsed configuration 906 */ 907 public static Config parseResources(Class<?> klass, String resource) { 908 return parseResources(klass, resource, ConfigParseOptions.defaults()); 909 } 910 911 /** 912 * Parses classpath resources with a flexible extension. In general, this 913 * method has the same behavior as 914 * {@link #parseFileAnySyntax(File,ConfigParseOptions)} but for classpath 915 * resources instead, as in {@link #parseResources}. 916 * 917 * <p> 918 * There is a thorny problem with this method, which is that 919 * {@link java.lang.ClassLoader#getResources} must be called separately for 920 * each possible extension. The implementation ends up with separate lists 921 * of resources called "basename.conf" and "basename.json" for example. As a 922 * result, the ideal ordering between two files with different extensions is 923 * unknown; there is no way to figure out how to merge the two lists in 924 * classpath order. To keep it simple, the lists are simply concatenated, 925 * with the same syntax priorities as 926 * {@link #parseFileAnySyntax(File,ConfigParseOptions) parseFileAnySyntax()} 927 * - all ".conf" resources are ahead of all ".json" resources which are 928 * ahead of all ".properties" resources. 929 * 930 * @param klass 931 * class which determines the <code>ClassLoader</code> and the 932 * package for relative resource names 933 * @param resourceBasename 934 * a resource name as in {@link java.lang.Class#getResource}, 935 * with or without extension 936 * @param options 937 * parse options (class loader is ignored in favor of the one 938 * from klass) 939 * @return the parsed configuration 940 */ 941 public static Config parseResourcesAnySyntax(Class<?> klass, String resourceBasename, 942 ConfigParseOptions options) { 943 return ConfigImpl.parseResourcesAnySyntax(klass, resourceBasename, 944 options).toConfig(); 945 } 946 947 /** 948 * Like {@link #parseResourcesAnySyntax(Class,String,ConfigParseOptions)} 949 * but always uses default parse options. 950 * 951 * @param klass 952 * <code>klass.getClassLoader()</code> will be used to load 953 * resources, and non-absolute resource names will have this 954 * class's package added 955 * @param resourceBasename 956 * a resource name as in {@link java.lang.Class#getResource}, 957 * with or without extension 958 * @return the parsed configuration 959 */ 960 public static Config parseResourcesAnySyntax(Class<?> klass, String resourceBasename) { 961 return parseResourcesAnySyntax(klass, resourceBasename, ConfigParseOptions.defaults()); 962 } 963 964 /** 965 * Parses all resources on the classpath with the given name and merges them 966 * into a single <code>Config</code>. 967 * 968 * <p> 969 * This works like {@link java.lang.ClassLoader#getResource}, not like 970 * {@link java.lang.Class#getResource}, so the name never begins with a 971 * slash. 972 * 973 * <p> 974 * See {@link #parseResources(Class,String,ConfigParseOptions)} for full 975 * details. 976 * 977 * @param loader 978 * will be used to load resources by setting this loader on the 979 * provided options 980 * @param resource 981 * resource to look up 982 * @param options 983 * parse options (class loader is ignored) 984 * @return the parsed configuration 985 */ 986 public static Config parseResources(ClassLoader loader, String resource, 987 ConfigParseOptions options) { 988 return parseResources(resource, options.setClassLoader(loader)); 989 } 990 991 /** 992 * Like {@link #parseResources(ClassLoader,String,ConfigParseOptions)} but always uses 993 * default parse options. 994 * 995 * @param loader 996 * will be used to load resources 997 * @param resource 998 * resource to look up in the loader 999 * @return the parsed configuration 1000 */ 1001 public static Config parseResources(ClassLoader loader, String resource) { 1002 return parseResources(loader, resource, ConfigParseOptions.defaults()); 1003 } 1004 1005 /** 1006 * Parses classpath resources with a flexible extension. In general, this 1007 * method has the same behavior as 1008 * {@link #parseFileAnySyntax(File,ConfigParseOptions)} but for classpath 1009 * resources instead, as in 1010 * {@link #parseResources(ClassLoader,String,ConfigParseOptions)}. 1011 * 1012 * <p> 1013 * {@link #parseResourcesAnySyntax(Class,String,ConfigParseOptions)} differs 1014 * in the syntax for the resource name, but otherwise see 1015 * {@link #parseResourcesAnySyntax(Class,String,ConfigParseOptions)} for 1016 * some details and caveats on this method. 1017 * 1018 * @param loader 1019 * class loader to look up resources in, will be set on options 1020 * @param resourceBasename 1021 * a resource name as in 1022 * {@link java.lang.ClassLoader#getResource}, with or without 1023 * extension 1024 * @param options 1025 * parse options (class loader ignored) 1026 * @return the parsed configuration 1027 */ 1028 public static Config parseResourcesAnySyntax(ClassLoader loader, String resourceBasename, 1029 ConfigParseOptions options) { 1030 return ConfigImpl.parseResourcesAnySyntax(resourceBasename, options.setClassLoader(loader)) 1031 .toConfig(); 1032 } 1033 1034 /** 1035 * Like {@link #parseResourcesAnySyntax(ClassLoader,String,ConfigParseOptions)} but always uses 1036 * default parse options. 1037 * 1038 * @param loader 1039 * will be used to load resources 1040 * @param resourceBasename 1041 * a resource name as in 1042 * {@link java.lang.ClassLoader#getResource}, with or without 1043 * extension 1044 * @return the parsed configuration 1045 */ 1046 public static Config parseResourcesAnySyntax(ClassLoader loader, String resourceBasename) { 1047 return parseResourcesAnySyntax(loader, resourceBasename, ConfigParseOptions.defaults()); 1048 } 1049 1050 /** 1051 * Like {@link #parseResources(ClassLoader,String,ConfigParseOptions)} but 1052 * uses thread's current context class loader if none is set in the 1053 * ConfigParseOptions. 1054 * @param resource the resource name 1055 * @param options parse options 1056 * @return the parsed configuration 1057 */ 1058 public static Config parseResources(String resource, ConfigParseOptions options) { 1059 ConfigParseOptions withLoader = ensureClassLoader(options, "parseResources"); 1060 return Parseable.newResources(resource, withLoader).parse().toConfig(); 1061 } 1062 1063 /** 1064 * Like {@link #parseResources(ClassLoader,String)} but uses thread's 1065 * current context class loader. 1066 * @param resource the resource name 1067 * @return the parsed configuration 1068 */ 1069 public static Config parseResources(String resource) { 1070 return parseResources(resource, ConfigParseOptions.defaults()); 1071 } 1072 1073 /** 1074 * Like 1075 * {@link #parseResourcesAnySyntax(ClassLoader,String,ConfigParseOptions)} 1076 * but uses thread's current context class loader. 1077 * @param resourceBasename the resource basename (no file type suffix) 1078 * @param options parse options 1079 * @return the parsed configuration 1080 */ 1081 public static Config parseResourcesAnySyntax(String resourceBasename, ConfigParseOptions options) { 1082 return ConfigImpl.parseResourcesAnySyntax(resourceBasename, options).toConfig(); 1083 } 1084 1085 /** 1086 * Like {@link #parseResourcesAnySyntax(ClassLoader,String)} but uses 1087 * thread's current context class loader. 1088 * @param resourceBasename the resource basename (no file type suffix) 1089 * @return the parsed configuration 1090 */ 1091 public static Config parseResourcesAnySyntax(String resourceBasename) { 1092 return parseResourcesAnySyntax(resourceBasename, ConfigParseOptions.defaults()); 1093 } 1094 1095 /** 1096 * Parse only any application replacement (specified by one of config.{resource,file,url}), returning 1097 * an empty Config if no overrides were set. 1098 * 1099 * @since 1.4.1 1100 * 1101 * @return a {@link java.util.Optional} containing any specified replacement, or {@link Optional#empty()} 1102 * if none was specified. 1103 */ 1104 public static java.util.Optional<Config> parseApplicationReplacement() { 1105 return parseApplicationReplacement(ConfigParseOptions.defaults()); 1106 } 1107 1108 /** 1109 * Like {@link #parseApplicationReplacement()} but allows you to specify a class loader 1110 * ti yse rather than the current context class loader. 1111 * 1112 * @since 1.4.1 1113 * 1114 * @param loader the class loader 1115 * @return a {@link java.util.Optional} containing any specified replacement, or {@link Optional#empty()} 1116 * if none was specified. 1117 */ 1118 public static java.util.Optional<Config> parseApplicationReplacement(ClassLoader loader) { 1119 return parseApplicationReplacement(ConfigParseOptions.defaults().setClassLoader(loader)); 1120 } 1121 1122 /** 1123 * Like {@link #parseApplicationReplacement()} but allows you to specify parse options. 1124 * 1125 * @since 1.4.1 1126 * 1127 * @param parseOptions parse options 1128 * @return a {@link java.util.Optional} containing any specified replacement, or {@link Optional#empty()} 1129 * if none was specified. 1130 */ 1131 public static java.util.Optional<Config> parseApplicationReplacement(ConfigParseOptions parseOptions) { 1132 final ConfigParseOptions withLoader = ensureClassLoader(parseOptions, "parseApplicationReplacement"); 1133 ClassLoader loader = withLoader.getClassLoader(); 1134 1135 int specified = 0; 1136 1137 // override application.conf with config.file, config.resource, 1138 // config.url if requested. 1139 String resource = System.getProperty("config.resource"); 1140 if (resource != null) 1141 specified += 1; 1142 String file = System.getProperty("config.file"); 1143 if (file != null) 1144 specified += 1; 1145 String url = System.getProperty("config.url"); 1146 if (url != null) 1147 specified += 1; 1148 1149 if (specified == 0) { 1150 return java.util.Optional.empty(); 1151 } else if (specified > 1) { 1152 throw new ConfigException.Generic("You set more than one of config.file='" + file 1153 + "', config.url='" + url + "', config.resource='" + resource 1154 + "'; don't know which one to use!"); 1155 } else { 1156 // the override file/url/resource MUST be present or it's an error 1157 ConfigParseOptions overrideOptions = parseOptions.setAllowMissing(false); 1158 if (resource != null) { 1159 if (resource.startsWith("/")) 1160 resource = resource.substring(1); 1161 // this deliberately does not parseResourcesAnySyntax; if 1162 // people want that they can use an include statement. 1163 return java.util.Optional.of(ConfigFactory.parseResources(loader, resource, overrideOptions)); 1164 } else if (file != null) { 1165 return java.util.Optional.of(ConfigFactory.parseFile(new File(file), overrideOptions)); 1166 } else { 1167 try { 1168 return java.util.Optional.of(ConfigFactory.parseURL(new URL(url), overrideOptions)); 1169 } catch (MalformedURLException e) { 1170 throw new ConfigException.Generic("Bad URL in config.url system property: '" 1171 + url + "': " + e.getMessage(), e); 1172 } 1173 } 1174 } 1175 1176 } 1177 1178 /** 1179 * Parses a string (which should be valid HOCON or JSON by default, or 1180 * the syntax specified in the options otherwise). 1181 * 1182 * @param s string to parse 1183 * @param options parse options 1184 * @return the parsed configuration 1185 */ 1186 public static Config parseString(String s, ConfigParseOptions options) { 1187 return Parseable.newString(s, options).parse().toConfig(); 1188 } 1189 1190 /** 1191 * Parses a string (which should be valid HOCON or JSON). 1192 * 1193 * @param s string to parse 1194 * @return the parsed configuration 1195 */ 1196 public static Config parseString(String s) { 1197 return parseString(s, ConfigParseOptions.defaults()); 1198 } 1199 1200 /** 1201 * Creates a {@code Config} based on a {@link java.util.Map} from paths to 1202 * plain Java values. Similar to 1203 * {@link ConfigValueFactory#fromMap(Map,String)}, except the keys in the 1204 * map are path expressions, rather than keys; and correspondingly it 1205 * returns a {@code Config} instead of a {@code ConfigObject}. This is more 1206 * convenient if you are writing literal maps in code, and less convenient 1207 * if you are getting your maps from some data source such as a parser. 1208 * 1209 * <p> 1210 * An exception will be thrown (and it is a bug in the caller of the method) 1211 * if a path is both an object and a value, for example if you had both 1212 * "a=foo" and "a.b=bar", then "a" is both the string "foo" and the parent 1213 * object of "b". The caller of this method should ensure that doesn't 1214 * happen. 1215 * 1216 * @param values map from paths to plain Java objects 1217 * @param originDescription 1218 * description of what this map represents, like a filename, or 1219 * "default settings" (origin description is used in error 1220 * messages) 1221 * @return the map converted to a {@code Config} 1222 */ 1223 public static Config parseMap(Map<String, ? extends Object> values, 1224 String originDescription) { 1225 return ConfigImpl.fromPathMap(values, originDescription).toConfig(); 1226 } 1227 1228 /** 1229 * See the other overload of {@link #parseMap(Map, String)} for details, 1230 * this one just uses a default origin description. 1231 * 1232 * @param values map from paths to plain Java values 1233 * @return the map converted to a {@code Config} 1234 */ 1235 public static Config parseMap(Map<String, ? extends Object> values) { 1236 return parseMap(values, null); 1237 } 1238 1239 private static ConfigLoadingStrategy getConfigLoadingStrategy() { 1240 String className = System.getProperties().getProperty(STRATEGY_PROPERTY_NAME); 1241 1242 if (className != null) { 1243 try { 1244 return ConfigLoadingStrategy.class.cast(Class.forName(className).newInstance()); 1245 } catch (Throwable e) { 1246 throw new ConfigException.BugOrBroken("Failed to load strategy: " + className, e); 1247 } 1248 } else { 1249 return new DefaultConfigLoadingStrategy(); 1250 } 1251 } 1252 1253 private static Boolean getOverrideWithEnv() { 1254 String overrideWithEnv = System.getProperties().getProperty(OVERRIDE_WITH_ENV_PROPERTY_NAME); 1255 1256 return Boolean.parseBoolean(overrideWithEnv); 1257 } 1258}