Class INIConfiguration
- All Implemented Interfaces:
Cloneable
,Configuration
,EventSource
,FileBasedConfiguration
,HierarchicalConfiguration<ImmutableNode>
,ImmutableConfiguration
,ImmutableHierarchicalConfiguration
,FileBased
,SynchronizerSupport
,InMemoryNodeModelSupport
,NodeKeyResolver<ImmutableNode>
,NodeModelSupport<ImmutableNode>
A specialized hierarchical configuration implementation for parsing ini files.
An initialization or ini file is a configuration file typically found on Microsoft's Windows operating system and contains data for Windows based applications.
Although popularized by Windows, ini files can be used on any system or platform due to the fact that they are merely text files that can easily be parsed and modified by both humans and computers.
A typical ini file could look something like:
[section1] ; this is a comment! var1 = foo var2 = bar [section2] var1 = doo
The format of ini files is fairly straight forward and is composed of three components:
- Sections: Ini files are split into sections, each section starting with a section declaration. A section declaration starts with a '[' and ends with a ']'. Sections occur on one line only.
- Parameters: Items in a section are known as parameters. Parameters have a typical
key = value
format. - Comments: Lines starting with a ';' are assumed to be comments.
There are various implementations of the ini file format by various vendors which has caused a number of differences to appear. As far as possible this configuration tries to be lenient and support most of the differences.
Some of the differences supported are as follows:
- Comments: The '#' character is also accepted as a comment signifier.
- Key value separator: The ':' character is also accepted in place of '=' to separate keys and values in
parameters, for example
var1 : foo
. - Duplicate sections: Typically duplicate sections are not allowed, this configuration does however support this feature. In the event of a duplicate section, the two section's values are merged so that there is only a single section. Note: This also affects the internal data of the configuration. If it is saved, only a single section is written!
- Duplicate parameters: Typically duplicate parameters are only allowed if they are in two different sections, thus they are local to sections; this configuration simply merges duplicates; if a section has a duplicate parameter the values are then added to the key as a list.
Global parameters are also allowed; any parameters declared before a section is declared are added to a global section. It is important to note that this global section does not have a name.
In all instances, a parameter's key is prepended with its section name and a '.' (period). Thus a parameter named
"var1" in "section1" will have the key section1.var1
in this configuration. (This is the default behavior.
Because this is a hierarchical configuration you can change this by setting a different
ExpressionEngine
.)
Implementation Details:
Consider the following ini file:default = ok [section1] var1 = foo var2 = doodle [section2] ; a comment var1 = baz var2 = shoodle bad = = worse [section3] # another comment var1 : foo var2 : bar var5 : test1 [section3] var3 = foo var4 = bar var5 = test2 [sectionSeparators] passwd : abc=def a:b = "value"
This ini file will be parsed without error. Note:
- The parameter named "default" is added to the global section, it's value is accessed simply using
getProperty("default")
. - Section 1's parameters can be accessed using
getProperty("section1.var1")
. - The parameter named "bad" simply adds the parameter with an empty value.
- The empty key with value "= worse" is added using a key consisting of a single space character. This key is still
added to section 2 and the value can be accessed using
getProperty("section2. ")
, notice the period '.' and the space following the section name. - Section three uses both '=' and ':' to separate keys and values.
- Section 3 has a duplicate key named "var5". The value for this key is [test1, test2], and is represented as a List.
- The section called sectionSeparators demonstrates how the configuration deals with multiple occurrences
of separator characters. Per default the first separator character in a line is detected and used to split the key
from the value. Therefore the first property definition in this section has the key
passwd
and the valueabc=def
. This default behavior can be changed by using quotes. If there is a separator character before the first quote character (ignoring whitespace), this character is used as separator. Thus the second property definition in the section has the keya:b
and the valuevalue
.
Internally, this configuration maps the content of the represented ini file to its node structure in the following way:
- Sections are represented by direct child nodes of the root node.
- For the content of a section, corresponding nodes are created as children of the section node.
This explains how the keys for the properties can be constructed. You can also use other methods of
HierarchicalConfiguration
for querying or manipulating the hierarchy of configuration nodes, for instance the
configurationAt()
method for obtaining the data of a specific section. However, be careful that the storage
scheme described above is not violated (e.g. by adding multiple levels of nodes or inserting duplicate section
nodes). Otherwise, the special methods for ini configurations may not work correctly!
The set of sections in this configuration can be retrieved using the getSections()
method. For obtaining a
SubnodeConfiguration
with the content of a specific section the getSection()
method can be used.
Like other Configuration
implementations, this class uses a Synchronizer
object to control concurrent
access. By choosing a suitable implementation of the Synchronizer
interface, an instance can be made
thread-safe or not. Note that access to most of the properties typically set through a builder is not protected by
the Synchronizer
. The intended usage is that these properties are set once at construction time through the
builder and after that remain constant. If you wish to change such properties during life time of an instance, you
have to use the lock()
and unlock()
methods manually to ensure that other threads see your changes.
As this class extends AbstractConfiguration
, all basic features like variable interpolation, list handling,
or data type conversions are available as well. This is described in the chapter
Basic features
and AbstractConfiguration of the user's guide.
Note that this configuration does not support properties with null values. Such properties are considered to be section nodes.
- Since:
- 1.6
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic class
Builds instances of INIConfiguration.private static class
A specialized node model implementation for the sub configuration representing the global section of the INI file.Nested classes/interfaces inherited from class org.apache.commons.configuration2.BaseHierarchicalConfiguration
BaseHierarchicalConfiguration.BuilderVisitor
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected static final String
The default characters that signal the start of a comment line.private String
The characters used to separate keys from values when reading an INI file.private static final String
The line continuation character.private static final String
Constant for the line separator.private static final String
The characters used for quoting values.private boolean
The flag for decision, whether inline comments on the section line are allowed.protected static final String
The default characters used to separate keys from values.private String
The separator used when reading an INI file.private String
The separator used when writing an INI file. -
Constructor Summary
ConstructorsModifierConstructorDescriptionCreate a new empty INI Configuration.private
INIConfiguration
(boolean sectionInLineCommentsAllowed) Create a new empty INI Configuration with option to allow inline comments on the section line.Creates a new instance ofINIConfiguration
with the content of the specifiedHierarchicalConfiguration
. -
Method Summary
Modifier and TypeMethodDescriptionstatic INIConfiguration.Builder
builder()
Creates a new builder.private static ImmutableNode
createNewRootNode
(ImmutableNode.Builder rootBuilder, Map<String, ImmutableNode.Builder> sectionBuilders) Creates a new root node from the builders constructed while reading the configuration file.private void
createNodeBuilders
(BufferedReader in, ImmutableNode.Builder rootBuilder, Map<String, ImmutableNode.Builder> sectionBuilders) Reads the content of an INI file from the passed in reader and creates a structure of builders for constructing theImmutableNode
objects representing the data.private void
createValueNodes
(ImmutableNode.Builder sectionBuilder, String key, String value) Creates the node(s) for the given key value-pair.private String
escapeComments
(String value) Escapes comment characters in the given value.private String
escapeValue
(String value) Escapes the given property value before it is written.private static int
findFirstOccurrence
(String line, String separators) Checks for the occurrence of the specified separators in the given line.private int
findSeparator
(String line) Tries to find the index of the separator character in the given string.private static int
findSeparatorBeforeQuote
(String line, int quoteIndex) Searches for a separator character directly before a quoting character.Get comment leading separator used in INI reading.private SubnodeConfiguration
Creates a sub configuration for the global section of the represented INI configuration.getSection
(String name) Gets a configuration with the content of the specified section.Return a set containing the sections in this ini configuration.Get separator used in INI reading.Get separator used in INI output.private boolean
isCommentChar
(char c) Tests whether the specified character is a comment character.protected boolean
isCommentLine
(String line) Determine if the given line is a comment line.private static boolean
isNonStrictSection
(String line) Determine if the given line contains a section - inline comments are allowed.protected boolean
isSectionLine
(String line) Determine if the given line is a section.private static boolean
isSectionNode
(ImmutableNode node) Checks whether the specified configuration node represents a section.private static boolean
isStrictSection
(String line) Determine if the entire given line is a section - inline comments are not allowed.private static boolean
lineContinues
(String line) Tests whether the specified string contains a line continuation marker.private boolean
lineContinues
(String line, int pos) Tests whether the specified string contains a line continuation marker after the specified position.private String
parseValue
(String val, BufferedReader reader) Parse the value to remove the quotes and ignoring the comment.void
Load the configuration from the given reader.void
setCommentLeadingCharsUsedInInput
(String separator) Allows setting the leading comment separator which is used in reading an INI filevoid
setSeparatorUsedInInput
(String separator) Allows setting the key and value separator which is used in reading an INI filevoid
setSeparatorUsedInOutput
(String separator) Allows setting the key and value separator which is used for the creation of the resulting INI outputvoid
Save the configuration to the specified writer.private void
writeProperty
(PrintWriter out, String key, Object value, String separator) Writes data about a property into the given stream.Methods inherited from class org.apache.commons.configuration2.BaseHierarchicalConfiguration
childConfigurationsAt, childConfigurationsAt, cloneNodeModel, configurationAt, configurationAt, configurationsAt, configurationsAt, createSubConfigurationForTrackedNode, getNodeModel, getSubConfigurationNodeSelector, getSubConfigurationParentModel, immutableChildConfigurationsAt, immutableConfigurationAt, immutableConfigurationAt, immutableConfigurationsAt, initSubConfigurationForThisParent, interpolatedConfiguration, subnodeConfigurationChanged, subset
Methods inherited from class org.apache.commons.configuration2.AbstractHierarchicalConfiguration
addNodes, addNodesInternal, addPropertyDirect, addPropertyInternal, clearInternal, clearPropertyDirect, clearTree, clearTreeInternal, clone, containsKeyInternal, fetchNodeList, getExpressionEngine, getKeysInternal, getKeysInternal, getMaxIndex, getMaxIndexInternal, getModel, getPropertyInternal, getRootElementName, getRootElementNameInternal, isEmptyInternal, nodeDefined, nodeKey, resolveAddKey, resolveKey, resolveNodeKey, resolveUpdateKey, setExpressionEngine, setPropertyInternal, sizeInternal, toString
Methods inherited from class org.apache.commons.configuration2.AbstractConfiguration
addErrorLogListener, addProperty, append, beginRead, beginWrite, clear, clearProperty, cloneInterpolator, containsKey, copy, endRead, endWrite, get, get, getArray, getArray, getBigDecimal, getBigDecimal, getBigInteger, getBigInteger, getBoolean, getBoolean, getBoolean, getByte, getByte, getByte, getCollection, getCollection, getConfigurationDecoder, getConversionHandler, getDouble, getDouble, getDouble, getDuration, getDuration, getEncodedString, getEncodedString, getFloat, getFloat, getFloat, getInt, getInt, getInteger, getInterpolator, getKeys, getKeys, getList, getList, getList, getList, getListDelimiterHandler, getLogger, getLong, getLong, getLong, getProperties, getProperties, getProperty, getShort, getShort, getShort, getString, getString, getStringArray, getSynchronizer, immutableSubset, initLogger, installInterpolator, interpolate, interpolate, isEmpty, isScalarValue, isThrowExceptionOnMissing, lock, setConfigurationDecoder, setConversionHandler, setDefaultLookups, setInterpolator, setListDelimiterHandler, setLogger, setParentInterpolator, setPrefixLookups, setProperty, setSynchronizer, setThrowExceptionOnMissing, size, unlock
Methods inherited from class org.apache.commons.configuration2.event.BaseEventSource
addEventListener, clearErrorListeners, clearEventListeners, copyEventListeners, createErrorEvent, createEvent, fireError, fireEvent, getEventListenerRegistrations, getEventListeners, isDetailEvents, removeEventListener, setDetailEvents
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.apache.commons.configuration2.Configuration
addProperty, clear, clearProperty, getInterpolator, installInterpolator, setInterpolator, setProperty, subset
Methods inherited from interface org.apache.commons.configuration2.ImmutableConfiguration
containsKey, get, get, getArray, getArray, getBigDecimal, getBigDecimal, getBigInteger, getBigInteger, getBoolean, getBoolean, getBoolean, getByte, getByte, getByte, getCollection, getCollection, getDouble, getDouble, getDouble, getDuration, getDuration, getEncodedString, getEncodedString, getEnum, getEnum, getFloat, getFloat, getFloat, getInt, getInt, getInteger, getKeys, getKeys, getList, getList, getList, getList, getLong, getLong, getLong, getProperties, getProperty, getShort, getShort, getShort, getString, getString, getStringArray, immutableSubset, isEmpty, size
Methods inherited from interface org.apache.commons.configuration2.sync.SynchronizerSupport
getSynchronizer, lock, setSynchronizer, unlock
-
Field Details
-
COMMENT_CHARS
The default characters that signal the start of a comment line.- See Also:
-
SEPARATOR_CHARS
The default characters used to separate keys from values.- See Also:
-
LINE_SEPARATOR
Constant for the line separator. -
QUOTE_CHARACTERS
The characters used for quoting values.- See Also:
-
LINE_CONT
The line continuation character.- See Also:
-
separatorUsedInOutput
The separator used when writing an INI file. -
separatorUsedInInput
The separator used when reading an INI file. -
commentCharsUsedInInput
The characters used to separate keys from values when reading an INI file. -
sectionInLineCommentsAllowed
private boolean sectionInLineCommentsAllowedThe flag for decision, whether inline comments on the section line are allowed.
-
-
Constructor Details
-
INIConfiguration
public INIConfiguration()Create a new empty INI Configuration. -
INIConfiguration
Creates a new instance ofINIConfiguration
with the content of the specifiedHierarchicalConfiguration
.- Parameters:
c
- the configuration to be copied- Since:
- 2.0
-
INIConfiguration
private INIConfiguration(boolean sectionInLineCommentsAllowed) Create a new empty INI Configuration with option to allow inline comments on the section line.- Parameters:
sectionInLineCommentsAllowed
- when true inline comments on the section line are allowed
-
-
Method Details
-
builder
Creates a new builder.- Returns:
- a new builder.
- Since:
- 2.9.0
-
getSeparatorUsedInOutput
Get separator used in INI output. seesetSeparatorUsedInOutput
for further explanation- Returns:
- the current separator for writing the INI output
- Since:
- 2.2
-
setSeparatorUsedInOutput
Allows setting the key and value separator which is used for the creation of the resulting INI output- Parameters:
separator
- String of the new separator for INI output- Since:
- 2.2
-
getSeparatorUsedInInput
Get separator used in INI reading. seesetSeparatorUsedInInput
for further explanation- Returns:
- the current separator for reading the INI input
- Since:
- 2.5
-
setSeparatorUsedInInput
Allows setting the key and value separator which is used in reading an INI file- Parameters:
separator
- String of the new separator for INI reading- Since:
- 2.5
-
getCommentLeadingCharsUsedInInput
Get comment leading separator used in INI reading. seesetCommentLeadingCharsUsedInInput
for further explanation- Returns:
- the current separator for reading the INI input
- Since:
- 2.5
-
setCommentLeadingCharsUsedInInput
Allows setting the leading comment separator which is used in reading an INI file- Parameters:
separator
- String of the new separator for INI reading- Since:
- 2.5
-
write
Save the configuration to the specified writer.- Specified by:
write
in interfaceFileBased
- Parameters:
writer
- - The writer to save the configuration to.- Throws:
ConfigurationException
- If an error occurs while writing the configurationIOException
- if an I/O error occurs.
-
read
Load the configuration from the given reader. Note that theclear()
method is not called so the configuration read in will be merged with the current configuration.- Specified by:
read
in interfaceFileBased
- Parameters:
in
- the reader to read the configuration from.- Throws:
ConfigurationException
- If an error occurs while reading the configurationIOException
- if an I/O error occurs.
-
createNewRootNode
private static ImmutableNode createNewRootNode(ImmutableNode.Builder rootBuilder, Map<String, ImmutableNode.Builder> sectionBuilders) Creates a new root node from the builders constructed while reading the configuration file.- Parameters:
rootBuilder
- the builder for the top-level sectionsectionBuilders
- a map storing the section builders- Returns:
- the root node of the newly created hierarchy
-
createNodeBuilders
private void createNodeBuilders(BufferedReader in, ImmutableNode.Builder rootBuilder, Map<String, ImmutableNode.Builder> sectionBuilders) throws IOExceptionReads the content of an INI file from the passed in reader and creates a structure of builders for constructing theImmutableNode
objects representing the data.- Parameters:
in
- the readerrootBuilder
- the builder for the top-level sectionsectionBuilders
- a map storing the section builders- Throws:
IOException
- if an I/O error occurs.
-
createValueNodes
Creates the node(s) for the given key value-pair. If delimiter parsing is enabled, the value string is split if possible, and for each single value a node is created. Otherwise only a single node is added to the section.- Parameters:
sectionBuilder
- the section builder for adding new nodeskey
- the keyvalue
- the value string
-
writeProperty
Writes data about a property into the given stream.- Parameters:
out
- the output streamkey
- the keyvalue
- the value
-
parseValue
Parse the value to remove the quotes and ignoring the comment. Example:"value" ; comment -> value
'value' ; comment -> value
Note that a comment character is only recognized if there is at least one whitespace character before it. So it can appear in the property value, e.g.:C:\\Windows;C:\\Windows\\system32
- Parameters:
val
- the value to be parsedreader
- the reader (needed if multiple lines have to be read)- Throws:
IOException
- if an IO error occurs
-
lineContinues
Tests whether the specified string contains a line continuation marker.- Parameters:
line
- the string to check- Returns:
- a flag whether this line continues
-
lineContinues
Tests whether the specified string contains a line continuation marker after the specified position. This method parses the string to remove a comment that might be present. Then it checks whether a line continuation marker can be found at the end.- Parameters:
line
- the line to checkpos
- the start position- Returns:
- a flag whether this line continues
-
isCommentChar
private boolean isCommentChar(char c) Tests whether the specified character is a comment character.- Parameters:
c
- the character- Returns:
- a flag whether this character starts a comment
-
findSeparator
Tries to find the index of the separator character in the given string. This method checks for the presence of separator characters in the given string. If multiple characters are found, the first one is assumed to be the correct separator. If there are quoting characters, they are taken into account, too.- Parameters:
line
- the line to be checked- Returns:
- the index of the separator character or -1 if none is found
-
findFirstOccurrence
Checks for the occurrence of the specified separators in the given line. The index of the first separator is returned.- Parameters:
line
- the line to be investigatedseparators
- a string with the separator characters to look for- Returns:
- the lowest index of a separator character or -1 if no separator is found
-
findSeparatorBeforeQuote
Searches for a separator character directly before a quoting character. If the first non-whitespace character before a quote character is a separator, it is considered the "real" separator in this line - even if there are other separators before.- Parameters:
line
- the line to be investigatedquoteIndex
- the index of the quote character- Returns:
- the index of the separator before the quote or < 0 if there is none
-
escapeValue
Escapes the given property value before it is written. This method add quotes around the specified value if it contains a comment character and handles list delimiter characters.- Parameters:
value
- the string to be escaped
-
escapeComments
Escapes comment characters in the given value.- Parameters:
value
- the value to be escaped- Returns:
- the value with comment characters escaped
-
isCommentLine
Determine if the given line is a comment line.- Parameters:
line
- The line to check.- Returns:
- true if the line is empty or starts with one of the comment characters
-
isSectionLine
Determine if the given line is a section.- Parameters:
line
- The line to check.- Returns:
- true if the line contains a section
-
isStrictSection
Determine if the entire given line is a section - inline comments are not allowed.- Parameters:
line
- The line to check.- Returns:
- true if the entire line is a section
-
isNonStrictSection
Determine if the given line contains a section - inline comments are allowed.- Parameters:
line
- The line to check.- Returns:
- true if the line contains a section
-
getSections
Return a set containing the sections in this ini configuration. Note that changes to this set do not affect the configuration.- Returns:
- a set containing the sections.
-
getSection
Gets a configuration with the content of the specified section. This provides an easy way of working with a single section only. The way this configuration is structured internally, this method is very similar to callingHierarchicalConfiguration.configurationAt(String)
with the name of the section in question. There are the following differences however:- This method never throws an exception. If the section does not exist, it is created now. The configuration returned in this case is empty.
- If section is contained multiple times in the configuration, the configuration returned by this method is
initialized with the first occurrence of the section. (This can only happen if
addProperty()
has been used in a way that does not conform to the storage scheme used byINIConfiguration
. If used correctly, there will not be duplicate sections.) - There is special support for the global section: Passing in null as section name returns a configuration with the content of the global section (which may also be empty).
- Parameters:
name
- the name of the section in question; null represents the global section- Returns:
- a configuration containing only the properties of the specified section
-
getGlobalSection
Creates a sub configuration for the global section of the represented INI configuration.- Returns:
- the sub configuration for the global section
-
isSectionNode
Checks whether the specified configuration node represents a section.- Parameters:
node
- the node in question- Returns:
- a flag whether this node represents a section
-