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