Return-Path:
* This is a "read only" interface preventing applications from modifying their
* own configurations. Once it is created, the information never changes.
*
* The data model is a subset of XML's; a single-rooted hierarchical tree where each
* node can contain multiple attributes, and leaf nodes can also
* contain a value. Reflecting this,
* Since version 4.1, each
* As an example, consider two If namespace support is enabled (eg through {@link
* DefaultConfigurationBuilder#DefaultConfigurationBuilder(boolean) new
* DefaultConfigurationBuilder(true)}), then the If namespace support is disabled (the default for {@link
* DefaultConfigurationBuilder}), the above XML will translate directly to
*
* Assuming the Configuration
implementation that deals
* with methods that can be abstracted away from underlying implementations.
*
* @author Federico Barbieri
* @author Stefano Mazzocchi
* @author Peter Donald
* @author Pierpaolo Fumagalli
* @version CVS $Revision: 1.1 $ $Date: 2002/03/31 13:27:56 $
*/
public abstract class AbstractConfiguration
implements Configuration
{
/**
* Returns the prefix of the namespace. This is only used as a serialization
* hint, therefore is not part of the client API. It should be included in
* all Configuration implementations though.
* @return A non-null String (defaults to "")
* @throws ConfigurationException if no prefix was defined (prefix is
* null
.
*/
protected abstract String getPrefix() throws ConfigurationException;
/**
* Returns the value of the configuration element as an int
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @exception ConfigurationException if an error occurs
* @return the value
*/
public int getValueAsInteger()
throws ConfigurationException
{
final String value = getValue();
try
{
if( value.startsWith( "0x" ) )
{
return Integer.parseInt( value.substring( 2 ), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Integer.parseInt( value.substring( 2 ), 8 );
}
else if( value.startsWith( "0b" ) )
{
return Integer.parseInt( value.substring( 2 ), 2 );
}
else
{
return Integer.parseInt( value );
}
}
catch( final Exception nfe )
{
throw new ConfigurationException( "Cannot parse the value \"" + value +
"\" as an integer in the configuration element \"" +
getName() + "\" at " + getLocation() );
}
}
/**
* Returns the value of the configuration element as an int
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public int getValueAsInteger( final int defaultValue )
{
try
{
return getValueAsInteger();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a long
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @exception ConfigurationException if an error occurs
* @return the value
*/
public long getValueAsLong()
throws ConfigurationException
{
final String value = getValue();
try
{
if( value.startsWith( "0x" ) )
{
return Long.parseLong( value.substring( 2 ), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Long.parseLong( value.substring( 2 ), 8 );
}
else if( value.startsWith( "0b" ) )
{
return Long.parseLong( value.substring( 2 ), 2 );
}
else
{
return Integer.parseInt(value);
}
}
catch( final Exception nfe )
{
throw new ConfigurationException( "Cannot parse the value \"" + value +
"\" as a long in the configuration element \"" +
getName() + "\" at " + getLocation() );
}
}
/**
* Returns the value of the configuration element as a long
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public long getValueAsLong( final long defaultValue )
{
try
{
return getValueAsLong();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a float
.
*
* @exception ConfigurationException if an error occurs
* @return the value
*/
public float getValueAsFloat()
throws ConfigurationException
{
final String value = getValue();
try
{
return Float.parseFloat( value );
}
catch( final Exception nfe )
{
throw new ConfigurationException( "Cannot parse the value \"" + value +
"\" as a float in the configuration element \"" +
getName() + "\" at " + getLocation() );
}
}
/**
* Returns the value of the configuration element as a float
.
*
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public float getValueAsFloat( final float defaultValue )
{
try
{
return getValueAsFloat();
}
catch( final ConfigurationException ce )
{
return(defaultValue);
}
}
/**
* Returns the value of the configuration element as a boolean
.
*
* @exception ConfigurationException if an error occurs
* @return the value
*/
public boolean getValueAsBoolean()
throws ConfigurationException
{
final String value = getValue();
if( value.equals( "true" ) )
{
return true;
}
else if( value.equals( "false" ) )
{
return false;
}
else
{
throw new ConfigurationException( "Cannot parse the value \"" + value +
"\" as a boolean in the configuration element \"" +
getName() + "\" at " + getLocation() );
}
}
/**
* Returns the value of the configuration element as a boolean
.
*
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public boolean getValueAsBoolean( final boolean defaultValue )
{
try
{
return getValueAsBoolean();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a String
.
*
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public String getValue( final String defaultValue )
{
try
{
return getValue();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as an
* int
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of the attribute
* @exception ConfigurationException if an error occurs
* @return the value
*/
public int getAttributeAsInteger( final String name )
throws ConfigurationException
{
final String value = getAttribute( name );
try
{
if( value.startsWith( "0x" ) )
{
return Integer.parseInt( value.substring( 2 ), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Integer.parseInt( value.substring( 2 ), 8);
}
else if( value.startsWith( "0b" ) )
{
return Integer.parseInt( value.substring( 2 ), 2 );
}
else
{
return Integer.parseInt(value);
}
}
catch( final Exception nfe )
{
throw new ConfigurationException( "Cannot parse the value \"" + value +
"\" as an integer in the attribute \"" +
name + "\" at " + getLocation() );
}
}
/**
* Returns the value of the attribute specified by its name as an
* int
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of the attribute
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public int getAttributeAsInteger( final String name, final int defaultValue )
{
try
{
return getAttributeAsInteger( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as a
* long
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of the attribute
* @exception ConfigurationException if an error occurs
* @return the value
*/
public long getAttributeAsLong( final String name )
throws ConfigurationException
{
final String value = getAttribute( name );
try
{
if( value.startsWith( "0x" ) )
{
return Long.parseLong( value.substring( 2 ), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Long.parseLong( value.substring( 2 ), 8 );
}
else if( value.startsWith( "0b" ) )
{
return Long.parseLong( value.substring( 2 ), 2);
}
else
{
return Long.parseLong( value );
}
}
catch( final Exception nfe )
{
throw new ConfigurationException( "Cannot parse the value \"" + value +
"\" as a long in the attribute \"" +
name + "\" at " + getLocation() );
}
}
/**
* Returns the value of the attribute specified by its name as a
* long
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of the attribute
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public long getAttributeAsLong( final String name, final long defaultValue )
{
try
{
return getAttributeAsLong( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as a
* float
.
*
* @param name the name of the attribute
* @exception ConfigurationException if an error occurs
* @return the value
*/
public float getAttributeAsFloat( final String name )
throws ConfigurationException
{
final String value = getAttribute( name );
try
{
return Float.parseFloat( value );
}
catch( final Exception e )
{
throw new ConfigurationException( "Cannot parse the value \"" + value +
"\" as a float in the attribute \"" +
name + "\" at " + getLocation() );
}
}
/**
* Returns the value of the attribute specified by its name as a
* float
.
*
* @param name the name of the attribute
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public float getAttributeAsFloat( final String name, final float defaultValue )
{
try
{
return getAttributeAsFloat( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as a
* boolean
.
*
* @param name the name of the attribute
* @exception ConfigurationException if an error occurs
* @return the value
*/
public boolean getAttributeAsBoolean( final String name )
throws ConfigurationException
{
final String value = getAttribute( name );
if( value.equalsIgnoreCase( "true" ) )
{
return true;
}
else if( value.equalsIgnoreCase( "false" ) )
{
return false;
}
else
{
throw new ConfigurationException( "Cannot parse the value \"" + value +
"\" as a boolean in the attribute \"" +
name + "\" at " + getLocation() );
}
}
/**
* Returns the value of the attribute specified by its name as a
* boolean
.
*
* @param name the name of the attribute
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public boolean getAttributeAsBoolean( final String name, final boolean defaultValue )
{
try
{
return getAttributeAsBoolean( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as a
* String
.
*
* @param name the name of the attribute
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public String getAttribute( final String name, final String defaultValue )
{
try
{
return getAttribute( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Return the first Configuration
object child of this
* associated with the given name. If no such child exists, a new one
* will be created.
*
* @param name the name of the child
* @return the child Configuration
*/
public Configuration getChild( final String name )
{
return getChild( name, true );
}
/**
* Return the first Configuration
object child of this
* associated with the given name.
*
* @param name the name of the child
* @param createNew true if you want to create a new Configuration object if none exists
* @return the child Configuration
*/
public Configuration getChild( final String name, final boolean createNew )
{
final Configuration[] children = getChildren( name );
if( children.length > 0 )
{
return children[ 0 ];
}
else
{
if( createNew )
{
return new DefaultConfiguration( name, "-" );
}
else
{
return null;
}
}
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/configuration/Configurable.java
Index: Configurable.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.configuration;
/**
* This interface should be implemented by classes that need to be
* configured with custom parameters before initialization.
*
*
* The contract surrounding a Configurable
is that the
* instantiating entity must call the configure
* method before it is valid. The configure
method
* must be called after the constructor, and before any other method.
*
*
* Note that this interface is incompatible with Parameterizable.
*
* @author Federico Barbieri
* @author Pierpaolo Fumagalli
* @author Stefano Mazzocchi
* @author Berin Loritsch
* @author Peter Donald
* @version 1.0
*/
public interface Configurable
{
/**
* Pass the Configuration
to the Configurable
* class. This method must always be called after the constructor
* and before any other method.
*
* @param configuration the class configurations.
* @exception ConfigurationException if an error occurs
*/
void configure( Configuration configuration )
throws ConfigurationException;
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/configuration/Configuration.java
Index: Configuration.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.configuration;
/**
* Configuration
is a interface encapsulating a configuration node
* used to retrieve configuration values.
*
* Data Model
* Configuration
s are
* usually built from an XML file by the {@link org.apache.framework.configuration.impl.DefaultConfigurationBuilder}
* class, or directly by a SAX parser using a {@link org.apache.framework.configuration.impl.SAXConfigurationHandler} or
* {@link org.apache.framework.configuration.impl.NamespacedSAXConfigurationHandler} event handler.
* Namespace support
* Configuration
node has a namespace
* associated with it, in the form of a string, accessible through {@link
* #getNamespace}. If no namespace is present, getNamespace
will
* return blank (""). See {@link org.apache.framework.configuration.impl.DefaultConfigurationBuilder} for details on how
* XML namespaces are mapped to Configuration
namespaces.
* Example
* Configuration
s (with and without
* namespaces) built from this XML:
*
* <my-system version="1.3" xmlns:doc="http://myco.com/documentation">
* <doc:desc>This is a highly fictitious config file</doc:desc>
* <widget name="fooWidget" initOrder="1" threadsafe="true"/>
* </my-system>
*
* xmlns:doc
element
* will not translate into a Configuration attribute, and the
* doc:desc
element will become a Configuration
node
* with name "desc" and namespace "http://myco.com/documentation". The
* widget
element will have namespace "".
* Configuration
nodes. The my-system
node will have
* an attribute named "xmlns:doc", and a child called "doc:desc".
* Configuration
object is named conf
,
* here is how the data could be retrieved:
*
*
*
* Code No namespaces With namespaces
*
* conf.{@link #getName getName}()
my-system
*
* conf.{@link #getAttributeNames getAttributeNames}().length
* 2 1
*
* conf.{@link #getChildren getChildren}().length
* 2
*
* conf.{@link #getAttributeAsFloat getAttributeAsFloat}("version")
* 1.3
*
* conf.{@link #getChild getChild}("widget").{@link #getAttribute getAttribute}("name")
* fooWidget
*
* conf.{@link #getChild getChild}("widget")
* .{@link #getAttributeAsBoolean getAttributeAsBoolean}("threadsafe")
* true
*
* conf.{@link #getChild getChild}("widget").{@link #getLocation getLocation}()
* file:///home/jeff/tmp/java/avalon/src/java/new.xconf:4:60
*
* conf.{@link #getChild getChild}("desc").{@link #getName getName}()
* desc (see {@link #getChild(String)}) desc
*
* conf.{@link #getChild getChild}("doc:desc").{@link #getName getName}()
* doc:desc doc:desc (see {@link #getChild(String)})
*
* conf.{@link #getChild getChild}("desc").{@link #getValue getValue}()
* {@link ConfigurationException} This is a highly fictitious config file
*
* conf.{@link #getChild getChild}("doc:desc").{@link #getValue getValue}()
* This is a highly fictitious config file {@link ConfigurationException}
*
* conf.{@link #getChild getChild}("desc").{@link #getNamespace getNamespace}()
* http://myco.com/documentation"
* Type-safe utility methods are provided for retrieving attribute and element
* values as String
, int
, long
,
* float
and boolean
.
*
* Currently, the configuration tree can only be traversed one node at a time, * eg., through {@link #getChild getChild("foo")} or {@link #getChildren}. In * a future release, it may be possible to access child nodes with an XPath-like * syntax. *
** Checking for the existence of an attribute can be done as follows: *
**String value = conf.getAttribute( "myAttribute", null ); * if ( null == value ) * { * // Do the processing applicable if the attribute isn't present. * } ** * @author Federico Barbieri * @author Pierpaolo Fumagalli * @author Stefano Mazzocchi * @author Berin Loritsch * @author Peter Donald * @author Jeff Turner * @version 1.0 */ public interface Configuration { /** * Return the name of the node. * * @return name of the
Configuration
node.
* @post getName() != null
*
*/
String getName();
/**
* Return a string describing location of Configuration.
* Location can be different for different mediums (ie "file:line" for normal XML files or
* "table:primary-key" for DB based configurations);
*
* @return a string describing location of Configuration
*/
String getLocation();
/**
* Returns a string indicating which namespace this Configuration node
* belongs to.
*
* * What this returns is dependent on the configuration file and the * Configuration builder. If the Configuration builder does not support * namespaces, this method will return a blank string. *
*In the case of {@link org.apache.framework.configuration.impl.DefaultConfigurationBuilder}, the namespace will * be the URI associated with the XML element. Eg.,:
** <foo xmlns:x="http://blah.com"> * <x:bar/> * </foo> **
The namespace of foo
will be "", and the namespace of
* bar
will be "http://blah.com".
Configuration
instance encapsulating the
* specified child node.
*
* If no such child node exists, an empty Configuration
will be
* returned, allowing constructs such as
* conf.getChild("foo").getChild("bar").getChild("baz").{@link
* #getValue(String) getValue}("default");
*
* If you wish to get a null
return when no element is present,
* use {@link #getChild(String, boolean) getChild("foo", false)}.
*
Configuration
instance encapsulating the specified
* child node.
*
* @param child The name of the child node.
* @param createNew If true
, a new Configuration
* will be created and returned if the specified child does not exist. If
* false
, null
will be returned when the specified
* child doesn't exist.
* @return Configuration
* @pre child != null
* @post getConfiguration() != null
*
*/
Configuration getChild( String child, boolean createNew );
/**
* Return an Array
of Configuration
* elements containing all node children. The array order will reflect the
* order in the source config file.
*
* @return All child nodes
*/
Configuration[] getChildren();
/**
* Return an Array
of Configuration
* elements containing all node children with the specified name. The array
* order will reflect the order in the source config file.
*
* @param name The name of the children to get.
* @return The child nodes with name name
* @pre name != null
* @post getConfigurations() != null
*
*/
Configuration[] getChildren( String name );
/**
* Return an array of all attribute names.
*
* The order of attributes in this array can not be relied on. As
* with XML, a Configuration
's attributes are an
* unordered set. If your code relies on order, eg
* conf.getAttributeNames()[0], then it is liable to break if a
* different XML parser is used.
*
String[]
value
*/
String[] getAttributeNames();
/**
* Return the value of specified attribute.
*
* @param paramName The name of the parameter you ask the value of.
* @return String value of attribute.
* @exception ConfigurationException If no attribute with that name exists.
* @pre paramName != null
* @post getAttribute != null
*
*/
String getAttribute( String paramName ) throws ConfigurationException;
/**
* Return the int
value of the specified attribute contained
* in this node.
*
* @param paramName The name of the parameter you ask the value of.
* @return int value of attribute
* @exception ConfigurationException If no parameter with that name exists.
* or if conversion to int
fails.
* @pre paramName != null
* @post getAttributeAsInteger() != null
*
*/
int getAttributeAsInteger( String paramName ) throws ConfigurationException;
/**
* Returns the value of the attribute specified by its name as a
* long
.
*
* @param name The name of the parameter you ask the value of.
* @return long value of attribute
* @exception ConfigurationException If no parameter with that name exists.
* or if conversion to long
fails.
* @pre paramName != null
* @post getAttributeAsLong() != null
*
*/
long getAttributeAsLong( String name ) throws ConfigurationException;
/**
* Return the float
value of the specified parameter contained
* in this node.
*
* @param paramName The name of the parameter you ask the value of.
* @return float value of attribute
* @exception ConfigurationException If no parameter with that name exists.
* or if conversion to float
fails.
* @pre paramName != null
* @post getAttributeAsFloat() != null
*
*/
float getAttributeAsFloat( String paramName ) throws ConfigurationException;
/**
* Return the boolean
value of the specified parameter contained
* in this node.
*
* @param paramName The name of the parameter you ask the value of.
* @return boolean value of attribute
* @exception ConfigurationException If no parameter with that name exists.
* or if conversion to boolean
fails.
* @pre paramName != null
* @post getAttributeAsBoolean() != null
*
*/
boolean getAttributeAsBoolean( String paramName ) throws ConfigurationException;
/**
* Return the String
value of the node.
*
* @return the value of the node.
* @exception ConfigurationException if an error occurs
* @post getValue() != null
*
*/
String getValue() throws ConfigurationException;
/**
* Return the int
value of the node.
*
* @return the value of the node.
*
* @exception ConfigurationException If conversion to int
fails.
* @post getValueAsInteger() != null
*
*/
int getValueAsInteger() throws ConfigurationException;
/**
* Return the float
value of the node.
*
* @return the value of the node.
* @exception ConfigurationException If conversion to float
fails.
* @post getValueAsFloat() != null
*
*/
float getValueAsFloat() throws ConfigurationException;
/**
* Return the boolean
value of the node.
*
* @return the value of the node.
* @exception ConfigurationException If conversion to boolean
fails.
* @post getValueAsBoolean() != null
*
*/
boolean getValueAsBoolean() throws ConfigurationException;
/**
* Return the long
value of the node.
*
* @return the value of the node.
* @exception ConfigurationException If conversion to long
fails.
* @post getValueAsLong() != null
*
*/
long getValueAsLong() throws ConfigurationException;
/**
* Returns the value of the configuration element as a String
.
* If the configuration value is not set, the default value will be
* used.
*
* @param defaultValue The default value desired.
* @return String value of the Configuration
, or default
* if none specified.
* @pre defaultValue != null
* @post getValue(defaultValue) != null
*
*/
String getValue( String defaultValue );
/**
* Returns the value of the configuration element as an int
.
* If the configuration value is not set, the default value will be
* used.
*
* @param defaultValue The default value desired.
* @return int value of the Configuration
, or default
* if none specified.
* @pre defaultValue != null
* @post getValueAsInteger(defaultValue) != null
*
*/
int getValueAsInteger( int defaultValue );
/**
* Returns the value of the configuration element as a long
.
* If the configuration value is not set, the default value will be
* used.
*
* @param defaultValue The default value desired.
* @return long value of the Configuration
, or default
* if none specified.
* @pre defaultValue != null
* @post getValueAsLong(defaultValue) != null
*
*/
long getValueAsLong( long defaultValue );
/**
* Returns the value of the configuration element as a float
.
* If the configuration value is not set, the default value will be
* used.
*
* @param defaultValue The default value desired.
* @return float value of the Configuration
, or default
* if none specified.
* @pre defaultValue != null
* @post getValueAsFloat(defaultValue) != null
*
*/
float getValueAsFloat( float defaultValue );
/**
* Returns the value of the configuration element as a boolean
.
* If the configuration value is not set, the default value will be
* used.
*
* @param defaultValue The default value desired.
* @return boolean value of the Configuration
, or default
* if none specified.
* @pre defaultValue != null
* @post getValueAsBoolean(defaultValue) != null
*
*/
boolean getValueAsBoolean( boolean defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* String
, or the default value if no attribute by
* that name exists or is empty.
*
* @param name The name of the attribute you ask the value of.
* @param defaultValue The default value desired.
* @return String value of attribute. It will return the default
* value if the named attribute does not exist, or if
* the value is not set.
* @pre name != null
* @pre defaultValue != null
* @pre name != null
* @pre defaultValue != null
* @post getAttribute(name, defaultValue) != null
*
*/
String getAttribute( String name, String defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* int
, or the default value if no attribute by
* that name exists or is empty.
*
* @param name The name of the attribute you ask the value of.
* @param defaultValue The default value desired.
* @return int value of attribute. It will return the default
* value if the named attribute does not exist, or if
* the value is not set.
* @pre name != null
* @pre defaultValue != null
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsInteger(name, defaultValue) != null
*
*/
int getAttributeAsInteger( String name, int defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* long
, or the default value if no attribute by
* that name exists or is empty.
*
* @param name The name of the attribute you ask the value of.
* @param defaultValue The default value desired.
* @return long value of attribute. It will return the default
* value if the named attribute does not exist, or if
* the value is not set.
* @pre name != null
* @pre defaultValue != null
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsLong(name, defaultValue) != null
*
*/
long getAttributeAsLong( String name, long defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* float
, or the default value if no attribute by
* that name exists or is empty.
*
* @param name The name of the attribute you ask the value of.
* @param defaultValue The default value desired.
* @return float value of attribute. It will return the default
* value if the named attribute does not exist, or if
* the value is not set.
* @pre name != null
* @pre defaultValue != null
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsFloat(name, defaultValue) != null
*
*/
float getAttributeAsFloat( String name, float defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* boolean
, or the default value if no attribute by
* that name exists or is empty.
*
* @param name The name of the attribute you ask the value of.
* @param defaultValue The default value desired.
* @return boolean value of attribute. It will return the default
* value if the named attribute does not exist, or if
* the value is not set.
* @pre name != null
* @pre defaultValue != null
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsBoolean(name, defaultValue) != null
*
*/
boolean getAttributeAsBoolean( String name, boolean defaultValue );
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/configuration/ConfigurationException.java
Index: ConfigurationException.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.configuration;
/**
* Thrown when a Configurable
component cannot be configured
* properly, or if a value cannot be retrieved properly.
*
* @author Federico Barbieri
* @author Stefano Mazzocchi
* @author Pierpaolo Fumagalli
*/
public class ConfigurationException
extends Exception
{
/**
* The Throwable that caused this exception to be thrown.
*/
private final Throwable m_throwable;
/**
* Construct a new ConfigurationException
instance.
*
* @param message The detail message for this exception.
*/
public ConfigurationException( final String message )
{
this( message, null );
}
/**
* Construct a new ConfigurationException
instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public ConfigurationException( final String message, final Throwable throwable )
{
super( message );
m_throwable = throwable;
}
/**
* Retrieve root cause of the exception.
*
* @return the root cause
*/
public final Throwable getCause()
{
return m_throwable;
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/configuration/package.html
Index: package.html
===================================================================
Component configuration interfaces and XML-based implementations.
The org.apache.avalon.framework.configuration
package contains primarily:
Configuration
implementation.
*
* @author Federico Barbieri
* @author Stefano Mazzocchi
* @author Pierpaolo Fumagalli
* @author Peter Donald
* @version 1.0
*/
public class DefaultConfiguration
extends AbstractConfiguration
implements Serializable
{
/**
* An empty (length zero) array of configuration objects.
*/
protected static final Configuration[] EMPTY_ARRAY = new Configuration[ 0 ];
private final String m_name;
private final String m_location;
private final String m_namespace;
private final String m_prefix;
private HashMap m_attributes;
private ArrayList m_children;
private String m_value;
private boolean m_readOnly;
/**
* Create a new DefaultConfiguration
instance.
* @param name a String
value
* @param location a String
value
*/
public DefaultConfiguration( final String name, final String location )
{
this( name, location, "", "" );
}
/**
* Create a new DefaultConfiguration
instance.
* @param name config node name
* @param location Builder-specific locator string
* @param ns Namespace string (typically a URI). Should not be null; use ""
* if no namespace.
* @param prefix A short string prefixed to element names, associating
* elements with a longer namespace string. Should not be null; use "" if no
* namespace.
*/
public DefaultConfiguration( final String name,
final String location,
final String ns,
final String prefix )
{
m_name = name;
m_location = location;
m_namespace = ns;
m_prefix = prefix; // only used as a serialization hint. Cannot be null
}
/**
* Returns the name of this configuration element.
* @return a String
value
*/
public String getName()
{
return m_name;
}
/**
* Returns the namespace of this configuration element
* @return a String
value
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
public String getNamespace() throws ConfigurationException
{
if( null != m_namespace )
{
return m_namespace;
}
else
{
throw new ConfigurationException
( "No namespace (not even default \"\") is associated with the "+
"configuration element \"" + getName() +
"\" at " + getLocation() );
}
}
/**
* Returns the prefix of the namespace
* @return a String
value
* @exception org.apache.framework.configuration.ConfigurationException if prefix is not present (null
).
*/
protected String getPrefix() throws ConfigurationException
{
if( null != m_prefix )
{
return m_prefix;
}
else
{
throw new ConfigurationException
( "No prefix (not even default \"\") is associated with the "+
"configuration element \"" + getName() +
"\" at " + getLocation() );
}
}
/**
* Returns a description of location of element.
* @return a String
value
*/
public String getLocation()
{
return m_location;
}
/**
* Returns the value of the configuration element as a String
.
*
* @return a String
value
* @exception org.apache.framework.configuration.ConfigurationException If the value is not present.
*/
public String getValue() throws ConfigurationException
{
if( null != m_value )
{
return m_value;
}
else
{
throw new ConfigurationException( "No value is associated with the "+
"configuration element \"" + getName() +
"\" at " + getLocation() );
}
}
/**
* Return an array of all attribute names.
* @return a String[]
value
*/
public String[] getAttributeNames()
{
if( null == m_attributes )
{
return new String[ 0 ];
}
else
{
return (String[])m_attributes.keySet().toArray( new String[ 0 ] );
}
}
/**
* Return an Iterator
of Configuration
* elements containing all node children.
*
* @return The child nodes with name
*/
public Configuration[] getChildren()
{
if( null == m_children )
{
return new Configuration[ 0 ];
}
else
{
return (Configuration[])m_children.toArray( new Configuration[ 0 ] );
}
}
/**
* Returns the value of the attribute specified by its name as a
* String
.
*
* @param name a String
value
* @return a String
value
* @exception org.apache.framework.configuration.ConfigurationException If the attribute is not present.
*/
public String getAttribute( final String name )
throws ConfigurationException
{
final String value =
(null != m_attributes) ? (String)m_attributes.get( name ) : null;
if( null != value )
{
return value;
}
else
{
throw new ConfigurationException( "No attribute named \"" + name + "\" is " +
"associated with the configuration element \"" +
getName() + "\" at " + getLocation() );
}
}
/**
* Return the first Configuration
object child of this
* associated with the given name.
* @param name a String
value
* @param createNew a boolean
value
* @return a Configuration
value
*/
public Configuration getChild( final String name, final boolean createNew )
{
if( null != m_children )
{
final int size = m_children.size();
for( int i = 0; i < size; i++ )
{
final Configuration configuration = (Configuration)m_children.get( i );
if( name.equals( configuration.getName() ) )
{
return configuration;
}
}
}
if( createNew )
{
return new DefaultConfiguration( name, "-" );
}
else
{
return null;
}
}
/**
* Return an Enumeration
of Configuration
objects
* children of this associated with the given name.
*
* The returned Enumeration
may be empty.
*
* @param name The name of the required children Configuration
.
* @return a Configuration[]
value
*/
public Configuration[] getChildren( final String name )
{
if( null == m_children )
{
return new Configuration[ 0 ];
}
else
{
final ArrayList children = new ArrayList();
final int size = m_children.size();
for( int i = 0; i < size; i++ )
{
final Configuration configuration = (Configuration)m_children.get( i );
if( name.equals( configuration.getName() ) )
{
children.add( configuration );
}
}
return (Configuration[])children.toArray( new Configuration[ 0 ] );
}
}
/**
* Append data to the value of this configuration element.
*
* @param value a String
value
* @deprecated Use setValue() instead
*/
public void appendValueData( final String value )
{
checkWriteable();
if( null == m_value )
{
m_value = value;
}
else
{
m_value += value;
}
}
/**
* Set the value of this Configuration
object to the specified string.
*
* @param value a String
value
*/
public void setValue( final String value )
{
checkWriteable();
m_value = value;
}
/**
* Set the value of the specified attribute to the specified string.
*
* @param name name of the attribute to set
* @param value a String
value
*/
public void setAttribute( final String name, final String value )
{
checkWriteable();
if( null == m_attributes )
{
m_attributes = new HashMap();
}
m_attributes.put( name, value );
}
/**
* Add an attribute to this configuration element, returning its old
* value or null.
*
* @param name a String
value
* @param value a String
value
* @return a String
value
* @deprecated Use setAttribute() instead
*/
public String addAttribute( final String name, String value )
{
checkWriteable();
if( null == m_attributes )
{
m_attributes = new HashMap();
}
return (String) m_attributes.put( name, value );
}
/**
* Add a child Configuration
to this configuration element.
* @param configuration a Configuration
value
*/
public void addChild( final Configuration configuration )
{
checkWriteable();
if( null == m_children )
{
m_children = new ArrayList();
}
m_children.add( configuration );
}
/**
* Remove a child Configuration
to this configuration element.
* @param configuration a Configuration
value
*/
public void removeChild( final Configuration configuration )
{
checkWriteable();
if( null == m_children )
{
return;
}
m_children.remove( configuration );
}
/**
* Return count of children.
* @return an int
value
*/
public int getChildCount()
{
if( null == m_children )
{
return 0;
}
return m_children.size();
}
/**
* Make this configuration read-only.
*
*/
public void makeReadOnly()
{
m_readOnly = true;
}
/**
* heck if this configuration is writeable.
*
* @exception java.lang.IllegalStateException if this configuration s read-only
*/
protected final void checkWriteable()
throws IllegalStateException
{
if( m_readOnly )
{
throw new IllegalStateException
( "Configuration is read only and can not be modified" );
}
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/configuration/impl/DefaultConfigurationBuilder.java
Index: DefaultConfigurationBuilder.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.configuration.impl;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.apache.framework.configuration.Configuration;
import org.apache.framework.configuration.ConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
/**
* A DefaultConfigurationBuilder builds Configuration
s from XML,
* via a SAX2 compliant parser.
*
*
* XML namespace support is optional, and disabled by default to preserve
* backwards-compatibility. To enable it, pass the {@link
* #DefaultConfigurationBuilder(boolean)} constructor the flag true
, or pass
* a namespace-enabled XMLReader
to the {@link
* #DefaultConfigurationBuilder(XMLReader)} constructor.
*
*
* The mapping from XML namespaces to {@link org.apache.framework.configuration.Configuration} namespaces is pretty
* straightforward, with one caveat: attribute namespaces are (deliberately) not
* supported. Enabling namespace processing has the following effects:
*
* - Attributes starting with
xmlns:
are interpreted as
* declaring a prefix:namespaceURI mapping, and won't result in the creation of
* xmlns
-prefixed attributes in the Configuration
.
*
* -
* Prefixed XML elements, like <doc:title xmlns:doc="http://foo.com">,
* will result in a
Configuration
with {@link
* Configuration#getName getName()}.equals("title")
and {@link
* Configuration#getNamespace getNamespace()}.equals("http://foo.com")
.
*
*
*
* @author Federico Barbieri
* @author Peter Donald
* @author Berin Loritsch
* @version 1.0
*/
public class DefaultConfigurationBuilder
{
private SAXConfigurationHandler m_handler;
private XMLReader m_parser;
/**
* Create a Configuration Builder with a default XMLReader that ignores
* namespaces. In order to enable namespaces, use either the constructor
* that has a boolean or that allows you to pass in your own
* namespace-enabled XMLReader.
*/
public DefaultConfigurationBuilder()
{
this( false );
}
/**
* Create a Configuration Builder, specifying a flag that determines
* namespace support.
*
* @param enableNamespaces If true
, a namespace-aware
* SAXParser
is used. If false
, the default JAXP
* SAXParser
(without namespace support) is used.
*/
public DefaultConfigurationBuilder( final boolean enableNamespaces )
{
//yaya the bugs with some compilers and final variables ..
try
{
final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
if ( enableNamespaces )
{
saxParserFactory.setNamespaceAware(true);
}
final SAXParser saxParser = saxParserFactory.newSAXParser();
this.setParser(saxParser.getXMLReader());
}
catch( final Exception se )
{
throw new Error( "Unable to setup SAX parser" + se );
}
}
/**
* Create a Configuration Builder with your own XMLReader.
* @param parser an XMLReader
*/
public DefaultConfigurationBuilder( XMLReader parser )
{
this.setParser(parser);
}
/**
* Internally sets up the XMLReader
*/
private void setParser(XMLReader parser)
{
m_parser = parser;
m_handler = getHandler();
m_parser.setContentHandler( m_handler );
m_parser.setErrorHandler( m_handler );
}
/**
* Get a SAXConfigurationHandler for your configuration reading.
* @return a SAXConfigurationHandler
*/
protected SAXConfigurationHandler getHandler()
{
try
{
if ( m_parser.getFeature( "http://xml.org/sax/features/namespaces" ) )
{
return new NamespacedSAXConfigurationHandler();
}
}
catch ( Exception e )
{
// ignore error and fall through to the non-namespaced version
}
return new SAXConfigurationHandler();
}
/**
* Build a configuration object from a file using a filename.
* @param filename name of the file
* @return a Configuration
object
* @exception SAXException if a parsing error occurs
* @exception java.io.IOException if an I/O error occurs
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
public Configuration buildFromFile( final String filename )
throws SAXException, IOException, ConfigurationException
{
return buildFromFile( new File( filename ) );
}
/**
* Build a configuration object from a file using a File object.
* @param file a File
object
* @return a Configuration
object
* @exception SAXException if a parsing error occurs
* @exception java.io.IOException if an I/O error occurs
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
public Configuration buildFromFile( final File file )
throws SAXException, IOException, ConfigurationException
{
synchronized(this)
{
m_handler.clear();
m_parser.parse( file.toURL().toString() );
return m_handler.getConfiguration();
}
}
/**
* Build a configuration object using an InputStream.
* @param inputStream an InputStream
value
* @return a Configuration
object
* @exception SAXException if a parsing error occurs
* @exception java.io.IOException if an I/O error occurs
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
public Configuration build( final InputStream inputStream )
throws SAXException, IOException, ConfigurationException
{
return build( new InputSource( inputStream ) );
}
/**
* Build a configuration object using an URI
* @param uri a String
value
* @return a Configuration
object
* @exception SAXException if a parsing error occurs
* @exception java.io.IOException if an I/O error occurs
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
public Configuration build( final String uri )
throws SAXException, IOException, ConfigurationException
{
return build( new InputSource( uri ) );
}
/**
* Build a configuration object using an XML InputSource object
* @param input an InputSource
value
* @return a Configuration
object
* @exception SAXException if a parsing error occurs
* @exception java.io.IOException if an I/O error occurs
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
public Configuration build( final InputSource input )
throws SAXException, IOException, ConfigurationException
{
synchronized(this)
{
m_handler.clear();
m_parser.parse( input );
return m_handler.getConfiguration();
}
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/configuration/impl/DefaultConfigurationSerializer.java
Index: DefaultConfigurationSerializer.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.configuration.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Properties;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.NamespaceSupport;
import org.apache.framework.configuration.Configuration;
import org.apache.framework.configuration.ConfigurationException;
import org.apache.framework.configuration.AbstractConfiguration;
/**
* A ConfigurationSerializer serializes configurations via SAX2 compliant parser.
*
* @author Berin Loritsch
* @version 1.0
*/
public class DefaultConfigurationSerializer
{
private SAXTransformerFactory m_tfactory;
private TransformerHandler m_handler;
private OutputStream m_out;
private Properties m_format = new Properties();
private NamespaceSupport m_namespaceSupport = new NamespaceSupport();
/**
* Build a ConfigurationSerializer
*/
public DefaultConfigurationSerializer()
{
getTransformerFactory();
}
/**
* Sets the Serializer's use of indentation. This will cause linefeeds to be added
* after each element, but it does not add any indentation via spaces.
* @param indent a boolean
value
*/
public void setIndent( boolean indent )
{
if ( indent )
{
m_format.put( OutputKeys.INDENT, "yes" );
}
else
{
m_format.put( OutputKeys.INDENT, "no" );
}
}
/**
* Internally set the output strream we will be using.
* @param out an OutputStream
value
*/
protected void setOutputStream( final OutputStream out )
{
try
{
m_out = out;
m_handler = getTransformerFactory().newTransformerHandler();
m_format.put(OutputKeys.METHOD,"xml");
m_handler.setResult(new StreamResult(out));
m_handler.getTransformer().setOutputProperties( m_format );
}
catch( final Exception e )
{
throw new RuntimeException( e.toString() );
}
}
/**
* Get the SAXTransformerFactory so we can get a serializer without being
* tied to one vendor.
* @return a SAXTransformerFactory
value
*/
protected SAXTransformerFactory getTransformerFactory()
{
if(m_tfactory == null)
{
m_tfactory = (SAXTransformerFactory) TransformerFactory.newInstance();
}
return m_tfactory;
}
/**
* Start the serialization process. The output stream must
* be set before calling this method.
* @param source a Configuration
value
* @exception SAXException if an error occurs
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
protected void serialize( final Configuration source )
throws SAXException, ConfigurationException
{
m_namespaceSupport.reset();
m_handler.startDocument();
serializeElement(source);
m_handler.endDocument();
}
/**
* Serialize each Configuration element. This method is called recursively.
* @param element a Configuration
value
* @exception SAXException if an error occurs
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
protected void serializeElement( final Configuration element )
throws SAXException, ConfigurationException
{
m_namespaceSupport.pushContext();
AttributesImpl attr = new AttributesImpl();
String[] attrNames = element.getAttributeNames();
if (null != attrNames)
{
for (int i = 0; i < attrNames.length; i++)
{
attr.addAttribute("", // namespace URI
attrNames[i], // local name
attrNames[i], // qName
"CDATA", // type
element.getAttribute(attrNames[i], "") // value
);
}
}
final String nsURI = element.getNamespace();
String nsPrefix = "";
if ( element instanceof AbstractConfiguration )
{
nsPrefix = ((AbstractConfiguration) element).getPrefix();
}
// nsPrefix is guaranteed to be non-null at this point.
boolean nsWasDeclared = false;
final String existingURI = m_namespaceSupport.getURI( nsPrefix );
// ie, there is no existing URI declared for this prefix or we're
// remapping the prefix to a different URI
if ( existingURI == null || !existingURI.equals( nsURI ) )
{
nsWasDeclared = true;
if (nsPrefix.equals("") && nsURI.equals(""))
{
// implicit mapping; don't need to declare
}
else if (nsPrefix.equals(""))
{
// (re)declare the default namespace
attr.addAttribute("", "xmlns", "xmlns", "CDATA", nsURI);
}
else
{
// (re)declare a mapping from nsPrefix to nsURI
attr.addAttribute("", "xmlns:"+nsPrefix, "xmlns:"+nsPrefix, "CDATA", nsURI);
}
m_handler.startPrefixMapping( nsPrefix, nsURI );
m_namespaceSupport.declarePrefix( nsPrefix, nsURI );
}
String localName = element.getName();
String qName = element.getName();
if ( nsPrefix == null || nsPrefix.length() == 0 )
{
qName = localName;
}
else
{
qName = nsPrefix + ":" + localName;
}
m_handler.startElement(nsURI, localName, qName, attr);
String value = element.getValue(null);
if (null == value)
{
Configuration[] children = element.getChildren();
for (int i = 0; i < children.length; i++)
{
serializeElement(children[i]);
}
}
else
{
m_handler.characters(value.toCharArray(), 0, value.length());
}
m_handler.endElement(nsURI, localName, qName);
if ( nsWasDeclared )
{
m_handler.endPrefixMapping( nsPrefix );
}
m_namespaceSupport.popContext();
}
/**
* Serialize the configuration object to a file using a filename.
* @param filename a String
value
* @param source a Configuration
value
* @exception SAXException if an error occurs
* @exception java.io.IOException if an error occurs
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
public void serializeToFile( final String filename, final Configuration source )
throws SAXException, IOException, ConfigurationException
{
serializeToFile( new File( filename ), source );
}
/**
* Serialize the configuration object to a file using a File object.
* @param file a File
value
* @param source a Configuration
value
* @exception SAXException if an error occurs
* @exception java.io.IOException if an error occurs
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
public void serializeToFile( final File file, final Configuration source )
throws SAXException, IOException, ConfigurationException
{
serialize( new FileOutputStream( file ), source );
}
/**
* Serialize the configuration object to an output stream.
* @param outputStream an OutputStream
value
* @param source a Configuration
value
* @exception SAXException if an error occurs
* @exception java.io.IOException if an error occurs
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
public void serialize( final OutputStream outputStream, final Configuration source )
throws SAXException, IOException, ConfigurationException
{
synchronized(this)
{
setOutputStream( outputStream );
serialize( source );
}
}
/**
* Serialize the configuration object to an output stream derived from an
* URI. The URI must be resolveable by the java.net.URL
object.
* @param uri a String
value
* @param source a Configuration
value
* @exception SAXException if an error occurs
* @exception java.io.IOException if an error occurs
* @exception org.apache.framework.configuration.ConfigurationException if an error occurs
*/
public void serialize( final String uri, final Configuration source )
throws SAXException, IOException, ConfigurationException
{
serialize( new URL( uri ).openConnection().getOutputStream(), source );
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/configuration/impl/NamespacedSAXConfigurationHandler.java
Index: NamespacedSAXConfigurationHandler.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.configuration.impl;
import java.util.ArrayList;
import java.util.Iterator;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.NamespaceSupport;
import org.xml.sax.helpers.AttributesImpl;
import org.apache.framework.configuration.impl.DefaultConfiguration;
import org.apache.framework.configuration.Configuration;
/**
* A SAXConfigurationHandler helps build Configurations out of sax events,
* including namespace information.
*
* @author Federico Barbieri
* @author Peter Donald
* @version 1.0
*/
public class NamespacedSAXConfigurationHandler
extends SAXConfigurationHandler
{
private final ArrayList m_elements = new ArrayList();
private final ArrayList m_prefixes = new ArrayList();
private Configuration m_configuration;
private Locator m_locator;
private NamespaceSupport m_namespaceSupport = new NamespaceSupport();
/**
* Get the configuration object that was built.
*
* @return a Configuration
object
*/
public Configuration getConfiguration()
{
return m_configuration;
}
/**
* Clears all data from this configuration handler.
*/
public void clear()
{
m_elements.clear();
Iterator i = m_prefixes.iterator();
while ( i.hasNext() )
{
( (ArrayList) i.next() ).clear();
}
m_prefixes.clear();
m_locator = null;
}
/**
* Set the document Locator
to use.
*
* @param locator a Locator
value
*/
public void setDocumentLocator( final Locator locator )
{
m_locator = locator;
}
/**
* Handling hook for starting the document parsing.
*
* @exception SAXException if an error occurs
*/
public void startDocument()
throws SAXException
{
m_namespaceSupport.reset();
super.startDocument();
}
/**
* Handling hook for ending the document parsing.
*
* @exception SAXException if an error occurs
*/
public void endDocument()
throws SAXException
{
super.endDocument();
m_namespaceSupport.reset();
}
/**
* Handling hook for character data.
*
* @param ch a char[]
of data
* @param start offset in the character array from which to start reading
* @param end length of character data
* @exception SAXException if an error occurs
*/
public void characters( final char[] ch, int start, int end )
throws SAXException
{
String value = (new String( ch, start, end )).trim();
if( value.equals( "" ) )
{
return;
}
final DefaultConfiguration configuration =
(DefaultConfiguration)m_elements.get( m_elements.size() - 1 );
if( 0 != configuration.getChildCount() )
{
throw new SAXException( "Not allowed to define mixed content in the " +
"element " + configuration.getName() + " at " +
configuration.getLocation() );
}
value = configuration.getValue( "" ) + value;
configuration.setValue( value );
}
/**
* Handling hook for finishing parsing of an element.
*
* @param namespaceURI a String
value
* @param localName a String
value
* @param rawName a String
value
* @exception SAXException if an error occurs
*/
public void endElement( final String namespaceURI,
final String localName,
final String rawName )
throws SAXException
{
final int location = m_elements.size() - 1;
final Object object = m_elements.remove( location );
final ArrayList prefixes = (ArrayList) m_prefixes.remove( location );
final Iterator i = prefixes.iterator();
while ( i.hasNext() )
{
endPrefixMapping( (String) i.next() );
}
prefixes.clear();
if( 0 == location )
{
m_configuration = (Configuration)object;
}
m_namespaceSupport.popContext();
}
/**
* Create a new DefaultConfiguration
with the specified
* local name, namespace, and location.
*
* @param localName a String
value
* @param namespaceURI a String
value
* @param location a String
value
* @return a DefaultConfiguration
value
*/
protected DefaultConfiguration createConfiguration( final String localName,
final String namespaceURI,
final String location )
{
String prefix = m_namespaceSupport.getPrefix( namespaceURI );
if (prefix == null)
{
prefix = "";
}
return new DefaultConfiguration( localName, location, namespaceURI, prefix );
}
/**
* Handling hook for starting parsing of an element.
*
* @param namespaceURI a String
value
* @param localName a String
value
* @param rawName a String
value
* @param attributes an Attributes
value
* @exception SAXException if an error occurs
*/
public void startElement( final String namespaceURI,
final String localName,
final String rawName,
final Attributes attributes )
throws SAXException
{
m_namespaceSupport.pushContext();
final ArrayList prefixes = new ArrayList();
AttributesImpl componentAttr = new AttributesImpl();
for (int i = 0; i < attributes.getLength(); i++)
{
if ( attributes.getQName(i).startsWith("xmlns") )
{
prefixes.add( attributes.getLocalName(i) );
this.startPrefixMapping( attributes.getLocalName(i),
attributes.getValue(i) );
}
else
{
componentAttr.addAttribute( attributes.getURI( i ),
attributes.getLocalName( i ),
attributes.getQName( i ),
attributes.getType( i ),
attributes.getValue( i ) );
}
}
final DefaultConfiguration configuration =
createConfiguration( localName, namespaceURI, getLocationString() );
final int size = m_elements.size() - 1;
if( size > -1 )
{
final DefaultConfiguration parent =
(DefaultConfiguration)m_elements.get( size );
if( null != parent.getValue( null ) )
{
throw new SAXException( "Not allowed to define mixed content in the " +
"element " + parent.getName() + " at " +
parent.getLocation() );
}
parent.addChild( configuration );
}
m_elements.add( configuration );
m_prefixes.add( prefixes );
final int attributesSize = componentAttr.getLength();
for( int i = 0; i < attributesSize; i++ )
{
final String name = componentAttr.getQName( i );
final String value = componentAttr.getValue( i );
configuration.setAttribute( name, value );
}
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @exception SAXException if an error occurs
*/
public void error( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @exception SAXException if an error occurs
*/
public void warning( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @exception SAXException if an error occurs
*/
public void fatalError( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* Returns a string showing the current system ID, line number and column number.
*
* @return a String
value
*/
protected String getLocationString()
{
if( null == m_locator )
{
return "Unknown";
}
else
{
return
m_locator.getSystemId() + ":" +
m_locator.getLineNumber() + ":" +
m_locator.getColumnNumber();
}
}
/**
* Handling hook for starting prefix mapping.
*
* @param prefix a String
value
* @param uri a String
value
* @exception SAXException if an error occurs
*/
public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
m_namespaceSupport.declarePrefix( prefix, uri );
super.startPrefixMapping( prefix, uri );
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/configuration/impl/SAXConfigurationHandler.java
Index: SAXConfigurationHandler.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.configuration.impl;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.framework.configuration.impl.DefaultConfiguration;
import org.apache.framework.configuration.Configuration;
/**
* A SAXConfigurationHandler helps build Configurations out of sax events.
*
* @author Federico Barbieri
* @author Peter Donald
*/
public class SAXConfigurationHandler
extends DefaultHandler
implements ErrorHandler
{
private final ArrayList m_elements = new ArrayList();
private Configuration m_configuration;
private Locator m_locator;
/**
* Get the configuration object that was built.
*
* @return a Configuration
object
*/
public Configuration getConfiguration()
{
return m_configuration;
}
/**
* Clears all data from this configuration handler.
*/
public void clear()
{
m_elements.clear();
m_locator = null;
}
/**
* Set the document Locator
to use.
*
* @param locator a Locator
value
*/
public void setDocumentLocator( final Locator locator )
{
m_locator = locator;
}
/**
* Handling hook for character data.
*
* @param ch a char[]
of data
* @param start offset in the character array from which to start reading
* @param end length of character data
* @exception SAXException if an error occurs
*/
public void characters( final char[] ch, int start, int end )
throws SAXException
{
String value = (new String( ch, start, end )).trim();
if( value.equals( "" ) )
{
return;
}
final DefaultConfiguration configuration =
(DefaultConfiguration)m_elements.get( m_elements.size() - 1 );
if( 0 != configuration.getChildCount() )
{
throw new SAXException( "Not allowed to define mixed content in the " +
"element " + configuration.getName() + " at " +
configuration.getLocation() );
}
value = configuration.getValue( "" ) + value;
configuration.setValue( value );
}
/**
* Handling hook for finishing parsing of an element.
*
* @param namespaceURI a String
value
* @param localName a String
value
* @param rawName a String
value
* @exception SAXException if an error occurs
*/
public void endElement( final String namespaceURI,
final String localName,
final String rawName )
throws SAXException
{
final int location = m_elements.size() - 1;
final Object object = m_elements.remove( location );
if( 0 == location )
{
m_configuration = (Configuration)object;
}
}
/**
* Create a new DefaultConfiguration
with the specified
* local name and location.
*
* @param localName a String
value
* @param location a String
value
* @return a DefaultConfiguration
value
*/
protected DefaultConfiguration createConfiguration( final String localName,
final String location )
{
return new DefaultConfiguration( localName, location );
}
/**
* Handling hook for starting parsing of an element.
*
* @param namespaceURI a String
value
* @param localName a String
value
* @param rawName a String
value
* @param attributes an Attributes
value
* @exception SAXException if an error occurs
*/
public void startElement( final String namespaceURI,
final String localName,
final String rawName,
final Attributes attributes )
throws SAXException
{
final DefaultConfiguration configuration =
createConfiguration( rawName, getLocationString() );
final int size = m_elements.size() - 1;
if( size > -1 )
{
final DefaultConfiguration parent =
(DefaultConfiguration)m_elements.get( size );
if( null != parent.getValue( null ) )
{
throw new SAXException( "Not allowed to define mixed content in the " +
"element " + parent.getName() + " at " +
parent.getLocation() );
}
parent.addChild( configuration );
}
m_elements.add( configuration );
final int attributesSize = attributes.getLength();
for( int i = 0; i < attributesSize; i++ )
{
final String name = attributes.getQName( i );
final String value = attributes.getValue( i );
configuration.setAttribute( name, value );
}
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @exception SAXException if an error occurs
*/
public void error( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @exception SAXException if an error occurs
*/
public void warning( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @exception SAXException if an error occurs
*/
public void fatalError( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* Returns a string showing the current system ID, line number and column number.
*
* @return a String
value
*/
protected String getLocationString()
{
if( null == m_locator )
{
return "Unknown";
}
else
{
return
m_locator.getSystemId() + ":" +
m_locator.getLineNumber() + ":" +
m_locator.getColumnNumber();
}
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/context/Context.java
Index: Context.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.context;
/**
* The context is the interface through which the Component
* and it's Container communicate.
*
* Each Container-Component relationship will also involve defining
* a contract between two entities. This contract will specify the
* services, settings and information that is supplied by the
* Container to the Component.
*
* This relationship should be documented in a well known place.
* It is sometimes convenient to derive from Context to provide
* a particular style of Context for your Component-Container
* relationship. The documentation for required entries in context
* can then be defined there. (examples include MailetContext,
* BlockContext etc.)
*
* There are traditionally four differet types of Context that may be
* used in a system. These ideas are partially derived from linguistic theory
* and partially from tradition computer science;
*
*
* - World Context / Per-Application context: This describes application
* wide settings/context. An example may be the working directory of the
* application.
*
* - Person Context / Per-Component context: This contains context
* information specific to the component. An example may be the name of
* the component.
*
* - Conversation Context / Per-Session context: This contains context
* information specific to the component. An example may be the IP address
* of the entity who you are talking to.
*
* - Speach Act Context / Per-Request context: This contains information
* about a specific request in component. Example may include the parameter
* submitted to a particular web form or whatever.
*
*
*
* When we implement this (1) and (2) are generally merged into one interface.
* For instance in the Pheonix Application Server there is a BlockContext. Part
* of the BlockContext consists of two methods. One is getHomeDirectory() and that
* belongs to (1) while the other is getName() which belongs to (2).
*
* (4) is usually passed into a service() style method as parameters. Often it will
* named something like RequestObject. So you may have something like:
*
*
* void doMagic( int param1, int param2, Context otherParamsInHere );
*
*
* When (3) is needed in the system it is usually also passed into the a serice method
* method, along with the request context (4). Alternatively it is made available via the
* context representing (4).
*
* @author Federico Barbieri
* @author Pierpaolo Fumagalli
* @author Stefano Mazzocchi
* @author Peter Donald
*/
public interface Context
{
/**
* Retrieve an object from Context.
*
* @param key the key into context
* @return the object
* @exception ContextException if object not found. Note that this
* means that either Component is asking for invalid entry
* or the Container is not living up to contract.
*/
Object get( Object key )
throws ContextException;
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/context/ContextException.java
Index: ContextException.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.context;
/**
* Exception signalling a badly formed Context.
*
* This can be thrown by Context object when a entry is not
* found. It can also be thrown manually in contextualize()
* when Component detects a malformed context value.
*
* @author Leo Simons
* @author Peter Donald
*/
public class ContextException
extends Exception
{
/**
* The Throwable that caused this exception to be thrown.
*/
private final Throwable m_throwable;
/**
* Construct a new ContextException
instance.
*
* @param message The detail message for this exception.
*/
public ContextException( final String message )
{
this( message, null );
}
/**
* Construct a new ContextException
instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public ContextException( final String message, final Throwable throwable )
{
super( message );
m_throwable = throwable;
}
/**
* Retrieve root cause of the exception.
*
* @return the root cause
*/
public final Throwable getCause()
{
return m_throwable;
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/context/Contextualizable.java
Index: Contextualizable.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.context;
/**
* This inteface should be implemented by components that need
* a Context to work. Context contains runtime generated object
* provided by the Container to this Component.
*
* @author Federico Barbieri
* @author Pierpaolo Fumagalli
* @author Stefano Mazzocchi
*/
public interface Contextualizable
{
/**
* Pass the Context to the component.
* This method is called after the Loggable.setLogger() (if present)
* method and before any other method.
*
* @param context the context
* @exception ContextException if context is invalid
*/
void contextualize( Context context )
throws ContextException;
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/context/package.html
Index: package.html
===================================================================
Interfaces and implementation of the Context model through which runtime context can be applied by a manager to a component.
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/context/impl/DefaultContext.java
Index: DefaultContext.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.context.impl;
import java.util.Hashtable;
import java.util.Map;
import org.apache.framework.context.Context;
import org.apache.framework.context.ContextException;
/**
* Default implementation of Context.
* This implementation is a static hierarchial store.
*
* @author Federico Barbieri
* @author Pierpaolo Fumagalli
* @author Stefano Mazzocchi
* @author Peter Donald
*/
public class DefaultContext
implements Context
{
private final Map m_contextData;
private final Context m_parent;
private boolean m_readOnly;
/**
* Create a Context with specified data and parent.
*
* @param contextData the context data
* @param parent the parent Context (may be null)
*/
public DefaultContext( final Map contextData, final Context parent )
{
m_parent = parent;
m_contextData = contextData;
}
/**
* Create a Context with specified data.
*
* @param contextData the context data
*/
public DefaultContext( final Map contextData )
{
this( contextData, null );
}
/**
* Create a Context with specified parent.
*
* @param parent the parent Context (may be null)
*/
public DefaultContext( final Context parent )
{
this( new Hashtable(), parent );
}
/**
* Create a Context with no parent.
*
*/
public DefaultContext()
{
this( (Context)null );
}
/**
* Retrieve an item from the Context.
*
* @param key the key of item
* @return the item stored in context
* @exception org.apache.framework.context.ContextException if item not present
*/
public Object get( final Object key )
throws ContextException
{
final Object data = m_contextData.get( key );
if( null != data )
{
return data;
}
// If data was null, check the parent
if( null == m_parent )
{
// There was no parent, and no data
throw new ContextException( "Unable to locate " + key );
}
return m_parent.get( key );
}
/**
* Helper method fo adding items to Context.
*
* @param key the items key
* @param value the item
* @exception java.lang.IllegalStateException if context is read only
*/
public void put( final Object key, final Object value )
throws IllegalStateException
{
checkWriteable();
m_contextData.put( key, value );
}
/**
* Utility method to retrieve context data.
*
* @return the context data
*/
protected final Map getContextData()
{
return m_contextData;
}
/**
* Get parent context if any.
*
* @return the parent Context (may be null)
*/
protected final Context getParent()
{
return m_parent;
}
/**
* Make the context read-only.
* Any attempt to write to the context via put()
* will result in an IllegalStateException.
*/
public void makeReadOnly()
{
m_readOnly = true;
}
/**
* Utility method to check if context is writeable and if not throw exception.
*
* @exception java.lang.IllegalStateException if context is read only
*/
protected final void checkWriteable()
throws IllegalStateException
{
if( m_readOnly )
{
throw new IllegalStateException( "Context is read only and can not be modified" );
}
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/logger/AbstractLogEnabled.java
Index: AbstractLogEnabled.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.logger;
/**
* Utility class to allow construction of easy components that will perform logging.
*
* @author Peter Donald
*/
public abstract class AbstractLogEnabled
implements LogEnabled
{
///Base Logger instance
private Logger m_logger;
/**
* Set the components logger.
*
* @param logger the logger
*/
public void enableLogging( final Logger logger )
{
m_logger = logger;
}
/**
* Helper method to allow sub-classes to aquire logger.
* This method exists rather than exposing a member variable
* because it protects other users against future changes. It
* also means they do not have to use our naming convention.
*
* There is no performance penalty as this is a final method
* and will be inlined by the JVM.
*
* @return the Logger
*/
protected final Logger getLogger()
{
return m_logger;
}
/**
* Helper method to setup other components with same logger.
*
* @param component the component to pass logger object to
*/
protected void setupLogger( final Object component )
{
setupLogger( component, (String)null );
}
/**
* Helper method to setup other components with logger.
* The logger has the subcategory of this components logger.
*
* @param component the component to pass logger object to
* @param subCategory the subcategory to use (may be null)
*/
protected void setupLogger( final Object component, final String subCategory )
{
Logger logger = m_logger;
if( null != subCategory )
{
logger = m_logger.getChildLogger( subCategory );
}
setupLogger( component, logger );
}
/**
* Helper method to setup other components with logger.
*
* @param component the component to pass logger object to
* @param logger the Logger
*/
protected void setupLogger( final Object component, final Logger logger )
{
if( component instanceof LogEnabled )
{
((LogEnabled)component).enableLogging( logger );
}
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/logger/LogEnabled.java
Index: LogEnabled.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.logger;
/**
* Components that need to log can implement this interface to
* be provided Loggers.
*
* @author Peter Donald
* @author Berin Loritsch
*/
public interface LogEnabled
{
/**
* Provide component with a logger.
*
* @param logger the logger
*/
void enableLogging( Logger logger );
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/logger/Logger.java
Index: Logger.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.logger;
/**
* This is a facade for the different logging subsystems.
* It offers a simplified interface that follows IOC patterns
* and a simplified priority/level/severity abstraction.
*
* @author Peter Donald
*/
public interface Logger
{
/**
* Log a debug message.
*
* @param message the message
*/
void debug( String message );
/**
* Log a debug message.
*
* @param message the message
* @param throwable the throwable
*/
void debug( String message, Throwable throwable );
/**
* Determine if messages of priority "debug" will be logged.
*
* @return true if "debug" messages will be logged
*/
boolean isDebugEnabled();
/**
* Log a info message.
*
* @param message the message
*/
void info( String message );
/**
* Log a info message.
*
* @param message the message
* @param throwable the throwable
*/
void info( String message, Throwable throwable );
/**
* Determine if messages of priority "info" will be logged.
*
* @return true if "info" messages will be logged
*/
boolean isInfoEnabled();
/**
* Log a warn message.
*
* @param message the message
*/
void warn( String message );
/**
* Log a warn message.
*
* @param message the message
* @param throwable the throwable
*/
void warn( String message, Throwable throwable );
/**
* Determine if messages of priority "warn" will be logged.
*
* @return true if "warn" messages will be logged
*/
boolean isWarnEnabled();
/**
* Log a error message.
*
* @param message the message
*/
void error( String message );
/**
* Log a error message.
*
* @param message the message
* @param throwable the throwable
*/
void error( String message, Throwable throwable );
/**
* Determine if messages of priority "error" will be logged.
*
* @return true if "error" messages will be logged
*/
boolean isErrorEnabled();
/**
* Log a fatalError message.
*
* @param message the message
*/
void fatalError( String message );
/**
* Log a fatalError message.
*
* @param message the message
* @param throwable the throwable
*/
void fatalError( String message, Throwable throwable );
/**
* Determine if messages of priority "fatalError" will be logged.
*
* @return true if "fatalError" messages will be logged
*/
boolean isFatalErrorEnabled();
/**
* Create a new child logger.
* The name of the child logger is [current-loggers-name].[passed-in-name]
* Throws IllegalArgumentException
if name has an empty element name
*
* @param name the subname of this logger
* @return the new logger
*/
Logger getChildLogger( String name );
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/logger/package.html
Index: package.html
===================================================================
Abstract logging framework supporting pluggable logging mechanisms including LogKit, Log4J and the JDK 1.4 logging infrastructure.
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/logger/impl/ConsoleLogger.java
Index: ConsoleLogger.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.logger.impl;
import org.apache.framework.logger.Logger;
/**
* Logger sending everything to the standard output streams.
* This is mainly for the cases when you have a utility that
* does not have a logger to supply.
*
* @author Leo Sutic
* @author Berin Loritsch
* @version 1.0
*/
public final class ConsoleLogger
implements Logger
{
/** Typecode for debugging messages. */
public static final int LEVEL_DEBUG = 0;
/** Typecode for informational messages. */
public static final int LEVEL_INFO = 1;
/** Typecode for warning messages. */
public static final int LEVEL_WARN = 2;
/** Typecode for error messages. */
public static final int LEVEL_ERROR = 3;
/** Typecode for fatal error messages. */
public static final int LEVEL_FATAL = 4;
/** Typecode for disabled log levels. */
public static final int LEVEL_DISABLED = 5;
private final int m_logLevel;
/**
* Creates a new ConsoleLogger with the priority set to DEBUG.
*/
public ConsoleLogger()
{
this( LEVEL_DEBUG );
}
/**
* Creates a new ConsoleLogger.
* @param logLevel log level typecode
*/
public ConsoleLogger( final int logLevel )
{
m_logLevel = logLevel;
}
/**
* Logs a debugging message.
*
* @param message a String
value
*/
public void debug( final String message )
{
debug( message, null );
}
/**
* Logs a debugging message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void debug( final String message, final Throwable throwable )
{
if ( m_logLevel <= LEVEL_DEBUG )
{
System.out.print( "[DEBUG] " );
System.out.println( message );
if ( null != throwable )
{
throwable.printStackTrace( System.out );
}
}
}
/**
* Returns true
if debug-level logging is enabled, false otherwise.
*
* @return true
if debug-level logging
*/
public boolean isDebugEnabled()
{
return m_logLevel <= LEVEL_DEBUG;
}
/**
* Logs an informational message.
*
* @param message a String
value
*/
public void info( final String message )
{
info( message, null );
}
/**
* Logs an informational message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void info( final String message, final Throwable throwable )
{
if ( m_logLevel <= LEVEL_INFO )
{
System.out.print( "[INFO] " );
System.out.println( message );
if ( null != throwable )
{
throwable.printStackTrace( System.out );
}
}
}
/**
* Returns true
if info-level logging is enabled, false otherwise.
*
* @return true
if info-level logging is enabled
*/
public boolean isInfoEnabled()
{
return m_logLevel <= LEVEL_INFO;
}
/**
* Logs a warning message.
*
* @param message a String
value
*/
public void warn( final String message )
{
warn( message, null );
}
/**
* Logs a warning message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void warn(final String message, final Throwable throwable)
{
if ( m_logLevel <= LEVEL_WARN )
{
System.out.print( "[WARNING] " );
System.out.println( message );
if ( null != throwable )
{
throwable.printStackTrace( System.out );
}
}
}
/**
* Returns true
if warn-level logging is enabled, false otherwise.
*
* @return true
if warn-level logging is enabled
*/
public boolean isWarnEnabled()
{
return m_logLevel <= LEVEL_WARN;
}
/**
* Logs an error message.
*
* @param message a String
value
*/
public void error( final String message )
{
error( message, null );
}
/**
* Logs an error message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void error( final String message, final Throwable throwable )
{
if ( m_logLevel <= LEVEL_ERROR )
{
System.out.print( "[ERROR] " );
System.out.println( message );
if ( null != throwable )
{
throwable.printStackTrace( System.out );
}
}
}
/**
* Returns true
if error-level logging is enabled, false otherwise.
*
* @return true
if error-level logging is enabled
*/
public boolean isErrorEnabled()
{
return m_logLevel <= LEVEL_ERROR;
}
/**
* Logs a fatal error message.
*
* @param message a String
value
*/
public void fatalError( final String message )
{
fatalError( message, null );
}
/**
* Logs a fatal error message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void fatalError( final String message, final Throwable throwable )
{
if ( m_logLevel <= LEVEL_FATAL )
{
System.out.print( "[FATAL ERROR] " );
System.out.println( message );
if ( null != throwable )
{
throwable.printStackTrace( System.out );
}
}
}
/**
* Returns true
if fatal-level logging is enabled, false otherwise.
*
* @return true
if fatal-level logging is enabled
*/
public boolean isFatalErrorEnabled()
{
return m_logLevel <= LEVEL_FATAL;
}
/**
* Just returns this logger (ConsoleLogger
is not hierarchical).
*
* @param name ignored
* @return this logger
*/
public Logger getChildLogger( final String name )
{
return this;
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/logger/impl/Jdk14Logger.java
Index: Jdk14Logger.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.logger.impl;
import java.util.logging.Level;
import org.apache.framework.logger.Logger;
/**
* The default JDK 1.4 wrapper class for Logger. Please note that there is
* not an exact match to the priority levels that JDK 1.4 logging has and
* what LogKit or Log4J has. For that reason, the following priority level
* matching was used:
*
*
* - SEVERE = error, fatalError
* - WARNING = warn
* - INFO = info
* - FINE = debug
*
*
*
* JDK 1.4 does allow you to have other levels like: CONFIG, FINER, and
* FINEST. Most projects don't separate out configuration logging from
* debugging information. Also, we wanted to maintain backwards
* compatibility as much as possible. Unfortunately, with all the "fineness"
* details, there is no equivalent to the "error" log level.
*
*
* @author Berin Loritsch
* @author Peter Donald
*/
public final class Jdk14Logger
implements Logger
{
//The actual JDK1.4 logger implementation
private final java.util.logging.Logger m_logger;
/**
* Construct a Logger with specified jdk1.4 logger instance as implementation.
*
* @param logImpl the jdk1.4 logger instance to delegate to
*/
public Jdk14Logger( java.util.logging.Logger logImpl )
{
m_logger = logImpl;
}
/**
* Log a debug message.
*
* @param message the message
*/
public final void debug( final String message )
{
m_logger.log( Level.FINE, message );
}
/**
* Log a debug message.
*
* @param message the message
* @param throwable the throwable
*/
public final void debug( final String message, final Throwable throwable )
{
m_logger.log( Level.FINE, message, throwable );
}
/**
* Determine if messages of priority "debug" will be logged.
*
* @return true if "debug" messages will be logged
*/
public final boolean isDebugEnabled()
{
return m_logger.isLoggable( Level.FINE );
}
/**
* Log a info message.
*
* @param message the message
*/
public final void info( final String message )
{
m_logger.log( Level.INFO, message );
}
/**
* Log a info message.
*
* @param message the message
* @param throwable the throwable
*/
public final void info( final String message, final Throwable throwable )
{
m_logger.log( Level.INFO, message, throwable );
}
/**
* Determine if messages of priority "info" will be logged.
*
* @return true if "info" messages will be logged
*/
public final boolean isInfoEnabled()
{
return m_logger.isLoggable( Level.INFO );
}
/**
* Log a warn message.
*
* @param message the message
*/
public final void warn( final String message )
{
m_logger.log( Level.WARNING, message );
}
/**
* Log a warn message.
*
* @param message the message
* @param throwable the throwable
*/
public final void warn( final String message, final Throwable throwable )
{
m_logger.log( Level.WARNING, message, throwable );
}
/**
* Determine if messages of priority "warn" will be logged.
*
* @return true if "warn" messages will be logged
*/
public final boolean isWarnEnabled()
{
return m_logger.isLoggable( Level.WARNING );
}
/**
* Log a error message.
*
* @param message the message
*/
public final void error( final String message )
{
m_logger.log( Level.SEVERE, message );
}
/**
* Log a error message.
*
* @param message the message
* @param throwable the throwable
*/
public final void error( final String message, final Throwable throwable )
{
m_logger.log( Level.SEVERE, message, throwable );
}
/**
* Determine if messages of priority "error" will be logged.
*
* @return true if "error" messages will be logged
*/
public final boolean isErrorEnabled()
{
return m_logger.isLoggable( Level.SEVERE );
}
/**
* Log a fatalError message.
*
* @param message the message
*/
public final void fatalError( final String message )
{
m_logger.log( Level.SEVERE, message );
}
/**
* Log a fatalError message.
*
* @param message the message
* @param throwable the throwable
*/
public final void fatalError( final String message, final Throwable throwable )
{
m_logger.log( Level.SEVERE, message, throwable );
}
/**
* Determine if messages of priority "fatalError" will be logged.
*
* @return true if "fatalError" messages will be logged
*/
public final boolean isFatalErrorEnabled()
{
return m_logger.isLoggable( Level.SEVERE );
}
/**
* Create a new child logger.
* The name of the child logger is [current-loggers-name].[passed-in-name]
* Throws IllegalArgumentException
if name has an empty element name
*
* @param name the subname of this logger
* @return the new logger
*/
public final Logger getChildLogger( final String name )
{
return new Jdk14Logger( java.util.logging.Logger
.getLogger( m_logger.getName() + "." + name ) );
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/logger/impl/Log4JLogger.java
Index: Log4JLogger.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.logger.impl;
import org.apache.log4j.Category;
import org.apache.log4j.Priority;
import org.apache.framework.logger.Logger;
/**
* The default Log4J wrapper class for Logger.
*
* @author Berin Loritsch
* @author Peter Donald
*/
public final class Log4JLogger
implements Logger
{
//underlying implementation
private final Category m_logger;
/**
* Create a logger that delegates to specified category.
*
* @param logImpl the category to delegate to
*/
public Log4JLogger( final Category logImpl )
{
m_logger = logImpl;
}
/**
* Log a debug message.
*
* @param message the message
*/
public final void debug( final String message )
{
m_logger.debug(message);
}
/**
* Log a debug message.
*
* @param message the message
* @param throwable the throwable
*/
public final void debug( final String message, final Throwable throwable )
{
m_logger.debug( message, throwable );
}
/**
* Determine if messages of priority "debug" will be logged.
*
* @return true if "debug" messages will be logged
*/
public final boolean isDebugEnabled()
{
return m_logger.isDebugEnabled();
}
/**
* Log a info message.
*
* @param message the message
*/
public final void info( final String message )
{
m_logger.info( message );
}
/**
* Log a info message.
*
* @param message the message
* @param throwable the throwable
*/
public final void info( final String message, final Throwable throwable )
{
m_logger.info( message, throwable );
}
/**
* Determine if messages of priority "info" will be logged.
*
* @return true if "info" messages will be logged
*/
public final boolean isInfoEnabled()
{
return m_logger.isInfoEnabled();
}
/**
* Log a warn message.
*
* @param message the message
*/
public final void warn( final String message )
{
m_logger.warn( message );
}
/**
* Log a warn message.
*
* @param message the message
* @param throwable the throwable
*/
public final void warn( final String message, final Throwable throwable )
{
m_logger.warn( message, throwable );
}
/**
* Determine if messages of priority "warn" will be logged.
*
* @return true if "warn" messages will be logged
*/
public final boolean isWarnEnabled()
{
return m_logger.isEnabledFor( Priority.WARN );
}
/**
* Log a error message.
*
* @param message the message
*/
public final void error( final String message )
{
m_logger.error( message );
}
/**
* Log a error message.
*
* @param message the message
* @param throwable the throwable
*/
public final void error( final String message, final Throwable throwable )
{
m_logger.error( message, throwable );
}
/**
* Determine if messages of priority "error" will be logged.
*
* @return true if "error" messages will be logged
*/
public final boolean isErrorEnabled()
{
return m_logger.isEnabledFor( Priority.ERROR );
}
/**
* Log a fatalError message.
*
* @param message the message
*/
public final void fatalError( final String message )
{
m_logger.fatal( message );
}
/**
* Log a fatalError message.
*
* @param message the message
* @param throwable the throwable
*/
public final void fatalError( final String message, final Throwable throwable )
{
m_logger.fatal( message, throwable );
}
/**
* Determine if messages of priority "fatalError" will be logged.
*
* @return true if "fatalError" messages will be logged
*/
public final boolean isFatalErrorEnabled()
{
return m_logger.isEnabledFor( Priority.FATAL );
}
/**
* Create a new child logger.
* The name of the child logger is [current-loggers-name].[passed-in-name]
* Throws IllegalArgumentException
if name has an empty element name
*
* @param name the subname of this logger
* @return the new logger
*/
public final Logger getChildLogger( final String name )
{
return new Log4JLogger( Category.getInstance( m_logger.getName() + "." + name ) );
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/logger/impl/LogKitLogger.java
Index: LogKitLogger.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.logger.impl;
import org.apache.framework.logger.Logger;
/**
* The default LogKit wrapper class for Logger.
*
* @author Berin Loritsch
* @author Peter Donald
*/
public final class LogKitLogger
implements Logger
{
//underlying implementation to delegate to
private final org.apache.log.Logger m_logger;
/**
* Create a logger that delegates to specified logger.
*
* @param logImpl the LogKit logger to delegate to
*/
public LogKitLogger( org.apache.log.Logger logImpl )
{
m_logger = logImpl;
}
/**
* Log a debug message.
*
* @param message the message
*/
public final void debug( final String message )
{
m_logger.debug(message);
}
/**
* Log a debug message.
*
* @param message the message
* @param throwable the throwable
*/
public final void debug( final String message, final Throwable throwable )
{
m_logger.debug( message, throwable );
}
/**
* Determine if messages of priority "debug" will be logged.
*
* @return true if "debug" messages will be logged
*/
public final boolean isDebugEnabled()
{
return m_logger.isDebugEnabled();
}
/**
* Log a info message.
*
* @param message the message
*/
public final void info( final String message )
{
m_logger.info( message );
}
/**
* Log a info message.
*
* @param message the message
* @param throwable the throwable
*/
public final void info( final String message, final Throwable throwable )
{
m_logger.info( message, throwable );
}
/**
* Determine if messages of priority "info" will be logged.
*
* @return true if "info" messages will be logged
*/
public final boolean isInfoEnabled()
{
return m_logger.isInfoEnabled();
}
/**
* Log a warn message.
*
* @param message the message
*/
public final void warn( final String message )
{
m_logger.warn( message );
}
/**
* Log a warn message.
*
* @param message the message
* @param throwable the throwable
*/
public final void warn( final String message, final Throwable throwable )
{
m_logger.warn( message, throwable );
}
/**
* Determine if messages of priority "warn" will be logged.
*
* @return true if "warn" messages will be logged
*/
public final boolean isWarnEnabled()
{
return m_logger.isWarnEnabled();
}
/**
* Log a error message.
*
* @param message the message
*/
public final void error( final String message )
{
m_logger.error( message );
}
/**
* Log a error message.
*
* @param message the message
* @param throwable the throwable
*/
public final void error( final String message, final Throwable throwable )
{
m_logger.error( message, throwable );
}
/**
* Determine if messages of priority "error" will be logged.
*
* @return true if "error" messages will be logged
*/
public final boolean isErrorEnabled()
{
return m_logger.isErrorEnabled();
}
/**
* Log a fatalError message.
*
* @param message the message
*/
public final void fatalError( final String message )
{
m_logger.fatalError( message );
}
/**
* Log a fatalError message.
*
* @param message the message
* @param throwable the throwable
*/
public final void fatalError( final String message, final Throwable throwable )
{
m_logger.fatalError( message, throwable );
}
/**
* Determine if messages of priority "fatalError" will be logged.
*
* @return true if "fatalError" messages will be logged
*/
public final boolean isFatalErrorEnabled()
{
return m_logger.isFatalErrorEnabled();
}
/**
* Create a new child logger.
* The name of the child logger is [current-loggers-name].[passed-in-name]
* Throws IllegalArgumentException
if name has an empty element name
*
* @param name the subname of this logger
* @return the new logger
*/
public final Logger getChildLogger( final String name )
{
return new LogKitLogger( m_logger.getChildLogger( name ) );
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/logger/impl/NullLogger.java
Index: NullLogger.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.logger.impl;
import org.apache.framework.logger.Logger;
/**
* The Null Logger class. This is useful for implementations where you need
* to provide a logger to a utility class, but do not want any output from it.
* It also helps when you have a utility that does not have a logger to supply.
*
* @author Berin Loritsch
* @version 1.0
*/
public final class NullLogger implements Logger
{
/**
* Creates a new NullLogger
.
*/
public NullLogger()
{
}
/**
* No-op.
*
* @param message ignored
*/
public void debug(String message)
{
}
/**
* No-op.
*
* @param message ignored
* @param throwable ignored
*/
public void debug(String message, Throwable throwable)
{
}
/**
* No-op.
*
* @return false
*/
public boolean isDebugEnabled()
{
return false;
}
/**
* No-op.
*
* @param message ignored
*/
public void info(String message)
{
}
/**
* No-op.
*
* @param message ignored
* @param throwable ignored
*/
public void info(String message, Throwable throwable)
{
}
/**
* No-op.
*
* @return false
*/
public boolean isInfoEnabled()
{
return false;
}
/**
* No-op.
*
* @param message ignored
*/
public void warn(String message)
{
}
/**
* No-op.
*
* @param message ignored
* @param throwable ignored
*/
public void warn(String message, Throwable throwable)
{
}
/**
* No-op.
*
* @return false
*/
public boolean isWarnEnabled()
{
return false;
}
/**
* No-op.
*
* @param message ignored
*/
public void error(String message)
{
}
/**
* No-op.
*
* @param message ignored
* @param throwable ignored
*/
public void error(String message, Throwable throwable)
{
}
/**
* No-op.
*
* @return false
*/
public boolean isErrorEnabled()
{
return false;
}
/**
* No-op.
*
* @param message ignored
*/
public void fatalError(String message)
{
}
/**
* No-op.
*
* @param message ignored
* @param throwable ignored
*/
public void fatalError(String message, Throwable throwable)
{
}
/**
* No-op.
*
* @return false
*/
public boolean isFatalErrorEnabled()
{
return false;
}
/**
* Returns this NullLogger
.
*
* @param name ignored
* @return this NullLogger
*/
public Logger getChildLogger(String name)
{
return this;
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/parameters/ParameterException.java
Index: ParameterException.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.parameters;
/**
* Thrown when a Parameterizable
component cannot be parameterized
* properly, or if a value cannot be retrieved properly.
*
* @author Peter Donald
*/
public final class ParameterException
extends Exception
{
/**
* The Throwable that caused this exception to be thrown.
*/
private final Throwable m_throwable;
/**
* Construct a new ParameterException
instance.
*
* @param message The detail message for this exception.
*/
public ParameterException( final String message )
{
this( message, null );
}
/**
* Construct a new ParameterException
instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public ParameterException( final String message, final Throwable throwable )
{
super( message );
m_throwable = throwable;
}
/**
* Retrieve root cause of the exception.
*
* @return the root cause
*/
public final Throwable getCause()
{
return m_throwable;
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/parameters/Parameterizable.java
Index: Parameterizable.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.parameters;
/**
* Components should implement this interface if they wish to
* be provided with parameters during startup.
*
* The Parameterizable interface is a light-weight alternative to the
* {@link org.apache.framework.configuration.Configurable}
* interface. As such, the Parameterizable
interface and
* the Configurable
interface are not
* compatible.
*
* This interface will be called after
* Composable.compose()
and before
* Initializable.initialize()
.
*
*
* @author Peter Donald
*/
public interface Parameterizable
{
/**
* Provide component with parameters.
*
* @param parameters the parameters
* @exception ParameterException if parameters are invalid
*/
void parameterize( Parameters parameters )
throws ParameterException;
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/parameters/Parameters.java
Index: Parameters.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.parameters;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.framework.configuration.Configuration;
import org.apache.framework.configuration.ConfigurationException;
/**
* The Parameters
class represents a set of key-value
* pairs.
*
* The Parameters
object provides a mechanism to obtain
* values based on a String
name. There are convenience
* methods that allow you to use defaults if the value does not exist,
* as well as obtain the value in any of the same formats that are in
* the {@link Configuration} interface.
*
* While there are similarities between the Parameters
* object and the java.util.Properties object, there are some
* important semantic differences. First, Parameters
are
* read-only. Second, Parameters
are easily
* derived from {@link Configuration} objects. Lastly, the
* Parameters
object is derived from XML fragments that
* look like this:
*
* <parameter name="param-name" value="param-value" />
*
*
* Note: this class is not thread safe by default. If you
* require thread safety please synchronize write access to this class to
* prevent potential data corruption.
*
*
* @author Pierpaolo Fumagalli
* @author Peter Donald
* @version 1.0
*/
public class Parameters
implements Serializable
{
/** Empty Parameters object */
public static final Parameters EMPTY_PARAMETERS;
/** Static initializer to initialize the empty Parameters object */
static
{
EMPTY_PARAMETERS = new Parameters();
EMPTY_PARAMETERS.makeReadOnly();
}
///Underlying store of parameters
private Map m_parameters = new HashMap();
private boolean m_readOnly;
/**
* Set the String
value of a specified parameter.
*
* If the specified value is null the parameter is removed.
*
* @param name a String
value
* @param value a String
value
* @return The previous value of the parameter or null.
* @exception IllegalStateException if the Parameters object is read-only
*/
public String setParameter( final String name, final String value )
throws IllegalStateException
{
checkWriteable();
if( null == name )
{
return null;
}
if( null == value )
{
return (String)m_parameters.remove( name );
}
return (String)m_parameters.put( name, value );
}
/**
* Remove a parameter from the parameters object
* @param name a String
value
*/
public void removeParameter( final String name )
{
setParameter( name, null );
}
/**
* Return an Iterator
view of all parameter names.
*
* @return a iterator of parameter names
* @deprecated Use getNames() instead
*/
public Iterator getParameterNames()
{
return m_parameters.keySet().iterator();
}
/**
* Retrieve an array of all parameter names.
*
* @return the parameters names
*/
public String[] getNames()
{
return (String[])m_parameters.keySet().toArray( new String[ 0 ] );
}
/**
* Test if the specified parameter can be retrieved.
*
* @param name the parameter name
* @return true if parameter is a name
*/
public boolean isParameter( final String name )
{
return m_parameters.containsKey( name );
}
/**
* Retrieve the String
value of the specified parameter.
*
* If the specified parameter cannot be found, an exception is thrown.
*
* @param name the name of parameter
* @return the value of parameter
* @throws ParameterException if the specified parameter cannot be found
*/
public String getParameter( final String name )
throws ParameterException
{
if( null == name )
{
throw new ParameterException( "You cannot lookup a null parameter" );
}
final String test = (String)m_parameters.get( name );
if( null == test )
{
throw new ParameterException( "The parameter '" + name +
"' does not contain a value" );
}
return test;
}
/**
* Retrieve the String
value of the specified parameter.
*
* If the specified parameter cannot be found, defaultValue
* is returned.
*
* @param name the name of parameter
* @param defaultValue the default value, returned if parameter does not exist
* @return the value of parameter
*/
public String getParameter( final String name, final String defaultValue )
{
try
{
return getParameter( name );
}
catch( final ParameterException pe )
{
return defaultValue;
}
}
/**
* Retrieve the int
value of the specified parameter.
*
* If the specified parameter cannot be found, an exception is thrown.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of parameter
* @return the integer parameter type
* @throws ParameterException if the specified parameter cannot be found
*/
public int getParameterAsInteger( final String name )
throws ParameterException
{
try
{
final String value = getParameter( name );
if( value.startsWith( "0x" ) )
{
return Integer.parseInt( value.substring(2), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Integer.parseInt( value.substring(2), 8 );
}
else if( value.startsWith( "0b" ) )
{
return Integer.parseInt( value.substring(2), 2 );
}
else
{
return Integer.parseInt( value );
}
}
catch( final Exception e )
{
throw new ParameterException( "Could not return an integer value", e );
}
}
/**
* Retrieve the int
value of the specified parameter.
*
* If the specified parameter cannot be found, defaultValue
* is returned.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of parameter
* @param defaultValue value returned if parameter does not exist or is of wrong type
* @return the integer parameter type
*/
public int getParameterAsInteger( final String name, final int defaultValue )
{
try
{
return getParameterAsInteger( name );
}
catch( final ParameterException pe )
{
return defaultValue;
}
}
/**
* Retrieve the long
value of the specified parameter.
*
* If the specified parameter cannot be found, an exception is thrown.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of parameter
* @return the long parameter type
* @throws ParameterException if the specified parameter cannot be found
*/
public long getParameterAsLong( final String name )
throws ParameterException
{
try
{
final String value = getParameter( name );
if( value.startsWith( "0x" ) )
{
return Long.parseLong( value.substring(2), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Long.parseLong( value.substring(2), 8 );
}
else if( value.startsWith( "0b" ) )
{
return Long.parseLong( value.substring(2), 2 );
}
else
{
return Long.parseLong( value );
}
}
catch( final Exception e )
{
throw new ParameterException( "Could not return a long value", e );
}
}
/**
* Retrieve the long
value of the specified parameter.
*
* If the specified parameter cannot be found, defaultValue
* is returned.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of parameter
* @param defaultValue value returned if parameter does not exist or is of wrong type
* @return the long parameter type
*/
public long getParameterAsLong( final String name, final long defaultValue )
{
try
{
return getParameterAsLong( name );
}
catch( final ParameterException pe )
{
return defaultValue;
}
}
/**
* Retrieve the float
value of the specified parameter.
*
* If the specified parameter cannot be found, an exception is thrown.
*
* @param name the parameter name
* @return the value
* @throws ParameterException if the specified parameter cannot be found
*/
public float getParameterAsFloat( final String name )
throws ParameterException
{
try
{
return Float.parseFloat( getParameter( name ) );
}
catch( final Exception e )
{
throw new ParameterException( "Could not return a float value", e );
}
}
/**
* Retrieve the float
value of the specified parameter.
*
* If the specified parameter cannot be found, defaultValue
* is returned.
*
* @param name the parameter name
* @param defaultValue the default value if parameter does not exist or is of wrong type
* @return the value
*/
public float getParameterAsFloat( final String name, final float defaultValue )
{
try
{
return getParameterAsFloat( name );
}
catch( final ParameterException pe )
{
return defaultValue;
}
}
/**
* Retrieve the boolean
value of the specified parameter.
*
* If the specified parameter cannot be found, an exception is thrown.
*
* @param name the parameter name
* @return the value
* @exception ParameterException if an error occurs
* @exception ParemterException
*/
public boolean getParameterAsBoolean( final String name )
throws ParameterException
{
final String value = getParameter( name );
if( value.equalsIgnoreCase( "true" ) )
{
return true;
}
else if( value.equalsIgnoreCase( "false" ) )
{
return false;
}
else
{
throw new ParameterException( "Could not return a boolean value" );
}
}
/**
* Retrieve the boolean
value of the specified parameter.
*
* If the specified parameter cannot be found, defaultValue
* is returned.
*
* @param name the parameter name
* @param defaultValue the default value if parameter does not exist or is of wrong type
* @return the value
*/
public boolean getParameterAsBoolean( final String name, final boolean defaultValue )
{
try
{
return getParameterAsBoolean( name );
}
catch( final ParameterException e )
{
return defaultValue;
}
}
/**
* Merge parameters from another Parameters
instance
* into this.
*
* @param other the other Parameters
* @return This Parameters
instance.
*/
public Parameters merge( final Parameters other )
{
checkWriteable();
final Iterator names = other.getParameterNames();
while( names.hasNext() )
{
final String name = (String) names.next();
String value = null;
try
{
value = other.getParameter( name );
}
catch( final ParameterException pe )
{
value = null;
}
setParameter( name, value );
}
return this;
}
/**
* Make this Parameters read-only so that it will throw a
* IllegalStateException
if someone tries to
* modify it.
*/
public void makeReadOnly()
{
m_readOnly = true;
}
/**
* Checks is this Parameters
object is writeable.
*
* @exception IllegalStateException if this Parameters
object is read-only
*/
protected final void checkWriteable()
throws IllegalStateException
{
if( m_readOnly )
{
throw new IllegalStateException( "Context is read only and can not be modified" );
}
}
/**
* Create a Parameters
object from a Configuration
* object. This acts exactly like the following method call:
*
* Parameters.fromConfiguration(configuration, "parameter");
*
*
* @param configuration the Configuration
* @return This Parameters
instance.
* @exception ConfigurationException if an error occurs
*/
public static Parameters fromConfiguration( final Configuration configuration )
throws ConfigurationException
{
return fromConfiguration( configuration, "parameter" );
}
/**
* Create a Parameters
object from a Configuration
* object using the supplied element name.
*
* @param configuration the Configuration
* @param elementName the element name for the parameters
* @return This Parameters
instance.
* @exception ConfigurationException if an error occurs
*/
public static Parameters fromConfiguration( final Configuration configuration,
final String elementName )
throws ConfigurationException
{
if( null == configuration )
{
throw new ConfigurationException( "You cannot convert to parameters with " +
"a null Configuration" );
}
final Configuration[] parameters = configuration.getChildren( elementName );
final Parameters params = new Parameters();
for( int i = 0; i < parameters.length; i++ )
{
try
{
final String name = parameters[ i ].getAttribute( "name" );
final String value = parameters[ i ].getAttribute( "value" );
params.setParameter( name, value );
}
catch( final Exception e )
{
throw new ConfigurationException( "Cannot process Configurable", e );
}
}
return params;
}
/**
* Create a Parameters
object from a Properties
* object.
*
* @param properties the Properties
* @return This Parameters
instance.
*/
public static Parameters fromProperties( final Properties properties )
{
final Parameters parameters = new Parameters();
final Enumeration names = properties.propertyNames();
while( names.hasMoreElements() )
{
final String key = (String)names.nextElement().toString();
final String value = properties.getProperty( key );
parameters.setParameter( key, value );
}
return parameters;
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/parameters/package.html
Index: package.html
===================================================================
Interfaces supporting the supply of flat configuration information.
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/service/ServiceException.java
Index: ServiceException.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.service;
/**
* The exception thrown to indicate a problem with service.
* It is usually thrown by ServiceManager or ServiceSelector.
*
* @author Peter Donald
* @author Pierpaolo Fumagalli
* @author Federico Barbieri
* @author Stefano Mazzocchi
* @author Stephen McConnell
*/
public class ServiceException
extends Exception
{
/**
* The Throwable that caused this exception to be thrown.
*/
private final Throwable m_throwable;
/**
* Construct a new ServiceException
instance.
*
* @param message the exception message
*/
public ServiceException( final String message )
{
this( message, null );
}
/**
* Construct a new ServiceException
instance.
*
* @param message the exception message
* @param throwable the throwable
*/
public ServiceException( final String message, final Throwable throwable )
{
super( message );
m_throwable = throwable;
}
/**
* Retrieve root cause of the exception.
*
* @return the root cause
*/
public final Throwable getCause()
{
return m_throwable;
}
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/service/ServiceManager.java
Index: ServiceManager.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.service;
/**
* A ServiceManager
selects Object
s based on a
* role. The contract is that all the Object
s implement the
* differing roles and there is one Object
per role. If you
* need to select on of many Object
s that implement the same
* role, then you need to use a ServiceSelector
. Roles are
* usually the full interface name.
*
* A role is better understood by the analogy of a play. There are many
* different roles in a script. Any actor or actress can play any given part
* and you get the same results (phrases said, movements made, etc.). The exact
* nuances of the performance is different.
*
* Below is a list of things that might be considered the different roles:
*
*
* - InputAdaptor and OutputAdaptor
* - Store and Spool
*
*
* The ServiceManager
does not specify the methodology of
* getting the Object
, merely the interface used to get it.
* Therefore the ServiceManager
can be implemented with a
* factory pattern, an object pool, or a simple Hashtable.
*
* @author Federico Barbieri
* @author Stefano Mazzocchi
* @author Pierpaolo Fumagalli
* @author Berin Loritsch
* @author Stephen McConnell
* @version 1.0
* @see org.apache.framework.service.Serviceable
*/
public interface ServiceManager
{
/**
* Get the Object
associated with the given role. For
* instance, If the ServiceManager
had a
* LoggerComponent
stored and referenced by role, I would use
* the following call:
*
* try
* {
* MyComponent log;
* myComponent = (MyComponent) manager.lookup(MyComponent.ROLE);
* }
* catch (...)
* {
* ...
* }
*
*
* @param role The role name of the Object
to retrieve.
* @return an Object
value
* @exception ServiceException if an error occurs
*/
Object lookup( String role )
throws ServiceException;
/**
* Check to see if a Object
exists for a role.
*
* @param role a string identifying the role to check.
* @return True if the object exists, False if it does not.
*/
boolean hasService( String role );
/**
* Return the Object
when you are finished with it. This
* allows the ServiceManager
to handle the End-Of-Life Lifecycle
* events associated with the Object
. Please note, that no
* Exception should be thrown at this point. This is to allow easy use of the
* ServiceManager system without having to trap Exceptions on a release.
*
* @param object The Object
we are releasing.
*/
void release( Object object );
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/service/Serviceable.java
Index: Serviceable.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.service;
/**
* A Serviceable is a class that need to connect to software components using
* a "role" abstraction, thus not depending on particular implementations
* but on behavioral interfaces.
*
*
* The contract surrounding a Serviceable
is that it is a user.
* The Serviceable
is able to use Object
s managed
* by the ServiceManager
it was initialized with. As part
* of the contract with the system, the instantiating entity must call
* the compose
method before the Serviceable
* can be considered valid.
*
* @author Federico Barbieri
* @author Pierpaolo Fumagalli
* @author Stefano Mazzocchi
* @author Berin Loritsch
* @author Stephen McConnell
* @version 1.0
* @see org.apache.framework.service.ServiceManager
*
*/
public interface Serviceable
{
/**
* Pass the ServiceManager
to the Serviceable
.
* The Serviceable
implementation should use the specified
* ServiceManager
to acquire the components it needs for
* execution.
*
* @param manager The ServiceManager
which this
* Serviceable
uses.
* @exception ServiceException if an error occurs
*/
void service( ServiceManager manager )
throws ServiceException;
}
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/service/package.html
Index: package.html
===================================================================
Interfaces and default implementation of a service management framework supporting container based service lookup and decommissioning.
1.1 jakarta-avalon/src/proposal/avalon5/org/apache/framework/service/impl/DefaultServiceManager.java
Index: DefaultServiceManager.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.framework.service.impl;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.framework.service.ServiceManager;
import org.apache.framework.service.ServiceException;
/**
* This class is a static implementation of a ServiceManager. Allow ineritance
* and extension so you can generate a tree of ServiceManager each defining
* Object scope.
*
* @author Federico Barbieri
* @author Peter Donald
* @author Stephen McConnell
* @version 1.0
*/
public class DefaultServiceManager
implements ServiceManager
{
private final HashMap m_objects = new HashMap();
private final ServiceManager m_parent;
private boolean m_readOnly;
/**
* Construct ServiceManager with no parent.
*
*/
public DefaultServiceManager()
{
this( null );
}
/**
* Construct ServiceManager with specified parent.
*
* @param parent the ServiceManager parent
*/
public DefaultServiceManager( final ServiceManager parent )
{
m_parent = parent;
}
/**
* Retrieve Object by role from ServiceManager.
*
* @param role the role
* @return the Object
* @exception org.apache.framework.service.ServiceException if an error occurs
*/
public Object lookup( final String role )
throws ServiceException
{
final Object object = m_objects.get( role );
if( null != object )
{
return object;
}
else if( null != m_parent )
{
return m_parent.lookup( role );
}
else
{
throw new ServiceException( "Unable to provide implementation for " + role );
}
}
/**
* Check to see if a Object
exists for a role.
*
* @param role a string identifying the role to check.
* @return True if the object exists, False if it does not.
*/
public boolean hasService( final String role )
{
boolean objectExists = false;
try
{
this.lookup(role);
objectExists = true;
}
catch (Throwable t)
{
// Ignore all throwables--we want a yes or no answer.
}
return objectExists;
}
/**
* Place Object into ComponentManager.
*
* @param role the components role
* @param object an Object
value
*/
public void put( final String role, final Object object )
{
checkWriteable();
m_objects.put( role, object );
}
/**
* Build a human readable representation of the ServiceManager.
*
* @return the description of the ServiceManager
*/
public String toString()
{
final StringBuffer buffer = new StringBuffer();
final Iterator objects = m_objects.keySet().iterator();
buffer.append( "Services:" );
while( objects.hasNext() )
{
buffer.append( "[" );
buffer.append( objects.next() );
buffer.append( "]" );
}
return buffer.toString();
}
/**
* Helper method for subclasses to retrieve parent.
*
* @return the parent ServiceManager
*/
protected final ServiceManager getParent()
{
return m_parent;
}
/**
* Helper method for subclasses to retrieve object map.
*
* @return the object map
*/
protected final Map getObjectMap()
{
return m_objects;
}
/**
* Makes this service manager read-only.
*
*/
public void makeReadOnly()
{
m_readOnly = true;
}
/**
* Checks if this service manager is writeable.
*
* @exception java.lang.IllegalStateException if this service manager is read-only
*/
protected final void checkWriteable()
throws IllegalStateException
{
if( m_readOnly )
{
throw new IllegalStateException
( "ServiceManager is read only and can not be modified" );
}
}
/**
* Release the object.
* @param object The Object
to release.
*/
public void release( Object object ){}
}
--
To unsubscribe, e-mail:
For additional commands, e-mail: