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