grizzled.config

Configuration

class Configuration extends AnyRef

An INI-style configuration file parser.

Configuration implements an in-memory store for a configuration file whose syntax is reminiscent of classic Windows .INI files, though with many extensions.

Syntax

A configuration file is broken into sections, and each section is introduced by a section name in brackets. For example:

[main]
installation.directory=/usr/local/foo
program.directory: /usr/local/foo/programs

[search]
searchCommand: find /usr/local/foo -type f -name '*.class'

[display]
searchFailedMessage=Search failed, sorry.

Notes and caveats:

At least one section is required.

Sections may be empty.

It is an error to have any variable definitions before the first section header.

The section names "system" and "env" are reserved. They don't really exist, but they're used during variable substitution (see below) to substitute from System.properties and the environment, respectively.

Section Name Syntax

There can be any amount of whitespace before and after the brackets in a section name; the whitespace is ignored. Section names may consist of alphanumeric characters and underscores. Anything else is not permitted.

Variable Syntax

Each section contains zero or more variable settings. Similar to a JavaProperties file, the variables are specified as name/value pairs, separated by an equal sign ("=") or a colon (":"). Variable names are case-sensitive by default, though the case-sensitivity (and other aspects of the variable name) may be changed by subclassingConfiguration and providing your own version of thetransformOptionName() method. Variable names may contain alphanumerics, underscores, and hyphens (-). Variable values may contain anything at all. The parser ignores whitespace on either side of the "=" or ":"; that is, leading whitespace in the value is skipped. The way to include leading whitespace in a value is escape the whitespace characters with backslashes. (See below).

Continuation Lines

Variable definitions may span multiple lines; each line to be continued must end with a backslash ("\") character, which escapes the meaning of the newline, causing it to be treated like a space character. The following line is treated as a logical continuation of the first line. Unlike Java properties files, however, leading whitespace isnot removed from continued lines.

Only variable definition lines may be continued. Section header lines, comment lines (see below) and include directives (see below) cannot span multiple lines.

Expansions of Variable Values

The configuration parser preprocesses each variable's value, replacing embedded metacharacter sequences and substituting variable references. You can use backslashes to escape the special characters that the parser uses to recognize metacharacter and variable sequences; you can also use single quotes. See Suppressing Metacharacter Expansion and Variable Substitution, below, for more details.

Metacharacters

The parser recognizes Java-style ASCII escape sequences \t, \n,\r, \\, \ (a backslash and a space), and \uxxxx are recognized and converted to single characters. Note that metacharacter expansion is performed before variable substitution.

Variable Substitution

A variable value can interpolate the values of other variables, using a variable substitution syntax. The general form of a variable reference is \${sectionName.varName}.

sectionName is the name of the section containing the variable to substitute; if omitted, it defaults to the current section. varName is the name of the variable to substitute.

If a variable reference specifies a section name, the referenced section must precede the current section. It is not possible to substitute the value of a variable in a section that occurs later in the file.

The section names "system" and "env" are reserved for special "pseudosections."

The "system" pseudosection is used to interpolate values fromSystem.properties For instance, \${system.user.home} substitutes the value of the user.home system property (typically, the home directory of the user running the program). Similarly, \${system.user.name}substitutes the user's name.

The "env" pseudosection is used to interpolate values from the environment. On UNIX systems, for instance, \${env.HOME} substitutes user's home directory (and is, therefore, a synonym for\${system.user.home}. On some versions of Windows, \${env.USERNAME}will substitute the name of the user running the program. Note: On UNIX systems, environment variable names are typically case-sensitive; for instance, \${env.USER} and \${env.user} refer to different environment variables. On Windows systems, environment variable names are typically case-insensitive; \${env.USERNAME} and \${env.username} are equivalent.

Notes and caveats:

Configuration uses thegrizzled.string.template.UnixShellVariableSubstituterclass to do variable substitution, so it honors all the syntax conventions supported by that class.

Variable substitutions are only permitted within variable values. They are ignored in variable names, section names, include directives and comments.

Variable substitution is performed after metacharacter expansion (so don't include metacharacter sequences in your variable names).

To include a literal "\$" character in a variable value, escape it with a backslash, e.g., "var=value with \\$ dollar sign"

Suppressing Metacharacter Expansion and Variable Substitution

To prevent the parser from interpreting metacharacter sequences, variable substitutions and other special characters, use the "->" assignment operator, instead of ":" or "=".

For example, suppose you want to set variable "prompt" to the literal value "Enter value. To specify a newline, use \n." The following configuration file line will do the trick:

prompt -> Enter value. To specify a newline, use \n

Similarly, to set variable "abc" to the literal string "\${foo}" suppressing the parser's attempts to expand "\${foo}" as a variable reference, you could use:

abc -> \${foo}

Note: It's also possible, though hairy, to escape the special meaning of special characters via the backslash character. For instance, you can escape the variable substitution lead-in character, '\$', with a backslash. e.g., "\\$". This technique is not recommended, however, because you have to double-escape any backslash characters that you want to be preserved literally. For instance, to get "\t", you must specify "\\\\t". To get a literal backslash, specify "\\\\". (Yes, that's four backslashes, just to get a single unescaped one.) This double-escaping is a regrettable side effect of how the configuration file parses variable values: It makes two separate passes over the value (one for metacharacter expansion and another for variable expansion). Each of those passes honors and processes backslash escapes. This problem would go away if the configuration file parser parsed both metacharacter sequences and variable substitutions itself, in one pass. It doesn't currently do that, because it uses the separategrizzled.string.template.UnixShellStringTemplate classgrizzled.GrizzledString.translateMetachars() method to do the variable substitution and metacharacter translation. In general, you're better off just sticking with the "->" assignment operator.

Includes

A special include directive permits inline inclusion of another configuration file. The include directive takes two forms:

%include "path"
%include "URL"

For example:

%include "/home/bmc/mytools/common.cfg"
%include "http://configs.example.com/mytools/common.cfg"

If the include path is not a URL, and is not an absolute path, its location is relative to the file that's trying to include it.

The included file may contain any content that is valid for this parser. It may contain just variable definitions (i.e., the contents of a section, without the section header), or it may contain a complete configuration file, with individual sections. SinceConfiguration recognizes a variable syntax that is essentially identical to Java's properties file syntax, it's also legal to include a properties file, provided it's included within a valid section.

Note: Attempting to include a file from itself, either directly or indirectly, will cause the parser to throw an exception.

Comments and Blank Lines

A comment line is a one whose first non-whitespace character is a "#". A blank line is a line containing no content, or one containing only white space. Blank lines and comments are ignored.

Caller-supplied Predefined Sections

Calling applications may supply predefined sections and options, in the form of a map. These sections may then be used by other sections, via variable references. The predefined sections are defined in a map of maps. The outer map is keyed by predefined section name. The inner maps consist of options and their values. For instance, to read a configuration file, giving it access to certain command line parameters, you could do something like this:

object Foo
{
    def main(args: Array[String]) =
    {
        // You'd obviously want to do some real argument checking here.
        val configFile = args(0)
        val name = args(1)
        val ipAddress = args(2)
        val sections = Map("args" -> Map("name" -> name,
                                         "ip" -> ipAddress))
        val config = Configuration(configFile, sections)
        ...
    }
}
go to: companion
linear super types: AnyRef, Any
Ordering
  1. Alphabetic
  2. By inheritance
Inherited
  1. Hide All
  2. Show all
  1. Configuration
  2. AnyRef
  3. Any
Visibility
  1. Public
  2. All
Impl.
  1. Concrete
  2. Abstract

Instance constructors

  1. new Configuration ()

    Alternate constructor for use when there are no predefined sections.

    Alternate constructor for use when there are no predefined sections.

  2. new Configuration (predefinedSections: Map[String, Map[String, String]], sectionNamePattern: Regex =, commentPattern: Regex =)

    predefinedSections

    the predefined sections. An empty map means there are no predefined sections.

    sectionNamePattern

    Regular expression that matches legal section names. The section name portion must be in a group. Default: ([a-zA-Z0-9_]+)

    commentPattern

    Regular expression that matches comment lines. Default: \s*(#.*)$

Value Members

  1. def != (arg0: AnyRef) : Boolean

    attributes: final
    definition classes: AnyRef
  2. def != (arg0: Any) : Boolean

    o != arg0 is the same as !(o == (arg0)).

    o != arg0 is the same as !(o == (arg0)).

    arg0

    the object to compare against this object for dis-equality.

    returns

    false if the receiver object is equivalent to the argument; true otherwise.

    attributes: final
    definition classes: Any
  3. def ## () : Int

    attributes: final
    definition classes: AnyRef → Any
  4. def $asInstanceOf [T0] () : T0

    attributes: final
    definition classes: AnyRef
  5. def $isInstanceOf [T0] () : Boolean

    attributes: final
    definition classes: AnyRef
  6. def == (arg0: AnyRef) : Boolean

    o == arg0 is the same as if (o eq null) arg0 eq null else o.equals(arg0).

    o == arg0 is the same as if (o eq null) arg0 eq null else o.equals(arg0).

    arg0

    the object to compare against this object for equality.

    returns

    true if the receiver object is equivalent to the argument; false otherwise.

    attributes: final
    definition classes: AnyRef
  7. def == (arg0: Any) : Boolean

    o == arg0 is the same as o.equals(arg0).

    o == arg0 is the same as o.equals(arg0).

    arg0

    the object to compare against this object for equality.

    returns

    true if the receiver object is equivalent to the argument; false otherwise.

    attributes: final
    definition classes: Any
  8. def addOption (sectionName: String, optionName: String, value: String) : Unit

    Add an option name and value to a section.

    Add an option name and value to a section.

    sectionName

    the section name

    optionName

    the option name, which will be transformed

    value

    the option's value

  9. def addSection (name: String) : Unit

    Add a section to the configuration.

    Add a section to the configuration.

    name

    the new section's name

  10. def asInstanceOf [T0] : T0

    This method is used to cast the receiver object to be of type T0.

    This method is used to cast the receiver object to be of type T0.

    Note that the success of a cast at runtime is modulo Scala's erasure semantics. Therefore the expression1.asInstanceOf[String] will throw a ClassCastException at runtime, while the expressionList(1).asInstanceOf[List[String]] will not. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the requested typed.

    returns

    the receiver object.

    attributes: final
    definition classes: Any
  11. def clone () : AnyRef

    This method creates and returns a copy of the receiver object.

    This method creates and returns a copy of the receiver object.

    The default implementation of the clone method is platform dependent.

    returns

    a copy of the receiver object.

    attributes: protected
    definition classes: AnyRef
  12. def eq (arg0: AnyRef) : Boolean

    This method is used to test whether the argument (arg0) is a reference to the receiver object (this).

    This method is used to test whether the argument (arg0) is a reference to the receiver object (this).

    The eq method implements an [http://en.wikipedia.org/wiki/Equivalence_relation equivalence relation] on non-null instances of AnyRef: * It is reflexive: for any non-null instance x of type AnyRef, x.eq(x) returns true. * It is symmetric: for any non-null instances x and y of type AnyRef, x.eq(y) returns true if and only if y.eq(x) returns true. * It is transitive: for any non-null instances x, y, and z of type AnyRef if x.eq(y) returns true and y.eq(z) returns true, then x.eq(z) returns true.

    Additionally, the eq method has three other properties. * It is consistent: for any non-null instances x and y of type AnyRef, multiple invocations of x.eq(y) consistently returns true or consistently returns false. * For any non-null instance x of type AnyRef, x.eq(null) and null.eq(x) returns false. * null.eq(null) returns true.

    When overriding the equals or hashCode methods, it is important to ensure that their behavior is consistent with reference equality. Therefore, if two objects are references to each other (o1 eq o2), they should be equal to each other (o1 == o2) and they should hash to the same value (o1.hashCode == o2.hashCode).

    arg0

    the object to compare against this object for reference equality.

    returns

    true if the argument is a reference to the receiver object; false otherwise.

    attributes: final
    definition classes: AnyRef
  13. def equals (arg0: Any) : Boolean

    This method is used to compare the receiver object (this) with the argument object (arg0) for equivalence.

    This method is used to compare the receiver object (this) with the argument object (arg0) for equivalence.

    The default implementations of this method is an [http://en.wikipedia.org/wiki/Equivalence_relation equivalence relation]: * It is reflexive: for any instance x of type Any, x.equals(x) should return true. * It is symmetric: for any instances x and y of type Any, x.equals(y) should return true if and only if y.equals(x) returns true. * It is transitive: for any instances x, y, and z of type AnyRef if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

    If you override this method, you should verify that your implementation remains an equivalence relation. Additionally, when overriding this method it is often necessary to override hashCode to ensure that objects that are "equal" (o1.equals(o2) returns true) hash to the same scala.Int (o1.hashCode.equals(o2.hashCode)).

    arg0

    the object to compare against this object for equality.

    returns

    true if the receiver object is equivalent to the argument; false otherwise.

    definition classes: AnyRef → Any
  14. def finalize () : Unit

    This method is called by the garbage collector on the receiver object when garbage collection determines that there are no more references to the object.

    This method is called by the garbage collector on the receiver object when garbage collection determines that there are no more references to the object.

    The details of when and if the finalize method are invoked, as well as the interaction between finalizeand non-local returns and exceptions, are all platform dependent.

    attributes: protected
    definition classes: AnyRef
  15. def forMatchingSections (regex: Regex)(code: (Section) ⇒ Unit) : Unit

    Invoke a code block on each section whose name matches a regular expression.

    Invoke a code block on each section whose name matches a regular expression.

    regex

    the regular expression to match

    code

    the block of code to invoke with each section

  16. def get (sectionName: String, optionName: String) : Option[String]

    Works like Map.get(), returning Some(string) if the value is found, None if not.

    Works like Map.get(), returning Some(string) if the value is found, None if not. Does not throw exceptions.

    sectionName

    the section name

    optionName

    the option name

    returns

    Some(value) if the section and option exist, None if either the section or option cannot be found.

  17. def getAsList (sectionName: String, optionName: String, separators: Regex = ...) : Option[List[String]]

    Retrieve a value, splitting it into a list of strings.

    Retrieve a value, splitting it into a list of strings. Returns Some(list) if the key is found, and None otherwise.

    sectionName

    the section name

    optionName

    the option name

    separators

    separator regex to use. Default: [\s,]

  18. def getBoolean (sectionName: String, optionName: String) : Option[Boolean]

    Get an optional boolean option.

    Get an optional boolean option.

    sectionName

    the section name

    optionName

    the option name

    returns

    Some(boolean) or None.

  19. def getBooleanOrElse (sectionName: String, optionName: String, default: Boolean) : Boolean

    Get a boolean option, applying a default if not found.

    Get a boolean option, applying a default if not found.

    sectionName

    the section name

    optionName

    the option name

    default

    the default value

    returns

    the integer result

  20. def getClass () : java.lang.Class[_]

    Returns a representation that corresponds to the dynamic class of the receiver object.

    Returns a representation that corresponds to the dynamic class of the receiver object.

    The nature of the representation is platform dependent.

    returns

    a representation that corresponds to the dynamic class of the receiver object.

    attributes: final
    definition classes: AnyRef
  21. def getInt (sectionName: String, optionName: String) : Option[Int]

    Get an optional integer option.

    Get an optional integer option.

    sectionName

    the section name

    optionName

    the option name

    returns

    Some(integer) or None.

  22. def getIntOrElse (sectionName: String, optionName: String, default: Int) : Int

    Get an integer option, applying a default if not found.

    Get an integer option, applying a default if not found.

    sectionName

    the section name

    optionName

    the option name

    default

    the default value

    returns

    the integer result

  23. def getOrElse (sectionName: String, optionName: String, default: String) : String

    Works like Map.getOrElse(), returning an option value or a default, if the option has no value.

    Works like Map.getOrElse(), returning an option value or a default, if the option has no value. Does not throw exceptions. Calling this function is the same as:

    get(sectionName, optionName).getOrElse(default)
    
    sectionName

    the section name

    optionName

    the option name

    default

    the default value

    returns

    The option's value if the section and option exist, the default if either the section or option cannot be found.

  24. def getSection (name: String) : Option[Section]

    Get a section.

    Get a section. Similar to Map.get, this method returns Some(Section)if the section exists, and None if it does not.

    name

    the section to get

    returns

    Some(Section) or None

  25. def hasSection (sectionName: String) : Boolean

    Determine whether the configuration contains a named section.

    Determine whether the configuration contains a named section.

    sectionName

    the new section's name

    returns

    true if the configuration has a section with that name, false otherwise

  26. def hashCode () : Int

    Returns a hash code value for the object.

    Returns a hash code value for the object.

    The default hashing algorithm is platform dependent.

    Note that it is allowed for two objects to have identical hash codes (o1.hashCode.equals(o2.hashCode)) yet not be equal (o1.equals(o2) returns false). A degenerate implementation could always return 0. However, it is required that if two objects are equal (o1.equals(o2) returns true) that they have identical hash codes (o1.hashCode.equals(o2.hashCode)). Therefore, when overriding this method, be sure to verify that the behavior is consistent with the equals method.

    returns

    the hash code value for the object.

    definition classes: AnyRef → Any
  27. def isInstanceOf [T0] : Boolean

    This method is used to test whether the dynamic type of the receiver object is T0.

    This method is used to test whether the dynamic type of the receiver object is T0.

    Note that the test result of the test is modulo Scala's erasure semantics. Therefore the expression1.isInstanceOf[String] will return false, while the expression List(1).isInstanceOf[List[String]] will return true. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the requested typed.

    returns

    true if the receiver object is an instance of erasure of type T0; false otherwise.

    attributes: final
    definition classes: Any
  28. def load (source: Source, safe: Boolean =false) : Configuration

    Load configuration data from the specified source into this object.

    Load configuration data from the specified source into this object. Clears the configuration first.

    source

    scala.io.Source object to read

    safe

    Whether an exception should be thrown for bad variable substitutions (false) or not (true).

    returns

    this object, for convenience

  29. def matchingSections (regex: Regex) : Seq[Section]

    Return a sequence of sections whose name match matches a regular expression.

    Return a sequence of sections whose name match matches a regular expression.

    regex

    the regular expression to match

  30. def ne (arg0: AnyRef) : Boolean

    o.ne(arg0) is the same as !(o.eq(arg0)).

    o.ne(arg0) is the same as !(o.eq(arg0)).

    arg0

    the object to compare against this object for reference dis-equality.

    returns

    false if the argument is not a reference to the receiver object; true otherwise.

    attributes: final
    definition classes: AnyRef
  31. def notify () : Unit

    Wakes up a single thread that is waiting on the receiver object's monitor.

    Wakes up a single thread that is waiting on the receiver object's monitor.

    attributes: final
    definition classes: AnyRef
  32. def notifyAll () : Unit

    Wakes up all threads that are waiting on the receiver object's monitor.

    Wakes up all threads that are waiting on the receiver object's monitor.

    attributes: final
    definition classes: AnyRef
  33. def option (sectionName: String, optionName: String, default: String) : String

    Get the value for an option in a section, supplying a default if the option or the section doesn't exist.

    Get the value for an option in a section, supplying a default if the option or the section doesn't exist. Exceptions for variable substitution errors are still thrown.

    sectionName

    the section name

    optionName

    the option name

    default

    default value

    returns

    the option's value (which may be the default)

      deprecated:
    1. Use get() or getOrElse(), instead

  34. def option (sectionName: String, optionName: String) : String

    Get the value for an option in a section.

    Get the value for an option in a section.

    sectionName

    the section name

    optionName

    the option name

    returns

    the option's value

      deprecated:
    1. Use get() or getOrElse(), instead

  35. def optionNames (sectionName: String) : Iterator[String]

    Get the list of option names.

    Get the list of option names.

    sectionName

    the section's name

    returns

    a list of option names in that section

  36. def options (sectionName: String) : Map[String, String]

    Get all options in a section.

    Get all options in a section.

    sectionName

    the section name

    returns

    a map of all options and their values for the section. If the section doesn't exist, an empty map is returned.

  37. def putOption (sectionName: String, optionName: String, value: String, preCheck: (String, Map[String, String]) ⇒ Unit) : Unit

    Puts an option in the configuration, running the specified pre-check logic first.

    Puts an option in the configuration, running the specified pre-check logic first.

    attributes: protected
  38. def sectionNames : Iterator[String]

    Get the list of section names.

    Get the list of section names.

    returns

    the section names, in a iterator

  39. def setOption (sectionName: String, optionName: String, value: String) : Unit

    Put an option name and value to a section, overwriting any existing instance of that option.

    Put an option name and value to a section, overwriting any existing instance of that option. Unlike addOption(), this method will not throw DuplicateOptionException.

    sectionName

    the section name

    optionName

    the option name, which will be transformed

    value

    the option's value

  40. def synchronized [T0] (arg0: T0) : T0

    attributes: final
    definition classes: AnyRef
  41. def toString () : String

    Returns a string representation of the object.

    Returns a string representation of the object.

    The default representation is platform dependent.

    returns

    a string representation of the object.

    definition classes: AnyRef → Any
  42. def transformOptionName (option: String) : String

    Transform an option (key) to a consistent form.

    Transform an option (key) to a consistent form. The default version of this method forces the option name to lower case.

    option

    the option name

    returns

    the transformed option name

  43. def wait () : Unit

    attributes: final
    definition classes: AnyRef
  44. def wait (arg0: Long, arg1: Int) : Unit

    attributes: final
    definition classes: AnyRef
  45. def wait (arg0: Long) : Unit

    attributes: final
    definition classes: AnyRef

Inherited from AnyRef

Inherited from Any