org.apache.commons.configuration
Class PropertiesConfiguration

java.lang.Object
  extended by org.apache.commons.configuration.event.EventSource
      extended by org.apache.commons.configuration.AbstractConfiguration
          extended by org.apache.commons.configuration.BaseConfiguration
              extended by org.apache.commons.configuration.AbstractFileConfiguration
                  extended by org.apache.commons.configuration.PropertiesConfiguration
All Implemented Interfaces:
java.lang.Cloneable, Configuration, FileConfiguration
Direct Known Subclasses:
XMLPropertiesConfiguration

public class PropertiesConfiguration
extends AbstractFileConfiguration

This is the "classic" Properties loader which loads the values from a single or multiple files (which can be chained with "include =". All given path references are either absolute or relative to the file name supplied in the constructor.

In this class, empty PropertyConfigurations can be built, properties added and later saved. include statements are (obviously) not supported if you don't construct a PropertyConfiguration from a file.

The properties file syntax is explained here, basically it follows the syntax of the stream parsed by Properties.load(java.io.Reader) and adds several useful extensions:

Here is an example of a valid extended properties file:

      # lines starting with # are comments

      # This is the simplest property
      key = value

      # A long property may be separated on multiple lines
      longvalue = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

      # This is a property with many tokens
      tokens_on_a_line = first token, second token

      # This sequence generates exactly the same result
      tokens_on_multiple_lines = first token
      tokens_on_multiple_lines = second token

      # commas may be escaped in tokens
      commas.escaped = Hi\, what'up?

      # properties can reference other properties
      base.prop = /base
      first.prop = ${base.prop}/first
      second.prop = ${first.prop}/second
 

A PropertiesConfiguration object is associated with an instance of the PropertiesConfigurationLayout class, which is responsible for storing the layout of the parsed properties file (i.e. empty lines, comments, and such things). The getLayout() method can be used to obtain this layout object. With setLayout() a new layout object can be set. This should be done before a properties file was loaded.

Note:Configuration objects of this type can be read concurrently by multiple threads. However if one of these threads modifies the object, synchronization has to be performed manually.

Version:
$Id: PropertiesConfiguration.java 550047 2007-06-23 14:44:15Z oheger $
Author:
Stefano Mazzocchi, Jon S. Stevens, Dave Bryson, Geir Magnusson Jr., Leon Messerschmidt, Kent Johnson, Daniel Rall, Ilkka Priha, Jason van Zyl, Martin Poeschl, Henning P. Schmiedehausen, Eric Pugh, Oliver Heger, Emmanuel Bourg
See Also:
Properties.load(java.io.Reader)

Nested Class Summary
static class PropertiesConfiguration.PropertiesReader
          This class is used to read properties lines.
static class PropertiesConfiguration.PropertiesWriter
          This class is used to write properties lines.
 
Field Summary
(package private) static java.lang.String COMMENT_CHARS
          Constant for the supported comment characters.
private static java.lang.String DEFAULT_ENCODING
          The default encoding (ISO-8859-1 as specified by http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html)
private static java.lang.String ESCAPE
          Constant for the escaping character.
private static int HEX_RADIX
          Constant for the radix of hex numbers.
private static java.lang.String include
          This is the name of the property that can point to other properties file for including other properties files.
private  boolean includesAllowed
          Allow file inclusion or not
private  PropertiesConfigurationLayout layout
          Stores the layout object.
private static java.lang.String LINE_SEPARATOR
          Constant for the platform specific line separator.
private static char[] SEPARATORS
          The list of possible key/value separators
private static int UNICODE_LEN
          Constant for the length of a unicode literal.
private static char[] WHITE_SPACE
          The white space characters used as key/value separators.
 
Fields inherited from class org.apache.commons.configuration.AbstractFileConfiguration
autoSave, basePath, EVENT_RELOAD, fileName, strategy
 
Fields inherited from class org.apache.commons.configuration.AbstractConfiguration
END_TOKEN, EVENT_ADD_PROPERTY, EVENT_CLEAR, EVENT_CLEAR_PROPERTY, EVENT_READ_PROPERTY, EVENT_SET_PROPERTY, START_TOKEN
 
Constructor Summary
PropertiesConfiguration()
          Creates an empty PropertyConfiguration object which can be used to synthesize a new Properties file by adding values and then saving().
PropertiesConfiguration(java.io.File file)
          Creates and loads the extended properties from the specified file.
PropertiesConfiguration(java.lang.String fileName)
          Creates and loads the extended properties from the specified file.
PropertiesConfiguration(java.net.URL url)
          Creates and loads the extended properties from the specified URL.
 
Method Summary
 java.lang.Object clone()
          Creates a copy of this object.
protected  PropertiesConfigurationLayout createLayout()
          Creates the associated layout object.
 java.lang.String getHeader()
          Return the comment header.
static java.lang.String getInclude()
          Gets the property value for including other properties files.
 boolean getIncludesAllowed()
          Reports the status of file inclusion.
 PropertiesConfigurationLayout getLayout()
          Returns the associated layout object.
(package private) static boolean isCommentLine(java.lang.String line)
          Tests whether a line is a comment, i.e.
 void load(java.io.Reader in)
          Load the properties from the given reader.
private  void loadIncludeFile(java.lang.String fileName)
          Helper method for loading an included properties file.
(package private)  boolean propertyLoaded(java.lang.String key, java.lang.String value)
          This method is invoked by the associated PropertiesConfigurationLayout object for each property definition detected in the parsed properties file.
 void save(java.io.Writer writer)
          Save the configuration to the specified stream.
 void setBasePath(java.lang.String basePath)
          Extend the setBasePath method to turn includes on and off based on the existence of a base path.
 void setHeader(java.lang.String header)
          Set the comment header.
static void setInclude(java.lang.String inc)
          Sets the property value for including other properties files.
protected  void setIncludesAllowed(boolean includesAllowed)
          Controls whether additional files can be loaded by the include = statement or not.
 void setLayout(PropertiesConfigurationLayout layout)
          Sets the associated layout object.
protected static java.lang.String unescapeJava(java.lang.String str, char delimiter)
          Unescapes any Java literals found in the String to a Writer.
 
Methods inherited from class org.apache.commons.configuration.AbstractFileConfiguration
addProperty, clearProperty, containsKey, enterNoReload, exitNoReload, fireEvent, getBasePath, getEncoding, getFile, getFileName, getKeys, getPath, getProperty, getReloadingStrategy, getURL, isAutoSave, isEmpty, load, load, load, load, load, load, possiblySave, reload, save, save, save, save, save, save, setAutoSave, setEncoding, setFile, setFileName, setPath, setProperty, setReloadingStrategy, setURL
 
Methods inherited from class org.apache.commons.configuration.BaseConfiguration
addPropertyDirect, clear, clearPropertyDirect
 
Methods inherited from class org.apache.commons.configuration.AbstractConfiguration
addErrorLogListener, append, copy, createInterpolator, getBigDecimal, getBigDecimal, getBigInteger, getBigInteger, getBoolean, getBoolean, getBoolean, getByte, getByte, getByte, getDefaultListDelimiter, getDelimiter, getDouble, getDouble, getDouble, getFloat, getFloat, getFloat, getInt, getInt, getInteger, getInterpolator, getKeys, getList, getList, getListDelimiter, getLogger, getLong, getLong, getLong, getProperties, getProperties, getShort, getShort, getShort, getString, getString, getStringArray, getSubstitutor, interpolate, interpolate, interpolatedConfiguration, interpolateHelper, isDelimiterParsingDisabled, isThrowExceptionOnMissing, resolveContainerStore, setDefaultListDelimiter, setDelimiter, setDelimiterParsingDisabled, setListDelimiter, setLogger, setThrowExceptionOnMissing, subset
 
Methods inherited from class org.apache.commons.configuration.event.EventSource
addConfigurationListener, addErrorListener, clearConfigurationListeners, clearErrorListeners, createErrorEvent, createEvent, fireError, getConfigurationListeners, getErrorListeners, isDetailEvents, removeConfigurationListener, removeErrorListener, setDetailEvents
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface org.apache.commons.configuration.Configuration
clear, getBigDecimal, getBigDecimal, getBigInteger, getBigInteger, getBoolean, getBoolean, getBoolean, getByte, getByte, getByte, getDouble, getDouble, getDouble, getFloat, getFloat, getFloat, getInt, getInt, getInteger, getKeys, getList, getList, getLong, getLong, getLong, getProperties, getShort, getShort, getShort, getString, getString, getStringArray, subset
 

Field Detail

COMMENT_CHARS

static final java.lang.String COMMENT_CHARS
Constant for the supported comment characters.

See Also:
Constant Field Values

include

private static java.lang.String include
This is the name of the property that can point to other properties file for including other properties files.


SEPARATORS

private static final char[] SEPARATORS
The list of possible key/value separators


WHITE_SPACE

private static final char[] WHITE_SPACE
The white space characters used as key/value separators.


DEFAULT_ENCODING

private static final java.lang.String DEFAULT_ENCODING
The default encoding (ISO-8859-1 as specified by http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html)

See Also:
Constant Field Values

LINE_SEPARATOR

private static final java.lang.String LINE_SEPARATOR
Constant for the platform specific line separator.


ESCAPE

private static final java.lang.String ESCAPE
Constant for the escaping character.

See Also:
Constant Field Values

HEX_RADIX

private static final int HEX_RADIX
Constant for the radix of hex numbers.

See Also:
Constant Field Values

UNICODE_LEN

private static final int UNICODE_LEN
Constant for the length of a unicode literal.

See Also:
Constant Field Values

layout

private PropertiesConfigurationLayout layout
Stores the layout object.


includesAllowed

private boolean includesAllowed
Allow file inclusion or not

Constructor Detail

PropertiesConfiguration

public PropertiesConfiguration()
Creates an empty PropertyConfiguration object which can be used to synthesize a new Properties file by adding values and then saving().


PropertiesConfiguration

public PropertiesConfiguration(java.lang.String fileName)
                        throws ConfigurationException
Creates and loads the extended properties from the specified file. The specified file can contain "include = " properties which then are loaded and merged into the properties.

Parameters:
fileName - The name of the properties file to load.
Throws:
ConfigurationException - Error while loading the properties file

PropertiesConfiguration

public PropertiesConfiguration(java.io.File file)
                        throws ConfigurationException
Creates and loads the extended properties from the specified file. The specified file can contain "include = " properties which then are loaded and merged into the properties. If the file does not exist, an empty configuration will be created. Later the save() method can be called to save the properties to the specified file.

Parameters:
file - The properties file to load.
Throws:
ConfigurationException - Error while loading the properties file

PropertiesConfiguration

public PropertiesConfiguration(java.net.URL url)
                        throws ConfigurationException
Creates and loads the extended properties from the specified URL. The specified file can contain "include = " properties which then are loaded and merged into the properties.

Parameters:
url - The location of the properties file to load.
Throws:
ConfigurationException - Error while loading the properties file
Method Detail

getInclude

public static java.lang.String getInclude()
Gets the property value for including other properties files. By default it is "include".

Returns:
A String.

setInclude

public static void setInclude(java.lang.String inc)
Sets the property value for including other properties files. By default it is "include".

Parameters:
inc - A String.

setIncludesAllowed

protected void setIncludesAllowed(boolean includesAllowed)
Controls whether additional files can be loaded by the include = statement or not. Base rule is, that objects created by the empty C'tor can not have included files.

Parameters:
includesAllowed - includesAllowed True if Includes are allowed.

getIncludesAllowed

public boolean getIncludesAllowed()
Reports the status of file inclusion.

Returns:
True if include files are loaded.

getHeader

public java.lang.String getHeader()
Return the comment header.

Returns:
the comment header
Since:
1.1

setHeader

public void setHeader(java.lang.String header)
Set the comment header.

Parameters:
header - the header to use
Since:
1.1

getLayout

public PropertiesConfigurationLayout getLayout()
Returns the associated layout object.

Returns:
the associated layout object
Since:
1.3

setLayout

public void setLayout(PropertiesConfigurationLayout layout)
Sets the associated layout object.

Parameters:
layout - the new layout object; can be null, then a new layout object will be created
Since:
1.3

createLayout

protected PropertiesConfigurationLayout createLayout()
Creates the associated layout object. This method is invoked when the layout object is accessed and has not been created yet. Derived classes can override this method to hook in a different layout implementation.

Returns:
the layout object to use
Since:
1.3

load

public void load(java.io.Reader in)
          throws ConfigurationException
Load the properties from the given reader. Note that the clear() method is not called, so the properties contained in the loaded file will be added to the actual set of properties.

Parameters:
in - An InputStream.
Throws:
ConfigurationException - if an error occurs

save

public void save(java.io.Writer writer)
          throws ConfigurationException
Save the configuration to the specified stream.

Parameters:
writer - the output stream used to save the configuration
Throws:
ConfigurationException - if an error occurs

setBasePath

public void setBasePath(java.lang.String basePath)
Extend the setBasePath method to turn includes on and off based on the existence of a base path.

Specified by:
setBasePath in interface FileConfiguration
Overrides:
setBasePath in class AbstractFileConfiguration
Parameters:
basePath - The new basePath to set.

clone

public java.lang.Object clone()
Creates a copy of this object.

Overrides:
clone in class AbstractFileConfiguration
Returns:
the copy

propertyLoaded

boolean propertyLoaded(java.lang.String key,
                       java.lang.String value)
                 throws ConfigurationException
This method is invoked by the associated PropertiesConfigurationLayout object for each property definition detected in the parsed properties file. Its task is to check whether this is a special property definition (e.g. the include property). If not, the property must be added to this configuration. The return value indicates whether the property should be treated as a normal property. If it is false, the layout object will ignore this property.

Parameters:
key - the property key
value - the property value
Returns:
a flag whether this is a normal property
Throws:
ConfigurationException - if an error occurs
Since:
1.3

isCommentLine

static boolean isCommentLine(java.lang.String line)
Tests whether a line is a comment, i.e. whether it starts with a comment character.

Parameters:
line - the line
Returns:
a flag if this is a comment line
Since:
1.3

unescapeJava

protected static java.lang.String unescapeJava(java.lang.String str,
                                               char delimiter)

Unescapes any Java literals found in the String to a Writer.

This is a slightly modified version of the StringEscapeUtils.unescapeJava() function in commons-lang that doesn't drop escaped separators (i.e '\,').

Parameters:
str - the String to unescape, may be null
delimiter - the delimiter for multi-valued properties
Returns:
the processed string
Throws:
java.lang.IllegalArgumentException - if the Writer is null

loadIncludeFile

private void loadIncludeFile(java.lang.String fileName)
                      throws ConfigurationException
Helper method for loading an included properties file. This method is called by load() when an include property is encountered. It tries to resolve relative file names based on the current base path. If this fails, a resolution based on the location of this properties file is tried.

Parameters:
fileName - the name of the file to load
Throws:
ConfigurationException - if loading fails