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