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