cpp-hocon  0.3.0
Public Member Functions | Static Public Member Functions | Protected Member Functions | Static Protected Member Functions | Friends | List of all members
hocon::config Class Reference

An immutable map from config paths to config values. More...

Inheritance diagram for hocon::config:
hocon::config_mergeable

Public Member Functions

virtual shared_object root () const
 Gets the. More...
 
virtual shared_origin origin () const
 Gets the origin of the. More...
 
std::shared_ptr< const config_mergeablewith_fallback (std::shared_ptr< const config_mergeable > other) const override
 Returns a new value computed by merging this value with another, with keys in this value "winning" over the other one. More...
 
shared_value to_fallback_value () const override
 Converts a config to its root object and a config_value to itself. More...
 
virtual shared_config resolve () const
 Returns a replacement config with all substitutions (the ${foo.bar} syntax, see the spec) resolved. More...
 
virtual shared_config resolve (config_resolve_options options) const
 Like config#resolve() but allows you to specify non-default options. More...
 
virtual bool is_resolved () const
 Checks whether the config is completely resolved. More...
 
virtual shared_config resolve_with (shared_config source) const
 Like config#resolve() except that substitution values are looked up in the given source, rather than in this instance. More...
 
virtual shared_config resolve_with (shared_config source, config_resolve_options options) const
 Like config#resolve_with(config) but allows you to specify non-default options. More...
 
virtual void check_valid (shared_config reference, std::vector< std::string > restrict_to_paths) const
 Validates this config against a reference config, throwing an exception if it is invalid. More...
 
virtual bool has_path (std::string const &path) const
 Checks whether a value is present and non-null at the given path. More...
 
virtual bool has_path_or_null (std::string const &path) const
 Checks whether a value is present at the given path, even if the value is null. More...
 
virtual bool is_empty () const
 Returns true if the. More...
 
virtual std::set< std::pair< std::string, std::shared_ptr< const config_value > > > entry_set () const
 Returns the set of path-value pairs, excluding any null values, found by recursing the root object. More...
 
virtual bool get_is_null (std::string const &path) const
 Checks whether a value is set to null at the given path, but throws an exception if the value is entirely unset. More...
 
virtual bool get_bool (std::string const &path) const
 
virtual int get_int (std::string const &path) const
 
virtual int64_t get_long (std::string const &path) const
 
virtual double get_double (std::string const &path) const
 
virtual std::string get_string (std::string const &path) const
 
virtual std::shared_ptr< const config_objectget_object (std::string const &path) const
 
virtual shared_config get_config (std::string const &path) const
 
virtual unwrapped_value get_any_ref (std::string const &path) const
 
virtual std::shared_ptr< const config_valueget_value (std::string const &path) const
 
template<typename T >
std::vector< T > get_homogeneous_unwrapped_list (std::string const &path) const
 
virtual shared_list get_list (std::string const &path) const
 
virtual std::vector< bool > get_bool_list (std::string const &path) const
 
virtual std::vector< int > get_int_list (std::string const &path) const
 
virtual std::vector< int64_t > get_long_list (std::string const &path) const
 
virtual std::vector< double > get_double_list (std::string const &path) const
 
virtual std::vector< std::string > get_string_list (std::string const &path) const
 
virtual std::vector< shared_object > get_object_list (std::string const &path) const
 
virtual std::vector< shared_config > get_config_list (std::string const &path) const
 
virtual int64_t get_duration (std::string const &path, time_unit unit) const
 Gets a value as an integer number of the specified units. More...
 
virtual shared_config with_only_path (std::string const &path) const
 Clone the config with only the given path (and its children) retained; all sibling paths are removed. More...
 
virtual shared_config without_path (std::string const &path) const
 Clone the config with the given path removed. More...
 
virtual shared_config at_path (std::string const &path) const
 Places the config inside another. More...
 
virtual shared_config at_key (std::string const &key) const
 Places the config inside a. More...
 
virtual shared_config with_value (std::string const &path, std::shared_ptr< const config_value > value) const
 Returns a. More...
 
bool operator== (config const &other) const
 
 config (shared_object object)
 
template<>
std::vector< int64_t > get_homogeneous_unwrapped_list (std::string const &path) const
 

Static Public Member Functions

static shared_config parse_file_any_syntax (std::string file_basename, config_parse_options options)
 Parses a file with a flexible extension. More...
 
static shared_config parse_file_any_syntax (std::string file_basename)
 Like parseFileAnySyntax(File,config_parse_options) but always uses default parse options. More...
 
static shared_config parse_string (std::string s, config_parse_options options)
 Parses a string (which should be valid HOCON or JSON by default, or the syntax specified in the options otherwise). More...
 
static shared_config parse_string (std::string s)
 Parses a string (which should be valid HOCON or JSON). More...
 
static shared_object env_variables_as_config_object ()
 

Protected Member Functions

shared_value find (std::string const &path_expression, config_value::type expected) const
 
shared_value find (path path_expression, config_value::type expected, path original_path) const
 
shared_value find (path path_expression, config_value::type expected) const
 
shared_config at_key (shared_origin origin, std::string const &key) const
 

Static Protected Member Functions

static shared_includer default_includer ()
 

Friends

class config_object
 
class config_value
 
class config_parseable
 
class parseable
 

Detailed Description

An immutable map from config paths to config values.

Paths are dot-separated expressions such as foo.bar.baz. Values are as in JSON (booleans, strings, numbers, lists, or objects), represented by config_value instances. Values accessed through the config interface are never null.

config

is an immutable object and thus safe to use from multiple threads. There's never a need for "defensive copies."

Fundamental operations on a

config

include getting configuration values, resolving substitutions with config#resolve(), and merging configs using config#with_fallback(config_mergeable).

All operations return a new immutable

config

rather than modifying the original instance.

Examples

You can find an example app and library on GitHub. Also be sure to read the package overview which describes the big picture as shown in those examples.

Paths, keys, and config vs. config_object

config is a view onto a tree of config_object; the corresponding object tree can be found through config#root(). config_object is a map from config keys, rather than paths, to config values. Think of config_object as a JSON object and config as a configuration API.

The API tries to consistently use the terms "key" and "path." A key is a key in a JSON object; it's just a string that's the key in a map. A "path" is a parseable expression with a syntax and it refers to a series of keys. Path expressions are described in the spec for Human-Optimized Config Object Notation. In brief, a path is period-separated so "a.b.c" looks for key c in object b in object a in the root object. Sometimes double quotes are needed around special characters in path expressions.

The API for a

config

is in terms of path expressions, while the API for a

config_object

is in terms of keys. Conceptually,

config

is a one-level map from paths to values, while a

config_object

is a tree of nested maps from keys to values.

Use config_util#join_path and config_util#split_path to convert between path expressions and individual path elements (keys).

Another difference between

config

and

config_object

is that conceptually,

config_value

s with a value_type() of NULL exist in a

config_object

, while a

config

treats null values as if they were missing. (With the exception of two methods: config#has_path_or_null and config#get_is_null let you detect null values.)

Getting configuration values

The "getters" on a

config

all work in the same way. They never return null, nor do they return a

config_value

with value_type() of NULL. Instead, they throw config_exception if the value is completely absent or set to null. If the value is set to null, a subtype of

config_exception.missing

called config_exception.null will be thrown. config_excpetion.wrong_type will be thrown anytime you ask for a type and the value has an incompatible type. Reasonable type conversions are performed for you though.

Iteration

If you want to iterate over the contents of a

config

, you can get its

config_object

with root(), and then iterate over the

config_object

(which implements java.util.Map). Or, you can use entry_set() which recurses the object tree for you and builds up a set of all path-value pairs where the value is not null.

Resolving substitutions

Substitutions are the ${foo.bar} syntax in config files, described in the specification. Resolving substitutions replaces these references with real values.

Before using a

config

it's necessary to call config#resolve() to handle substitutions (though config_factory#load() and similar methods will do the resolve for you already).

Merging

The full config for your application can be constructed using the associative operation config#with_fallback(config_mergeable). If you use config_factory#load() (recommended), it merges system properties over the top of application.conf over the top of reference.conf, using with_fallback. You can add in additional sources of configuration in the same way (usually, custom layers should go either just above or just below application.conf, keeping reference.conf at the bottom and system properties at the top).

Serialization

Convert a config to a JSON or HOCON string by calling config_object#render() on the root object, my_config.root().render(). There's also a variant config_object#render(config_render_options) which allows you to control the format of the rendered string. (See config_render_options.) Note that config does not remember the formatting of the original file, so if you load, modify, and re-save a config file, it will be substantially reformatted.

As an alternative to config_object#render(), the to_string() method produces a debug-output-oriented representation (which is not valid JSON).

This is an interface but don't implement it yourself

Do not implement

config

; it should only be implemented by the config library. Arbitrary implementations will not work because the library internals assume a specific concrete implementation. Also, this interface is likely to grow new methods over time, so third-party implementations will break.

Definition at line 172 of file config.hpp.

Member Function Documentation

◆ at_key()

virtual shared_config hocon::config::at_key ( std::string const &  key) const
virtual

Places the config inside a.

config

at the given key. See also at_path(). Note that a key is NOT a path expression (see config_util#join_path and config_util#split_path).

Parameters
keykey to store this config at.
Returns
a
config
instance containing this config at the given key.

◆ at_path()

virtual shared_config hocon::config::at_path ( std::string const &  path) const
virtual

Places the config inside another.

config

at the given path.

Note that path expressions have a syntax and sometimes require quoting (see config_util#join_path and config_util#split_path).

Parameters
pathpath expression to store this config at.
Returns
a
config
instance containing this config at the given path.

◆ check_valid()

virtual void hocon::config::check_valid ( shared_config  reference,
std::vector< std::string >  restrict_to_paths 
) const
virtual

Validates this config against a reference config, throwing an exception if it is invalid.

The purpose of this method is to "fail early" with a comprehensive list of problems; in general, anything this method can find would be detected later when trying to use the config, but it's often more user-friendly to fail right away when loading the config.

Using this method is always optional, since you can "fail late" instead.

You must restrict validation to paths you "own" (those whose meaning are defined by your code module). If you validate globally, you may trigger errors about paths that happen to be in the config but have nothing to do with your module. It's best to allow the modules owning those paths to validate them. Also, if every module validates only its own stuff, there isn't as much redundant work being done.

If no paths are specified in check_valid()'s parameter list, validation is for the entire config.

If you specify paths that are not in the reference config, those paths are ignored. (There's nothing to validate.)

Here's what validation involves:

  • All paths found in the reference config must be present in this config or an exception will be thrown.
  • Some changes in type from the reference config to this config will cause an exception to be thrown. Not all potential type problems are detected, in particular it's assumed that strings are compatible with everything except objects and lists. This is because string types are often "really" some other type (system properties always start out as strings, or a string like "5ms" could be used with get_milliseconds). Also, it's allowed to set any type to null or override null with any type.
  • Any unresolved substitutions in this config will cause a validation failure; both the reference config and this config should be resolved before validation. If the reference config is unresolved, it's a bug in the caller of this method.

If you want to allow a certain setting to have a flexible type (or otherwise want validation to be looser for some settings), you could either remove the problematic setting from the reference config provided to this method, or you could intercept the validation exception and screen out certain problems. Of course, this will only work if all other callers of this method are careful to restrict validation to their own paths, as they should be.

If validation fails, the thrown exception contains a list of all problems found. The exception will have all the problem concatenated into one huge string.

Again, check_valid() can't guess every domain-specific way a setting can be invalid, so some problems may arise later when attempting to use the config. check_valid() is limited to reporting generic, but common, problems such as missing settings and blatant type incompatibilities.

Parameters
referencea reference configuration
restrictToPathsonly validate values underneath these paths that your code module owns and understands

◆ entry_set()

virtual std::set<std::pair<std::string, std::shared_ptr<const config_value> > > hocon::config::entry_set ( ) const
virtual

Returns the set of path-value pairs, excluding any null values, found by recursing the root object.

Note that this is very different from root().entry_set() which returns the set of immediate-child keys in the root object and includes null values.

Entries contain path expressions meaning there may be quoting and escaping involved. Parse path expressions with config_util#split_path.

Because a config is conceptually a single-level map from paths to values, there will not be any config_object values in the entries (that is, all entries represent leaf nodes). Use config_object rather than config if you want a tree. (OK, this is a slight lie: config entries may contain config_list and the lists may contain objects. But no objects are directly included as entry values.)

Returns
set of paths with non-null values, built up by recursing the entire tree of config_object and creating an entry for each leaf value.

◆ get_duration()

virtual int64_t hocon::config::get_duration ( std::string const &  path,
time_unit  unit 
) const
virtual

Gets a value as an integer number of the specified units.

If the result would have a fractional part, the number is truncated. Correctly handles durations within the range +/-2^63 seconds.

Parameters
paththe path to the time value
unitthe units of the number returned
Returns
a 64-bit integer representing the value converted to the requested units

◆ get_is_null()

virtual bool hocon::config::get_is_null ( std::string const &  path) const
virtual

Checks whether a value is set to null at the given path, but throws an exception if the value is entirely unset.

This method will not throw if {} returned true for the same path, so to avoid any possible exception check has_path_or_null() first. However, an exception for unset paths will usually be the right thing (because a reference.conf should exist that has the path set, the path should never be unset unless something is broken). Note that path expressions have a syntax and sometimes require quoting (see config_util#join_path and config_util#split_path).

Parameters
paththe path expression
Returns
true if the value exists and is null, false if it exists and is not null

◆ has_path()

virtual bool hocon::config::has_path ( std::string const &  path) const
virtual

Checks whether a value is present and non-null at the given path.

This differs in two ways from

Map.containsKey()

as implemented by config_object: it looks for a path expression, not a key; and it returns false for null values, while

contains_key()

returns true indicating that the object contains a null value for the key.

If a path exists according to has_path(string), then get_value(string) will never throw an exception. However, the typed getters will still throw if the value is not convertible to the requested type.

Note that path expressions have a syntax and sometimes require quoting (see config_util#join_path and config_util#split_path).

Parameters
paththe path expression
Returns
true if a non-null value is present at the path

◆ has_path_or_null()

virtual bool hocon::config::has_path_or_null ( std::string const &  path) const
virtual

Checks whether a value is present at the given path, even if the value is null.

Most of the getters on config will throw if you try to get a null value, so if you plan to call get_value(string), get_int(string), or another getter you may want to use plain has_path(string) rather than this method.

To handle all three cases (unset, null, and a non-null value) the code might look like:


if (config.has_path_or_null(path)) {
    if (config.get_is_null(path)) {
       // handle null setting
    } else {
       // get and use non-null setting
    }
} else {
    // handle entirely unset path
}

However, the usual thing is to allow entirely unset paths to be a bug that throws an exception (because you set a default in your reference.conf), so in that case it's OK to call get_is_null(string) without checking has_path_or_null first.

Note that path expressions have a syntax and sometimes require quoting (see config_util#join_path and config_util#split_path).

Parameters
paththe path expression
Returns
true if a value is present at the path, even if the value is null

◆ is_empty()

virtual bool hocon::config::is_empty ( ) const
virtual

Returns true if the.

config

's root object contains no key-value pairs.

Returns
true if the configuration is empty

◆ is_resolved()

virtual bool hocon::config::is_resolved ( ) const
virtual

Checks whether the config is completely resolved.

After a successful call to config#resolve() it will be completely resolved, but after calling config#resolve(config_resolve_options) with allow_unresolved set in the options, it may or may not be completely resolved. A newly-loaded config may or may not be completely resolved depending on whether there were substitutions present in the file.

Returns
true if there are no unresolved substitutions remaining in this configuration.

◆ origin()

virtual shared_origin hocon::config::origin ( ) const
virtual

Gets the origin of the.

config

, which may be a file, or a file with a line number, or just a descriptive phrase.

Returns
the origin of the
config
for use in error messages

◆ parse_file_any_syntax() [1/2]

static shared_config hocon::config::parse_file_any_syntax ( std::string  file_basename)
static

Like parseFileAnySyntax(File,config_parse_options) but always uses default parse options.

Parameters
fileBasenamea filename with or without extension
Returns
the parsed configuration

◆ parse_file_any_syntax() [2/2]

static shared_config hocon::config::parse_file_any_syntax ( std::string  file_basename,
config_parse_options  options 
)
static

Parses a file with a flexible extension.

If the fileBasename already ends in a known extension, this method parses it according to that extension (the file's syntax must match its extension). If the fileBasename does not end in an extension, it parses files with all known extensions and merges whatever is found.

In the current implementation, the extension ".conf" forces config_syntax#CONF, ".json" forces config_syntax#JSON. When merging files, ".conf" falls back to ".json".

Future versions of the implementation may add additional syntaxes or additional extensions. However, the ordering (fallback priority) of the three current extensions will remain the same.

If options forces a specific syntax, this method only parses files with an extension matching that syntax.

If options.getAllowMissing() is true, then no files have to exist; if false, then at least one file has to exist.

Parameters
fileBasenamea filename with or without extension
optionsparse options
Returns
the parsed configuration

◆ parse_string() [1/2]

static shared_config hocon::config::parse_string ( std::string  s)
static

Parses a string (which should be valid HOCON or JSON).

Parameters
sstring to parse
Returns
the parsed configuration

◆ parse_string() [2/2]

static shared_config hocon::config::parse_string ( std::string  s,
config_parse_options  options 
)
static

Parses a string (which should be valid HOCON or JSON by default, or the syntax specified in the options otherwise).

Parameters
sstring to parse
optionsparse options
Returns
the parsed configuration

◆ resolve() [1/2]

virtual shared_config hocon::config::resolve ( ) const
virtual

Returns a replacement config with all substitutions (the ${foo.bar} syntax, see the spec) resolved.

Substitutions are looked up using this config as the root object, that is, a substitution ${foo.bar} will be replaced with the result of get_value("foo.bar").

This method uses config_resolve_options(), there is another variant config#resolve(config_resolve_options) which lets you specify non-default options.

A given config must be resolved before using it to retrieve config values, but ideally should be resolved one time for your entire stack of fallbacks (see config#with_fallback). Otherwise, some substitutions that could have resolved with all fallbacks available may not resolve, which will be potentially confusing for your application's users.

resolve() should be invoked on root config objects, rather than on a subtree (a subtree is the result of something like config.get_config("foo")). The problem with resolve() on a subtree is that substitutions are relative to the root of the config and the subtree will have no way to get values from the root. For example, if you did config.get_config("foo").resolve() on the below config file, it would not work:

  common-value = 10
  foo {
     whatever = ${common-value}
  }

Many methods on config_factory such as config_factory#load() automatically resolve the loaded config on the loaded stack of config files.

Resolving an already-resolved config is a harmless no-op, but again, it is best to resolve an entire stack of fallbacks (such as all your config files combined) rather than resolving each one individually.

Returns
an immutable object with substitutions resolved

◆ resolve() [2/2]

virtual shared_config hocon::config::resolve ( config_resolve_options  options) const
virtual

Like config#resolve() but allows you to specify non-default options.

Parameters
optionsresolve options
Returns
the resolved config (may be only partially resolved if options are set to allow unresolved)

◆ resolve_with() [1/2]

virtual shared_config hocon::config::resolve_with ( shared_config  source) const
virtual

Like config#resolve() except that substitution values are looked up in the given source, rather than in this instance.

This is a special-purpose method which doesn't make sense to use in most cases; it's only needed if you're constructing some sort of app-specific custom approach to configuration. The more usual approach if you have a source of substitution values would be to merge that source into your config stack using config#withFallback and then resolve.

Note that this method does NOT look in this instance for substitution values. If you want to do that, you could either merge this instance into your value source using config#with_fallback, or you could resolve multiple times with multiple sources (using config_resolve_options#setAllowUnresolved(boolean) so the partial resolves don't fail).

Parameters
sourceconfiguration to pull values from
Returns
an immutable object with substitutions resolved

◆ resolve_with() [2/2]

virtual shared_config hocon::config::resolve_with ( shared_config  source,
config_resolve_options  options 
) const
virtual

Like config#resolve_with(config) but allows you to specify non-default options.

Parameters
sourcesource configuration to pull values from
optionsresolve options
Returns
the resolved config (may be only partially resolved if options are set to allow unresolved)

◆ root()

virtual shared_object hocon::config::root ( ) const
virtual

Gets the.

config

as a tree of config_object. This is a constant-time operation (it is not proportional to the number of values in the

config

).

Returns
the root object in the configuration

◆ to_fallback_value()

shared_value hocon::config::to_fallback_value ( ) const
overridevirtual

Converts a config to its root object and a config_value to itself.

Originally in the MergeableValue interface, squashing to ease C++ public API separation

Implements hocon::config_mergeable.

◆ with_fallback()

std::shared_ptr<const config_mergeable> hocon::config::with_fallback ( std::shared_ptr< const config_mergeable other) const
overridevirtual

Returns a new value computed by merging this value with another, with keys in this value "winning" over the other one.

This associative operation may be used to combine configurations from multiple sources (such as multiple configuration files).

The semantics of merging are described in the spec for HOCON. Merging typically occurs when either the same object is created twice in the same file, or two config files are both loaded. For example:

 foo = { a: 42 }
 foo = { b: 43 }

Here, the two objects are merged as if you had written:

 foo = { a: 42, b: 43 }

Only config_object and config instances do anything in this method (they need to merge the fallback keys into themselves). All other values just return the original value, since they automatically override any fallback. This means that objects do not merge "across" non-objects; if you write object.withFallback(nonObject).withFallback(otherObject), then otherObject will simply be ignored. This is an intentional part of how merging works, because non-objects such as strings and integers replace (rather than merging with) any prior value:

foo = { a: 42 }
foo = 10

Here, the number 10 "wins" and the value of foo would be simply 10. Again, for details see the spec.

Parameters
otheran object whose keys should be used as fallbacks, if the keys are not present in this one
Returns
a new object (or the original one, if the fallback doesn't get used)

Implements hocon::config_mergeable.

◆ with_only_path()

virtual shared_config hocon::config::with_only_path ( std::string const &  path) const
virtual

Clone the config with only the given path (and its children) retained; all sibling paths are removed.

Note that path expressions have a syntax and sometimes require quoting (see config_util#join_path and config_util#split_path).

Parameters
pathpath to keep
Returns
a copy of the config minus all paths except the one specified

◆ with_value()

virtual shared_config hocon::config::with_value ( std::string const &  path,
std::shared_ptr< const config_value value 
) const
virtual

Returns a.

config

based on this one, but with the given path set to the given value. Does not modify this instance (since it's immutable). If the path already has a value, that value is replaced. To remove a value, use withoutPath().

Note that path expressions have a syntax and sometimes require quoting (see config_util#join_path and config_util#split_path).

Parameters
pathpath expression for the value's new location
valuevalue at the new path
Returns
the new instance with the new map entry

◆ without_path()

virtual shared_config hocon::config::without_path ( std::string const &  path) const
virtual

Clone the config with the given path removed.

Note that path expressions have a syntax and sometimes require quoting (see config_util#join_path and config_util#split_path).

Parameters
pathpath expression to remove
Returns
a copy of the config minus the specified path

The documentation for this class was generated from the following file: