Class XMLConfiguration
- java.lang.Object
-
- org.apache.commons.configuration2.event.BaseEventSource
-
- org.apache.commons.configuration2.AbstractConfiguration
-
- org.apache.commons.configuration2.AbstractHierarchicalConfiguration<ImmutableNode>
-
- org.apache.commons.configuration2.BaseHierarchicalConfiguration
-
- org.apache.commons.configuration2.XMLConfiguration
-
- All Implemented Interfaces:
java.lang.Cloneable
,Configuration
,EventSource
,FileBasedConfiguration
,HierarchicalConfiguration<ImmutableNode>
,ImmutableConfiguration
,ImmutableHierarchicalConfiguration
,FileBased
,FileLocatorAware
,InputStreamSupport
,SynchronizerSupport
,InMemoryNodeModelSupport
,NodeKeyResolver<ImmutableNode>
,NodeModelSupport<ImmutableNode>
public class XMLConfiguration extends BaseHierarchicalConfiguration implements FileBasedConfiguration, FileLocatorAware, InputStreamSupport
A specialized hierarchical configuration class that is able to parse XML documents.
The parsed document will be stored keeping its structure. The class also tries to preserve as much information from the loaded XML document as possible, including comments and processing instructions. These will be contained in documents created by the
save()
methods, too.Like other file based configuration classes this class maintains the name and path to the loaded configuration file. These properties can be altered using several setter methods, but they are not modified by
save()
andload()
methods. If XML documents contain relative paths to other documents (e.g. to a DTD), these references are resolved based on the path set for this configuration.By inheriting from
AbstractConfiguration
this class provides some extended functionality, e.g. interpolation of property values. Like inPropertiesConfiguration
property values can contain delimiter characters (the comma ',' per default) and are then split into multiple values. This works for XML attributes and text content of elements as well. The delimiter can be escaped by a backslash. As an example consider the following XML fragment:<config> <array>10,20,30,40</array> <scalar>3\,1415</scalar> <cite text="To be or not to be\, this is the question!"/> </config>
Here the content of the
array
element will be split at the commas, so thearray
key will be assigned 4 values. In thescalar
property and thetext
attribute of thecite
element the comma is escaped, so that no splitting is performed.The configuration API allows setting multiple values for a single attribute, e.g. something like the following is legal (assuming that the default expression engine is used):
XMLConfiguration config = new XMLConfiguration(); config.addProperty("test.dir[@name]", "C:\\Temp\\"); config.addProperty("test.dir[@name]", "D:\\Data\\");
However, in XML such a constellation is not supported; an attribute can appear only once for a single element. Therefore, an attempt to save a configuration which violates this condition will throw an exception.
Like other
Configuration
implementations,XMLConfiguration
uses aListDelimiterHandler
object for controlling list split operations. Per default, a list delimiter handler object is set which disables this feature. XML has a built-in support for complex structures including list properties; therefore, list splitting is not that relevant for this configuration type. Nevertheless, by setting an alternativeListDelimiterHandler
implementation, this feature can be enabled. It works as for any other concreteConfiguration
implementation.Whitespace in the content of XML documents is trimmed per default. In most cases this is desired. However, sometimes whitespace is indeed important and should be treated as part of the value of a property as in the following example:
<indent> </indent>
Per default the spaces in the
indent
element will be trimmed resulting in an empty element. To tellXMLConfiguration
that spaces are relevant thexml:space
attribute can be used, which is defined in the XML specification. This will look as follows:<indent xml:space="preserve"> </indent>
The value of the
indent
property will now contain the spaces.XMLConfiguration
implements theFileBasedConfiguration
interface and thus can be used together with a file-based builder to load XML configuration files from various sources like files, URLs, or streams.Like other
Configuration
implementations, this class uses aSynchronizer
object to control concurrent access. By choosing a suitable implementation of theSynchronizer
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 theSynchronizer
. 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 thelock()
andunlock()
methods manually to ensure that other threads see your changes.More information about the basic functionality supported by
XMLConfiguration
can be found at the user's guide at Basic features and AbstractConfiguration. There is also a separate chapter dealing with XML Configurations in special.- Since:
- commons-configuration 1.0
- Version:
- $Id: XMLConfiguration.java 1799980 2017-06-26 20:21:16Z oheger $
- Author:
- Jörg Schaible
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class org.apache.commons.configuration2.BaseHierarchicalConfiguration
BaseHierarchicalConfiguration.BuilderVisitor
-
-
Constructor Summary
Constructors Constructor Description XMLConfiguration()
Creates a new instance ofXMLConfiguration
.XMLConfiguration(HierarchicalConfiguration<ImmutableNode> c)
Creates a new instance ofXMLConfiguration
and copies the content of the passed in configuration into this object.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected javax.xml.parsers.DocumentBuilder
createDocumentBuilder()
Creates theDocumentBuilder
to be used for loading files.protected javax.xml.transform.Transformer
createTransformer()
Creates and initializes the transformer used for save operations.org.w3c.dom.Document
getDocument()
Returns the XML document this configuration was loaded from.javax.xml.parsers.DocumentBuilder
getDocumentBuilder()
Returns theDocumentBuilder
object that is used for loading documents.org.xml.sax.EntityResolver
getEntityResolver()
Returns the EntityResolver.java.lang.String
getPublicID()
Returns the public ID of the DOCTYPE declaration from the loaded XML document.protected java.lang.String
getRootElementNameInternal()
Returns the name of the root element.java.lang.String
getSystemID()
Returns the system ID of the DOCTYPE declaration from the loaded XML document.void
initFileLocator(FileLocator loc)
Passes the currentFileLocator
to this object.boolean
isSchemaValidation()
Returns the value of the schemaValidation flag.boolean
isValidating()
Returns the value of the validating flag.void
read(java.io.InputStream in)
Loads the configuration from the given input stream.void
read(java.io.Reader in)
Loads the configuration from the given reader.void
setDocumentBuilder(javax.xml.parsers.DocumentBuilder documentBuilder)
Sets theDocumentBuilder
object to be used for loading documents.void
setEntityResolver(org.xml.sax.EntityResolver resolver)
Sets a new EntityResolver.void
setPublicID(java.lang.String publicID)
Sets the public ID of the DOCTYPE declaration.void
setRootElementName(java.lang.String name)
Sets the name of the root element.void
setSchemaValidation(boolean schemaValidation)
Sets the value of the schemaValidation flag.void
setSystemID(java.lang.String systemID)
Sets the system ID of the DOCTYPE declaration.void
setValidating(boolean validating)
Sets the value of the validating flag.void
validate()
Validate the document against the Schema.void
write(java.io.Writer writer)
Saves the configuration to the specified writer.-
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, 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, 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, getEncodedString, getEncodedString, 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
-
-
-
-
Constructor Detail
-
XMLConfiguration
public XMLConfiguration()
Creates a new instance ofXMLConfiguration
.
-
XMLConfiguration
public XMLConfiguration(HierarchicalConfiguration<ImmutableNode> c)
Creates a new instance ofXMLConfiguration
and copies the content of the passed in configuration into this object. Note that only the data of the passed in configuration will be copied. If, for instance, the other configuration is aXMLConfiguration
, too, things like comments or processing instructions will be lost.- Parameters:
c
- the configuration to copy- Since:
- 1.4
-
-
Method Detail
-
getRootElementNameInternal
protected java.lang.String getRootElementNameInternal()
Returns the name of the root element. If this configuration was loaded from a XML document, the name of this document's root element is returned. Otherwise it is possible to set a name for the root element that will be used when this configuration is stored.- Overrides:
getRootElementNameInternal
in classAbstractHierarchicalConfiguration<ImmutableNode>
- Returns:
- the name of the root element
-
setRootElementName
public void setRootElementName(java.lang.String name)
Sets the name of the root element. This name is used when this configuration object is stored in an XML file. Note that setting the name of the root element works only if this configuration has been newly created. If the configuration was loaded from an XML file, the name cannot be changed and anUnsupportedOperationException
exception is thrown. Whether this configuration has been loaded from an XML document or not can be found out using thegetDocument()
method.- Parameters:
name
- the name of the root element
-
getDocumentBuilder
public javax.xml.parsers.DocumentBuilder getDocumentBuilder()
Returns theDocumentBuilder
object that is used for loading documents. If no specific builder has been set, this method returns null.- Returns:
- the
DocumentBuilder
for loading new documents - Since:
- 1.2
-
setDocumentBuilder
public void setDocumentBuilder(javax.xml.parsers.DocumentBuilder documentBuilder)
Sets theDocumentBuilder
object to be used for loading documents. This method makes it possible to specify the exact document builder. So an application can create a builder, configure it for its special needs, and then pass it to this method.- Parameters:
documentBuilder
- the document builder to be used; if undefined, a default builder will be used- Since:
- 1.2
-
getPublicID
public java.lang.String getPublicID()
Returns the public ID of the DOCTYPE declaration from the loaded XML document. This is null if no document has been loaded yet or if the document does not contain a DOCTYPE declaration with a public ID.- Returns:
- the public ID
- Since:
- 1.3
-
setPublicID
public void setPublicID(java.lang.String publicID)
Sets the public ID of the DOCTYPE declaration. When this configuration is saved, a DOCTYPE declaration will be constructed that contains this public ID.- Parameters:
publicID
- the public ID- Since:
- 1.3
-
getSystemID
public java.lang.String getSystemID()
Returns the system ID of the DOCTYPE declaration from the loaded XML document. This is null if no document has been loaded yet or if the document does not contain a DOCTYPE declaration with a system ID.- Returns:
- the system ID
- Since:
- 1.3
-
setSystemID
public void setSystemID(java.lang.String systemID)
Sets the system ID of the DOCTYPE declaration. When this configuration is saved, a DOCTYPE declaration will be constructed that contains this system ID.- Parameters:
systemID
- the system ID- Since:
- 1.3
-
isValidating
public boolean isValidating()
Returns the value of the validating flag.- Returns:
- the validating flag
- Since:
- 1.2
-
setValidating
public void setValidating(boolean validating)
Sets the value of the validating flag. This flag determines whether DTD/Schema validation should be performed when loading XML documents. This flag is evaluated only if no customDocumentBuilder
was set.- Parameters:
validating
- the validating flag- Since:
- 1.2
-
isSchemaValidation
public boolean isSchemaValidation()
Returns the value of the schemaValidation flag.- Returns:
- the schemaValidation flag
- Since:
- 1.7
-
setSchemaValidation
public void setSchemaValidation(boolean schemaValidation)
Sets the value of the schemaValidation flag. This flag determines whether DTD or Schema validation should be used. This flag is evaluated only if no customDocumentBuilder
was set. If set to true the XML document must contain a schemaLocation definition that provides resolvable hints to the required schemas.- Parameters:
schemaValidation
- the validating flag- Since:
- 1.7
-
setEntityResolver
public void setEntityResolver(org.xml.sax.EntityResolver resolver)
Sets a new EntityResolver. Setting this will cause RegisterEntityId to have no effect.- Parameters:
resolver
- The EntityResolver to use.- Since:
- 1.7
-
getEntityResolver
public org.xml.sax.EntityResolver getEntityResolver()
Returns the EntityResolver.- Returns:
- The EntityResolver.
- Since:
- 1.7
-
getDocument
public org.w3c.dom.Document getDocument()
Returns the XML document this configuration was loaded from. The return value is null if this configuration was not loaded from a XML document.- Returns:
- the XML document this configuration was loaded from
-
createDocumentBuilder
protected javax.xml.parsers.DocumentBuilder createDocumentBuilder() throws javax.xml.parsers.ParserConfigurationException
Creates theDocumentBuilder
to be used for loading files. This implementation checks whether a specificDocumentBuilder
has been set. If this is the case, this one is used. Otherwise a default builder is created. Depending on the value of the validating flag this builder will be a validating or a non validatingDocumentBuilder
.- Returns:
- the
DocumentBuilder
for loading configuration files - Throws:
javax.xml.parsers.ParserConfigurationException
- if an error occurs- Since:
- 1.2
-
createTransformer
protected javax.xml.transform.Transformer createTransformer() throws ConfigurationException
Creates and initializes the transformer used for save operations. This base implementation initializes all of the default settings like indention mode and the DOCTYPE. Derived classes may overload this method if they have specific needs.- Returns:
- the transformer to use for a save operation
- Throws:
ConfigurationException
- if an error occurs- Since:
- 1.3
-
initFileLocator
public void initFileLocator(FileLocator loc)
Passes the currentFileLocator
to this object. Note that thisFileLocator
object is only temporarily valid for the following invocation ofread()
orwrite(
. Depending on the state of theFileHandler
and which of its methods was called, the object may not be fully initialized. For instance, if theFileHandler
'sload(InputStream)
method was called, no file information is available, and all methods of theFileLocator
will return null. Stores the passed in locator for the upcoming IO operation.- Specified by:
initFileLocator
in interfaceFileLocatorAware
- Parameters:
loc
- the currentFileLocator
-
read
public void read(java.io.Reader in) throws ConfigurationException, java.io.IOException
Loads the configuration from the given reader. Note that theclear()
method is not called, so the properties contained in the loaded file will be added to the current set of properties.- Specified by:
read
in interfaceFileBased
- Parameters:
in
- the reader- Throws:
ConfigurationException
- if an error occursjava.io.IOException
- if an IO error occurs
-
read
public void read(java.io.InputStream in) throws ConfigurationException, java.io.IOException
Loads the configuration from the given input stream. This is analogous toread(Reader)
, but data is read from a stream. Note that this method will be called most time when reading an XML configuration source. By reading XML documents directly from an input stream, the file's encoding can be correctly dealt with.- Specified by:
read
in interfaceInputStreamSupport
- Parameters:
in
- the input stream- Throws:
ConfigurationException
- if an error occursjava.io.IOException
- if an IO error occurs
-
write
public void write(java.io.Writer writer) throws ConfigurationException, java.io.IOException
Saves the configuration to the specified writer.- Specified by:
write
in interfaceFileBased
- Parameters:
writer
- the writer used to save the configuration- Throws:
ConfigurationException
- if an error occursjava.io.IOException
- if an IO error occurs
-
validate
public void validate() throws ConfigurationException
Validate the document against the Schema.- Throws:
ConfigurationException
- if the validation fails.
-
-