fede 01/02/23 02:47:52
Added: . README WARNING build.bat build.sh build.xml
lib bytecode.jar log.jar xerces.jar
src/java/org/apache/avalon AbstractConfiguration.java
AbstractLoggable.java CascadingError.java
CascadingException.java
CascadingRuntimeException.java
CascadingThrowable.java Component.java
ComponentManager.java
ComponentManagerException.java
ComponentNotAccessibleException.java
ComponentNotFoundException.java
ComponentSelector.java Composer.java
Configurable.java Configuration.java
ConfigurationBuilder.java
ConfigurationException.java Context.java
Contextualizable.java DefaultComponentManager.java
DefaultComponentSelector.java
DefaultConfiguration.java
DefaultConfigurationBuilder.java
DefaultContext.java DefaultPipeline.java
Disposable.java Initializable.java Loggable.java
Modifiable.java Parameters.java Pipeline.java
Poolable.java ProcessorPipeline.java
ProcessorStage.java Recomposer.java
Reconfigurable.java Recontextualizable.java
Recyclable.java Resolvable.java Resumable.java
SAXConfigurationHandler.java SingleThreaded.java
Stage.java Startable.java Stoppable.java
Suspendable.java ThreadSafe.java
src/java/org/apache/avalon/atlantis AbstractKernel.java
Application.java ApplicationException.java
Facility.java Kernel.java
src/java/org/apache/avalon/blocks AbstractBlock.java
Block.java
src/java/org/apache/avalon/camelot
AbstractCamelotDeployer.java AbstractContainer.java
AbstractDeployer.java AbstractZipDeployer.java
AvalonState.java CamelotUtil.java
ComponentBuilder.java ComponentManagerBuilder.java
ConfigurationRepository.java Container.java
ContainerException.java ContextBuilder.java
DefaultFactory.java DefaultLoader.java
DefaultLocator.java DefaultLocatorRegistry.java
DefaultRegistry.java Deployer.java
DeployerUtil.java DeploymentException.java
Entry.java Factory.java FactoryException.java
Info.java Loader.java Locator.java
LocatorRegistry.java LoggerBuilder.java
MetaInfo.java Registry.java RegistryException.java
State.java
src/java/org/apache/avalon/configuration
AbstractConfiguration.java Configurable.java
Configuration.java ConfigurationBuilder.java
ConfigurationException.java
DefaultConfiguration.java
DefaultConfigurationBuilder.java
Reconfigurable.java SAXConfigurationHandler.java
src/java/org/apache/avalon/services Service.java
src/java/org/apache/avalon/util ArrayEnumeration.java
ArrayStack.java BinaryHeap.java Circuit.java
CircularBuffer.java
CircularDependencyException.java
DependencyGraph.java Enum.java
IteratorEnumeration.java ListUtils.java Lock.java
LockException.java ObjectUtil.java Primes.java
PriorityQueue.java PropertyException.java
PropertyUtil.java ProxyClassLoader.java
ProxyGenerator.java StringUtil.java ValuedEnum.java
Version.java
src/java/org/apache/avalon/util/cli AbstractMain.java
AbstractParserControl.java CLArgsParser.java
CLOption.java CLOptionDescriptor.java CLUtil.java
ParserControl.java
src/java/org/apache/avalon/util/cli/test ClutilTestlet.java
src/java/org/apache/avalon/util/i18n ResourceGroup.java
XMLResourceBundle.java
XMLResourceBundleFactory.java XPathAPI.java
src/java/org/apache/avalon/util/internet
CRLFInputStream.java CRLFOutputStream.java
InternetException.java InternetReply.java
InternetStream.java LineReader.java LineWriter.java
src/java/org/apache/avalon/util/io
ByteTerminatedInputStream.java
DirectoryFileFilter.java ExtensionFileFilter.java
FileUtil.java IOUtil.java MergedInputStreams.java
ResettableFileInputStream.java
src/java/org/apache/avalon/util/io/test FileUtilTestlet.java
src/java/org/apache/avalon/util/lang ThreadManager.java
src/java/org/apache/avalon/util/log AvalonLogFormatter.java
DefaultLogManager.java
src/java/org/apache/avalon/util/pipeline
AbstractLifeCycleStage.java CompositionStage.java
ConfigurationStage.java ContextualizationStage.java
CreationStage.java DisposingStage.java
InitializationStage.java LifeCyclePipeline.java
LifeCycleStage.java LoggerStage.java
OldConfigurationStage.java RunnerStage.java
ShutdownPipeline.java StartStage.java
StartupPipeline.java StopStage.java
src/java/org/apache/avalon/util/pool AbstractPool.java
DefaultObjectFactory.java DefaultPool.java
ObjectFactory.java Pool.java PoolController.java
ThreadSafePool.java
src/java/org/apache/avalon/util/pool/test PoolProfile.java
src/java/org/apache/avalon/util/security AbstractPolicy.java
DefaultPolicy.java PolicyClassLoader.java
src/java/org/apache/avalon/util/test BinaryHeapTestlet.java
DependencyGraphTestlet.java
PropertyUtilTestlet.java ProxyGeneratorTestlet.java
StringUtilTestlet.java
src/java/org/apache/avalon/util/thread
DefaultThreadManager.java ThreadContext.java
ThreadManager.java ThreadPool.java
WorkerThread.java
src/make build-docs.xml
src/skins javadoc.css
src/skins/avalon loader.xml
src/skins/avalon/resources header.gif jakarta-logo.gif
line.gif
src/skins/avalon/stylesheets book2project.xsl
changes2document.xsl directory2project.xsl
document2html.xsl document2project.xsl
scan4resources.xsl
src/xdocs administrator-guide.xml assemblers-guide.xml
blank.xml block-developers-guide.xml book.xml
changes.xml code-standards.xml contributors.xml
deployers-guide.xml design.xml features.xml
getting-started.xml history.xml index.xml
install.xml license.xml mail.xml phoenix.xml
to-merge.txt todo.xml
src/xdocs/design components.xml composer.xml
inversion-of-control.xml life-cycle.xml
patterns.xml reuse-standards.xml security.xml
separation-of-concerns.xml
src/xdocs/dtd changes-v10.dtd characters.ent
document-v10.dtd
src/xdocs/history call-to-vote.xml need-for-avalon.xml
what-is-a-server.xml
src/xdocs/history/images server-01.gif server-02.gif
server-03.gif server-04.gif
src/xdocs/images add.jpg remove.jpg update.jpg
src/xdocs/phoenix assembly-xml-specification.xml
blockinfo-specification.xml creating-a-block.xml
creating-a-server-application.xml
server-xml-specification.xml what-is-a-block.xml
what-is-a-server-application.xml
tools/bin ant ant.bat antRun antRun.bat lcp.bat
tools/lib ant.jar optional.jar stylebook-1.0-b2.jar
testlet.jar xalan_1_2_D02.jar
Log:
Avalon moved from java.apache.org
Revision Changes Path
1.1 jakarta-avalon/README
Index: README
===================================================================
A V A L O N
@@version@@
What is it?
-----------
It is a set of classes and patterns that support high level server
development.
Where is it?
------------
http://java.apache.org/framework
Requirements
------------
-JDK1.2 or above
-To build form CVS you must set JAVA_HOME to the jdk dir
(eg:/usr/bin/jdk1.2 or
c:\jdk1.3)
Distribution
------------
Distribution contains the following:
-xerces.jar Any SAX2 parser will work. By default xerces is
used.
-avalon-engine.jar The avalon kernel
-avalon-demo.sar Sample server application provided with the kernel
-avalon-loader.jar Avalon loader
Installation Instructions and Documentation
-------------------------------------------
Avalon is a framework that loads and runs servers. Without a server
plugged into it, it doesn't do anything. To run it just execute run.bat
or run.sh in the distribution bin folder. See docs/ subdirectory for further
documentation.
Acknowledgements
----------------
As well as code from various Apache projects this projects also
contains code (bytecode manipulation) from the Kawa project at
http://www.gnu.org/software/kawa/
Licensing and legal issues
--------------------------
For other legal and licensing issues, please read the LICENSE file.
Thanks for using Avalon.
The Java Apache Project
http://java.apache.org/
1.1 jakarta-avalon/WARNING
Index: WARNING
===================================================================
***************************** W A R N I N G
**********************************
All user accessible points in this software package are to be considered
"alpha". This means that the developer team is not investing _any_ effort
in providing back compatibility between alpha releases.
This software will continue to be released as "alpha" until both code,
schemas and APIs will be considered stable.
Until then, there will be no warranty that newer versions will maintain back
compatibility even in the most simple cases.
On the other hand, once "beta" status is reached, back incompatible changes
will be made only if absolutely necessary to reach "final" status.
The Avalon development team understands the importance of reliable
software as well as the importance of protecting user investiments by the
creation of a solid development platform that doesn't change.
On the other hand, being the Avalon project a pioneer in many fields, this
cannot be guaranteed before a final status is reached for the software.
Until then, no effort will be provided to guarantee back compatibility.
You have been warned.
***************************** W A R N I N G
**********************************
1.1 jakarta-avalon/build.bat
Index: build.bat
===================================================================
@echo off
echo -------------------
echo Avalon Build System
echo -------------------
set ANT_HOME=tools
set BUILD_FILE=build.xml
set LOCALCLASSPATH=
for %%i in (lib\*.jar) do call %ANT_HOME%\bin\lcp.bat %%i
set CLASSPATH=%LOCALCLASSPATH%
set LOCALCLASSPATH=
:runAnt
%ANT_HOME%\bin\ant.bat -logger org.apache.tools.ant.NoBannerLogger -emacs %1
%2 %3 %4 %5 %6 %7 %8
set BUILD_FILE=
set ANT_HOME=
set CLASSPATH=
1.1 jakarta-avalon/build.sh
Index: build.sh
===================================================================
#!/bin/sh
echo
echo "Avalon Build System"
echo "-------------------"
export CLASSPATH=`echo $PWD/lib/*.jar | tr ' ' ':'`
chmod u+x ./tools/bin/antRun
chmod u+x ./tools/bin/ant
export PROPOSAL=""
unset ANT_HOME
if [ "$1" = "proposal" ]; then
export PROPOSAL="-buildfile proposal/make/proposal.xml"
fi
$PWD/tools/bin/ant -logger org.apache.tools.ant.NoBannerLogger -emacs
$PROPOSAL $@
1.1 jakarta-avalon/build.xml
Index: build.xml
===================================================================
<?xml version="1.0"?>
<!--
==============================================================================
Avalon build file
Authors:
Federico Barbieri <[EMAIL PROTECTED]>
Berin Loritsch <[EMAIL PROTECTED]>
Peter Donald <[EMAIL PROTECTED]>
Legal:
Copyright (c) 1999-2000 The Apache Software Foundation. All Rights Reserved.
==============================================================================
-->
<project default="main" basedir=".">
<!--
Give user a chance to override without editing this file
(and without typing -D each time he compiles it)
-->
<property file=".ant.properties"/>
<property file="${user.home}/.ant.properties"/>
<property name="name" value="avalonapi"/>
<property name="Name" value="Avalon"/>
<property name="version" value="3.1a1-dev"/>
<property name="year" value="1999-2001"/>
<!--
these are here only for those who use jikes compiler. For other
developers this part makes no difference.
-->
<property name="build.compiler.emacs" value="on"/>
<property name="build.compiler.warnings" value="true"/>
<!-- <property name="build.compiler.pedantic" value="true"/> -->
<property name="build.compiler.depend" value="true"/>
<property name="build.compiler.fulldepend" value="true"/>
<property name="debug" value="off"/>
<property name="optimize" value="off"/>
<property name="deprecation" value="off"/>
<!--
===================================================================
Set the properties for intermediate directory
===================================================================
-->
<property name="build.dir" value="build"/>
<property name="build.lib" value="${build.dir}/lib"/>
<property name="build.src" value="${build.dir}/src"/>
<property name="build.classes" value="${build.dir}/classes"/>
<property name="build.javadocs" value="${build.dir}/javadocs"/>
<property name="build.docs" value="${build.dir}/docs"/>
<!--
===================================================================
Set the properties for source directories
===================================================================
-->
<property name="src.dir" value="src"/>
<property name="java.dir" value="${src.dir}/java"/>
<property name="script.dir" value="${src.dir}/script"/>
<property name="lib.dir" value="lib"/>
<property name="tools.dir" value="tools"/>
<property name="docs.dir" value="docs"/>
<property name="javadocs.dir" value="${build.docs}/api"/>
<property name="dist.name" value="${name}-${version}"/>
<!--
===================================================================
Main target
===================================================================
-->
<target name="main" depends="dist-lite" />
<!--
===================================================================
Help on usage
===================================================================
-->
<target name="usage">
<echo message=""/>
<echo message="${Name} Build file"/>
<echo
message="-------------------------------------------------------------"/>
<echo message=""/>
<echo message=" available targets are:"/>
<echo message=""/>
<echo message=" jar --> generates the ${Name} jar files"/>
<echo message=" test --> perform unit tests"/>
<echo message=" compile --> compiles the source code"/>
<echo message=" javadocs --> generates the API documentation (java
1.2+ only)"/>
<echo message=" docs --> generates the ${Name} Documentation"/>
<echo message=" dist-lite --> generates the ${Name} distribution
without the javadocs (default)"/>
<echo message=" dist --> generates the ${Name} distribution"/>
<echo message=" clean --> cleans up the created directories"/>
<echo message=" real-clean --> cleans up all genereated files and
directories"/>
<echo message=""/>
<echo
message="-------------------------------------------------------------"/>
<echo message=""/>
</target>
<target name="help" depends="usage"/>
<!--
===================================================================
Set up dist properties
===================================================================
-->
<target name="setup-properties" >
<property name="dist.dir" value="dist"/>
<property name="dist.bin" value="${dist.dir}/bin"/>
<property name="dist.apps" value="${dist.dir}/apps"/>
<property name="dist.lib" value="${dist.dir}/lib"/>
<property name="dist.docs" value="${dist.dir}/docs"/>
<property name="dist.javadocs" value="${dist.dir}/docs/api"/>
<property name="src.dist.dir" value="dist-src"/>
<property name="src.dist.src" value="${src.dist.dir}/src"/>
<property name="src.dist.docs" value="${src.dist.dir}/docs"/>
<property name="src.dist.javadocs" value="${src.dist.dir}/docs/api"/>
<property name="src.dist.lib" value="${src.dist.dir}/lib"/>
<property name="src.dist.tools" value="${src.dist.dir}/tools"/>
</target>
<!--
===================================================================
Checks the environment for existing resources
===================================================================
-->
<target name="check-environment">
<available property="test-task.present"
classname="org.apache.tools.ant.taskdefs.Test" />
<available property="xalan.present"
classname="org.apache.xalan.xpath.XPath" />
</target>
<!--
===================================================================
Prepares the build directory
===================================================================
-->
<target name="prepare" depends="check-environment,setup-properties">
<tstamp/>
<filter token="year" value="${year}"/>
<filter token="version" value="${version}"/>
<filter token="date" value="${TODAY}"/>
<property name="date" value="${TODAY}" />
<mkdir dir="${build.dir}"/>
<mkdir dir="${build.lib}"/>
<copy file="${lib.dir}/xerces.jar" todir="${build.lib}"/>
<mkdir dir="${build.src}"/>
<copy todir="${build.src}">
<fileset dir="${java.dir}">
</fileset>
</copy>
</target>
<!--
===================================================================
Compiles the source code
===================================================================
-->
<target name="compile" depends="prepare">
<mkdir dir="${build.classes}"/>
<javac srcdir="${build.src}"
destdir="${build.classes}"
debug="${debug}"
optimize="${optimize}"
deprecation="${deprecation}">
<classpath>
<pathelement location="${lib.dir}/log.jar"/>
<fileset dir="${build.lib}">
<include name="*.jar" />
</fileset>
</classpath>
</javac>
</target>
<!--
===================================================================
Create documentation
===================================================================
-->
<target name="docs" depends="prepare" >
<ant antfile="src/make/build-docs.xml" target="docs" />
</target>
<!--
===================================================================
Create documentation
===================================================================
-->
<target name="xdocs" depends="prepare">
<ant antfile="src/make/build-docs.xml" target="xdocs" />
</target>
<!--
===================================================================
Create api documentation
===================================================================
-->
<target name="javadocs" depends="prepare" >
<ant antfile="src/make/build-docs.xml" target="javadocs" />
</target>
<!--
===================================================================
Creates all the .jar files
===================================================================
-->
<target name="jars" depends="compile">
<jar jarfile="${build.lib}/${dist.name}.jar" basedir="${build.classes}">
<include name="org/apache/avalon/**"/>
</jar>
</target>
<!--
===================================================================
Create the lite build
===================================================================
-->
<target name="dist-lite" depends="jars">
<mkdir dir="${dist.dir}"/>
<copy file="${build.lib}/${dist.name}.jar"
tofile="${dist.dir}/${dist.name}.jar"/>
</target>
<!--
===================================================================
Create the distribution
===================================================================
-->
<target name="dist" depends="dist-lite,javadocs,docs">
<mkdir dir="${dist.docs}"/>
<mkdir dir="${dist.javadocs}"/>
<copy todir="${dist.docs}">
<fileset dir="${build.docs}"/>
</copy>
<copy todir="${dist.javadocs}">
<fileset dir="${build.javadocs}"/>
</copy>
<copy todir="${dist.dir}">
<fileset dir=".">
<include name="README"/>
<include name="WARNING"/>
</fileset>
</copy>
<chmod dir="${dist.dir}" perm="go-rwx" />
<zip zipfile="${dist.name}-bin.zip" basedir="${dist.dir}/.."
includes="${dist.dir}/**"/>
<tar tarfile="${dist.name}-bin.tar" basedir="${dist.dir}/.."
includes="${dist.dir}/**"/>
<gzip zipfile="${dist.name}-bin.tar.gz" src="${dist.name}-bin.tar"/>
<delete file="${dist.name}-bin.tar"/>
</target>
<!--
===================================================================
Create the source distribution
===================================================================
-->
<target name="src-dist" depends="docs,setup-properties">
<mkdir dir="${src.dist.dir}" />
<copy todir="${src.dist.tools}">
<fileset dir="${tools.dir}"/>
</copy>
<copy todir="${src.dist.lib}">
<fileset dir="${lib.dir}">
<include name="README" />
<include name="bytecode.jar" />
<include name="xerces.jar" />
</fileset>
</copy>
<copy todir="${src.dist.src}">
<fileset dir="${src.dir}"/>
</copy>
<copy todir="${src.dist.docs}">
<fileset dir="${build.docs}"/>
</copy>
<copy todir="${src.dist.javadocs}">
<fileset dir="${build.javadocs}"/>
</copy>
<copy todir="${src.dist.dir}">
<fileset dir=".">
<include name="README"/>
<include name="WARNING"/>
<include name="build.bat"/>
<include name="build.sh"/>
<include name="build.xml"/>
</fileset>
</copy>
<fixcrlf srcdir="${src.dist.dir}" includes="build.sh" cr="remove"/>
<fixcrlf srcdir="${src.dist.dir}" includes="build.bat" cr="add"/>
<chmod perm="+x">
<fileset dir="${src.dist.dir}">
<include name="build.sh" />
</fileset>
</chmod>
<fixcrlf srcdir="${src.dist.src}/java" includes="**/*.java" cr="remove"/>
<chmod dir="${src.dist.dir}" perm="go-rwx" />
<zip zipfile="${dist.name}-src.zip"
basedir="${src.dist.dir}/.."
includes="${src.dist.dir}/**"/>
<delete dir="${src.dist.dir}" />
</target>
<!--
===================================================================
Completely build all dists
===================================================================
-->
<target name="full-dist">
<antcall target="src-dist">
<param name="src.dist.dir" value="${dist.name}" />
</antcall>
<antcall target="dist">
<param name="dist.dir" value="${dist.name}" />
</antcall>
<delete dir="${dist.name}" />
</target>
<!--
===================================================================
Cleans up build and distribution directories
===================================================================
-->
<target name="clean" depends="setup-properties">
<delete dir="${build.dir}" />
<delete dir="${dist.dir}" />
<delete>
<fileset dir="." includes="**/*~" defaultexcludes="no"/>
</delete>
</target>
<!--
===================================================================
Cleans absolutely everything up
===================================================================
-->
<target name="real-clean" depends="clean">
<delete dir="${docs.dir}" />
<delete file="${dist.name}-bin.tar.gz" />
<delete file="${dist.name}-bin.zip" />
<delete file="${dist.name}-src.zip" />
</target>
</project>
1.1 jakarta-avalon/lib/bytecode.jar
<<Binary file>>
1.1 jakarta-avalon/lib/log.jar
<<Binary file>>
1.1 jakarta-avalon/lib/xerces.jar
<<Binary file>>
1.1
jakarta-avalon/src/java/org/apache/avalon/AbstractConfiguration.java
Index: AbstractConfiguration.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 file.
*/
package org.apache.avalon;
import java.util.Iterator;
/**
* This is an abstract <code>Configuration</code> implementation that deals
* with methods that can be abstracted away from underlying implementations.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @version CVS $Revision: 1.1 $ $Date: 2001/02/23 10:47:33 $
* @deprecated This has been deprecated in favour of configuration interface
in org.apache.avalon.configuration interface
*/
public abstract class AbstractConfiguration
implements Configuration
{
private static int PREFIX = 2;
/**
* Returns the value of the configuration element as an <code>int</code>.
*/
public int getValueAsInt()
throws ConfigurationException
{
final String value = getValue();
try
{
if( value.startsWith("0x") )
{
return Integer.parseInt(
value.substring(AbstractConfiguration.PREFIX), 16 );
}
else if( value.startsWith("0o") )
{
return Integer.parseInt(
value.substring(AbstractConfiguration.PREFIX), 8 );
}
else if( value.startsWith("0b") )
{
return Integer.parseInt(
value.substring(AbstractConfiguration.PREFIX), 2 );
}
else
{
return Integer.parseInt( value );
}
}
catch( final Exception nfe )
{
throw
new ConfigurationException( "Cannot parse the value of the
configuration " +
"element \"" + getName() + "\" as
an integer" );
}
}
/**
* Returns the value of the configuration element as an <code>int</code>.
*/
public int getValueAsInt( final int defaultValue )
{
try
{
return getValueAsInt();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a <code>long</code>.
*/
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 of the
" +
"configuration element \"" +
getName() +
"\" as a long" );
}
}
/**
* Returns the value of the configuration element as a <code>long</code>.
*/
public long getValueAsLong( final long defaultValue )
{
try
{
return getValueAsLong();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a <code>float</code>.
*/
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 of the
" +
"configuration element \"" +
getName() +
"\" as a float" );
}
}
/**
* Returns the value of the configuration element as a <code>float</code>.
*/
public float getValueAsFloat( final float defaultValue )
{
try
{
return getValueAsFloat();
}
catch( final ConfigurationException ce )
{
return(defaultValue);
}
}
/**
* Returns the value of the configuration element as a
<code>boolean</code>.
*/
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 of the
" +
"configuration element \"" +
getName() + "\" as a boolean" );
}
}
/**
* Returns the value of the configuration element as a
<code>boolean</code>.
*/
public boolean getValueAsBoolean( final boolean defaultValue )
{
try
{
return getValueAsBoolean();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a
<code>String</code>.
*/
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
* <code>int</code>.
*/
public int getAttributeAsInt( 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 of the
attribute \"" +
name + "\" of the configuration
element \"" +
getName() + "\" as an integer"
);
}
}
/**
* Returns the value of the attribute specified by its name as an
* <code>int</code>.
*/
public int getAttributeAsInt( final String name, final int defaultValue )
{
try
{
return getAttributeAsInt( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as a
* <code>long</code>.
*/
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 Integer.parseInt( value );
}
}
catch( final Exception nfe )
{
throw new ConfigurationException( "Cannot parse the value of the
attribute \"" +
name + "\" of the configuration
element \"" +
getName() + "\" as a long" );
}
}
/**
* Returns the value of the attribute specified by its name as a
* <code>long</code>.
*/
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
* <code>float</code>.
*/
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 of the
attribute \"" +
name + "\" of the configuration
element \"" +
getName() + "\" as a float" );
}
}
/**
* Returns the value of the attribute specified by its name as a
* <code>float</code>.
*/
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
* <code>boolean</code>.
*/
public boolean getAttributeAsBoolean( final String name )
throws ConfigurationException
{
final String value = getAttribute( name );
if( value.equals("true") ) return true;
else if( value.equals("false") ) return false;
else
{
throw new ConfigurationException( "Cannot parse the value of the
attribute \"" +
name + "\" of the configuration
element \"" +
getName() + "\" as a boolean" );
}
}
/**
* Returns the value of the attribute specified by its name as a
* <code>boolean</code>.
*/
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
* <code>String</code>.
*/
public String getAttribute( final String name, final String defaultValue )
{
try
{
return getAttribute( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Return the first <code>Configuration</code> object child of this
* associated with the given name.
*/
public Configuration getChild( final String name )
{
final Iterator iterator = getChildren( name );
if( iterator.hasNext() )
{
return (Configuration)iterator.next();
}
else
{
return new DefaultConfiguration( name, "-" );
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/AbstractLoggable.java
Index: AbstractLoggable.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 file.
*/
package org.apache.avalon;
import org.apache.log.Logger;
/**
* Helper class to inherit from.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class AbstractLoggable
implements Component, Loggable
{
protected Logger m_logger;
public void setLogger( final Logger logger )
{
m_logger = logger;
}
protected final Logger getLogger()
{
return m_logger;
}
protected void setupLogger( final Component component )
{
setupLogger( component, (String)null );
}
protected void setupLogger( final Component component, final String
subCategory )
{
if( component instanceof Loggable )
{
Logger logger = m_logger;
if( null != subCategory )
{
logger = m_logger.getChildLogger( subCategory );
}
((Loggable)component).setLogger( logger );
}
}
protected void setupLogger( final Component component, final Logger
logger )
{
if( component instanceof Loggable )
{
((Loggable)component).setLogger( logger );
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/CascadingError.java
Index: CascadingError.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 file.
*/
package org.apache.avalon;
/**
* Class from which all exceptions should inherit.
* Allows recording of nested exceptions.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class CascadingError
extends Error
implements CascadingThrowable
{
private final Throwable m_throwable;
/**
* Construct a new <code>CascadingError</code> instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public CascadingError( 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/java/org/apache/avalon/CascadingException.java
Index: CascadingException.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 file.
*/
package org.apache.avalon;
/**
* Class from which all exceptions should inherit.
* Allows recording of nested exceptions.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class CascadingException
extends Exception
implements CascadingThrowable
{
private final Throwable m_throwable;
/**
* Construct a new <code>CascadingException</code> instance.
*
* @param message The detail message for this exception.
*/
public CascadingException( final String message )
{
this( message, null );
}
/**
* Construct a new <code>CascadingException</code> instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public CascadingException( 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/java/org/apache/avalon/CascadingRuntimeException.java
Index: CascadingRuntimeException.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 file.
*/
package org.apache.avalon;
/**
* Class from which all exceptions should inherit.
* Allows recording of nested exceptions.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class CascadingRuntimeException
extends RuntimeException
implements CascadingThrowable
{
private final Throwable m_throwable;
/**
* Construct a new <code>CascadingRuntimeException</code> instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public CascadingRuntimeException( 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/java/org/apache/avalon/CascadingThrowable.java
Index: CascadingThrowable.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 file.
*/
package org.apache.avalon;
/**
* Interface which all cascadign throwables should implement.
* Allows recording of nested exceptions.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface CascadingThrowable
{
Throwable getCause();
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Component.java
Index: Component.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 file.
*/
package org.apache.avalon;
/**
* This interface identifies classes that can be used as
<code>Components</code>
* by a <code>Composer</code>.
* <br />
*
* The contract surrounding the <code>Component</code> is that it is
* used, but not a user. When a class implements this interface, it
* is stating that other entities may use that class. As part of the
* contract with the system, a <code>Component</code> must always
* declare an empty constructor.
* <br />
*
* A <code>Component</code> is the basic building block of the Avalon.
* When a class implements this interface, it allows itself to be
* managed by a <code>ComponentManager</code> and used by an outside
* element called a <code>Composer</code>. The <code>Composer</code>
* must know what type of <code>Component</code> it is accessing, so
* it will re-cast the <code>Component</code> into the type it needs.
* <br />
*
* In order for a <code>Component</code> to be useful you must either
* extend this interface, or implement this interface in conjunction
* with one that actually has methods. The new interface is the contract
* with the <code>Composer</code> that this is a particular type of
* component, and as such it can perform those functions on that type
* of component.
* <br />
*
* For example, we want a component that performs a logging function
* so we extend the <code>Component</code> to be a
<code>LoggingComponent</code>.
*
* <pre>
* interface LoggingComponent extends Component {
* log(String message);
* }
* </pre>
*
* Now all <code>Composer</code>s that want to use this type of component,
* will re-cast the <code>Component</code> into a
<code>LoggingComponent</code>
* and the <code>Composer</code> will be able to use the <code>log</code>
* method.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]>Berin Loritsch</a>
*/
public interface Component
{
}
1.1
jakarta-avalon/src/java/org/apache/avalon/ComponentManager.java
Index: ComponentManager.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 file.
*/
package org.apache.avalon;
/**
* A <code>ComponentManager</code> selects <code>Component</code>s based on a
* role. The contract is that all the <code>Component</code>s implement the
* differing roles and there is one <code>Component</code> per role. If you
* need to select on of many <code>Component</code>s that implement the same
* role, then you need to use a <code>ComponentSelector</code>. Roles are 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 <code>ComponentManager</code> does not specify the methodology of
* getting the <code>Component</code>, merely the interface used to get it.
* Therefore the <code>ComponentManager</code> can be implemented with a
* factory pattern, an object pool, or a simple Hashtable.
*
* @see org.apache.avalon.Component
* @see org.apache.avalon.Composer
* @see org.apache.avalon.ComponentSelector
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]>Berin Loritsch</a>
*/
public interface ComponentManager
{
/**
* Get the <code>Component</code> associated with the given role. For
* instance, If the <code>ComponentManager</code> had a
* <code>LoggerComponent</code> stored and referenced by role, I would use
* the following call:
* <pre>
* try {
* LoggerComponent log;
* log = (LoggerComponent)
manager.lookup("org.apache.avalon.blocks.Logger");
* } catch (...) {
* ...
* }
* </pre>
*
* @param name The role name of the <code>Component</code> to retrieve.
*
* @exception ComponentNotFoundException If the given role is not
associated
* with a <code>Component</code>.
* @exception ComponentNotAccessibleException If a <code>Component</code>
* instance cannot be created.
*/
Component lookup( String role )
throws ComponentManagerException, ComponentNotFoundException,
ComponentNotAccessibleException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/ComponentManagerException.java
Index: ComponentManagerException.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 file.
*/
package org.apache.avalon;
/**
* This base class of exceptions thrown by ComponentManager.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
*/
public class ComponentManagerException
extends CascadingException
{
/**
* Construct a new <code>ComponentManagerException</code> instance.
*/
public ComponentManagerException( final String message, final Throwable
throwable )
{
super( message, throwable );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/ComponentNotAccessibleException.java
Index: ComponentNotAccessibleException.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 file.
*/
package org.apache.avalon;
/**
* This exception is thrown by the <code>ComponentManager</code> when a
* <code>Component</code> cannot be accessed.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
*/
public class ComponentNotAccessibleException
extends ComponentManagerException
{
/**
* Construct a new <code>ComponentNotAccessibleException</code> instance.
*/
public ComponentNotAccessibleException( final String message )
{
this( message, null );
}
/**
* Construct a new <code>ComponentNotAccessibleException</code> instance.
*/
public ComponentNotAccessibleException( final String message, final
Throwable throwable )
{
super( message, throwable );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/ComponentNotFoundException.java
Index: ComponentNotFoundException.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 file.
*/
package org.apache.avalon;
/**
* This exception is thrown by the <code>ComponentManager</code> when a
* <code>Component</code> cannot be found.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
*/
public final class ComponentNotFoundException
extends ComponentManagerException
{
/**
* Constructs the ComponentNotFoundException with an initial
* message.
*/
public ComponentNotFoundException( final String message )
{
this( message, null );
}
/**
* Constructs the ComponentNotFoundException with an initial
* message.
*/
public ComponentNotFoundException( final String message, final Throwable
throwable )
{
super( message, throwable );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/ComponentSelector.java
Index: ComponentSelector.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 file.
*/
package org.apache.avalon;
/**
* A <code>ComponentSelector</code> selects <code>Component</code>s based on a
* hint. The contract is that all the <code>Component</code>s implement the
* same role.
*
* 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 same role:
*
* > XMLInputAdaptor and PropertyInputAdaptor
* > FileGenerator and SQLGenerator
*
* The <code>ComponentSelector</code> does not specify the methodology of
* getting the <code>Component</code>, merely the interface used to get it.
* Therefore the <code>ComponentSelector</code> can be implemented with a
* factory pattern, an object pool, or a simple Hashtable.
*
* @see org.apache.avalon.Component
* @see org.apache.avalon.Composer
* @see org.apache.avalon.ComponentManager
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
*/
public interface ComponentSelector
extends Component
{
/**
* Select the <code>Component</code> associated with the given hint.
* For instance, If the <code>ComponentSelector</code> has a
* <code>Generator</code> stored and referenced by a URL, I would use the
* following call:
*
* <pre>
* try {
* Generator input;
* input = (Generator) selector.select(new URL("foo://demo/url"));
* } catch (...) {
* ...
* }
* </pre>
*
* @param name A hint to retrieve the correct <code>Component</code>.
*
* @exception ComponentNotFoundException If the given role is not
associated
* with a <code>Component</code>.
* @exception ComponentNotAccessibleException If a <code>Component</code>
* instance cannot be created.
*/
Component select( Object hint )
throws ComponentManagerException, ComponentNotFoundException,
ComponentNotAccessibleException;
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Composer.java
Index: Composer.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 file.
*/
package org.apache.avalon;
/**
* A composer is a class that need to connect to software components using
* a "role" abstraction, thus not depending on particular implementations
* but on behavioral interfaces.
* <br />
*
* The contract surrounding a <code>Composer</code> is that it is a user.
* The <code>Composer</code> is able to use <code>Components</code> managed
* by the <code>ComponentManager</code> it was initialized with. As part
* of the contract with the system, the instantiating entity must call
* the <code>setComponenetManager</code> method before the
* <code>Composer</code> can be considered valid. The
* <code>setComponentManager</code> method must be called after the
constructor
* and before any user methods.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
*/
public interface Composer
{
/**
* Pass the <code>ComponentManager</code> to the <code>composer</code>.
* The <code>Composer</code> implementation should use the specified
* <code>ComponentManager</code> to acquire the components it needs for
* execution.
*
* @param manager The <code>ComponentManager</code> which this
* <code>Composer</code> uses.
*/
void compose( ComponentManager componentManager )
throws ComponentManagerException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/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 file.
*/
package org.apache.avalon;
/**
* This interface should be implemented by classes that need to be
* configured with custom parameters before initialization.
* <br />
*
* The contract surrounding a <code>Configurable</code> is that the
* instantiating entity must call the <code>configure</code>
* method before it is valid. The <code>configure</code> method
* must be called after the constructor, and before any other method.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @deprecated This has been deprecated in favour of configuration interface
in org.apache.avalon.configuration interface
*/
public interface Configurable
{
/**
* Pass the <code>Configuration</code> to the <code>Configurable</code>
* class. This method must always be called after the constructor
* and before any other method.
*
* @param configuration the class configurations.
*/
void configure( Configuration configuration )
throws ConfigurationException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/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 file.
*/
package org.apache.avalon;
import java.util.Iterator;
/**
* <code>Configuration</code> is a interface encapsulating a configuration
node
* used to retrieve configuration values. This is a "read only" interface
* preventing applications from modifying their own configurations.
* <br />
*
* The contract surrounding the <code>Configuration</code> is that once
* it is created, information never changes. The <code>Configuration</code>
* is built by the <code>SAXConfigurationBuilder</code> and the
* <code>ConfigurationImpl</code> helper classes.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @deprecated This has been deprecated in favour of configuration interface
in org.apache.avalon.configuration interface
*/
public interface Configuration
{
/**
* Return the name of the node.
*
* @post getName() != null
*
* @return name of the <code>Configuration</code> node.
*/
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();
/**
* Return a new <code>Configuration</code> instance encapsulating the
* specified child node.
*
* @pre child != null
* @post getConfiguration() != null
*
* @param child The name of the child node.
* @return Configuration
*/
Configuration getChild( String child );
/**
* Return an <code>Iterator</code> of <code>Configuration<code>
* elements containing all node children with the specified name.
*
* @pre name != null
* @post getConfigurations() != null
*
* @param name The name of the children to get.
* @return The child nodes with name
*/
Iterator getChildren( String name );
/**
* Return the value of specified attribute.
*
* @pre paramName != null
* @post getAttribute != null
*
* @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.
*/
String getAttribute( String paramName ) throws ConfigurationException;
/**
* Return the <code>int</code> value of the specified attribute contained
* in this node.
*
* @pre paramName != null
* @post getAttributeAsInt() != null
*
* @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 <code>int</code>
fails.
*/
int getAttributeAsInt( String paramName ) throws ConfigurationException;
/**
* Returns the value of the attribute specified by its name as a
* <code>long</code>.
*
* @pre paramName != null
* @post getAttributeAsLong() != null
*
* @param paramName 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
<code>long</code> fails.
*/
long getAttributeAsLong( String name ) throws ConfigurationException;
/**
* Return the <code>float</code> value of the specified parameter
contained
* in this node.
*
* @pre paramName != null
* @post getAttributeAsFloat() != null
*
* @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
<code>float</code> fails.
*/
float getAttributeAsFloat( String paramName ) throws
ConfigurationException;
/**
* Return the <code>boolean</code> value of the specified parameter
contained
* in this node.<br>
*
* @pre paramName != null
* @post getAttributeAsBoolean() != null
*
* @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
<code>boolean</code> fails.
*/
boolean getAttributeAsBoolean( String paramName ) throws
ConfigurationException;
/**
* Return the <code>String</code> value of the node.
*
* @post getValue() != null
*
* @return the value of the node.
*/
String getValue() throws ConfigurationException;
/**
* Return the <code>int</code> value of the node.
*
* @post getValueAsInt() != null
*
* @returns the value of the node.
*
* @exception ConfigurationException If conversion to <code>int</code>
fails.
*/
int getValueAsInt() throws ConfigurationException;
/**
* Return the <code>float</code> value of the node.
*
* @post getValueAsFloat() != null
*
* @return the value of the node.
* @exception ConfigurationException If conversion to <code>float</code>
fails.
*/
float getValueAsFloat() throws ConfigurationException;
/**
* Return the <code>boolean</code> value of the node.
*
* @post getValueAsBoolean() != null
*
* @return the value of the node.
* @exception ConfigurationException If conversion to
<code>boolean</code> fails.
*/
boolean getValueAsBoolean() throws ConfigurationException;
/**
* Return the <code>long</code> value of the node.<br>
*
* @post getValueAsLong() != null
*
* @return the value of the node.
* @exception ConfigurationException If conversion to <code>long</code>
fails.
*/
long getValueAsLong() throws ConfigurationException;
/**
* Returns the value of the configuration element as a
<code>String</code>.
* If the configuration value is not set, the default value will be
* used.
*
* @pre defaultValue != null
* @post getValue(defaultValue) != null
*
* @param defaultValue The default value desired.
* @return String value of the <code>Configuration</code>, or default
* if none specified.
*/
String getValue( String defaultValue );
/**
* Returns the value of the configuration element as an <code>int</code>.
* If the configuration value is not set, the default value will be
* used.
*
* @pre defaultValue != null
* @post getValueAsInt(defaultValue) != null
*
* @param defaultValue The default value desired.
* @return int value of the <code>Configuration</code>, or default
* if none specified.
*/
int getValueAsInt( int defaultValue );
/**
* Returns the value of the configuration element as a <code>long</code>.
* If the configuration value is not set, the default value will be
* used.
*
* @pre defaultValue != null
* @post getValueAsLong(defaultValue) != null
*
* @param defaultValue The default value desired.
* @return long value of the <code>Configuration</code>, or default
* if none specified.
*/
long getValueAsLong( long defaultValue );
/**
* Returns the value of the configuration element as a <code>float</code>.
* If the configuration value is not set, the default value will be
* used.
*
* @pre defaultValue != null
* @post getValueAsFloat(defaultValue) != null
*
* @param defaultValue The default value desired.
* @return float value of the <code>Configuration</code>, or default
* if none specified.
*/
float getValueAsFloat( float defaultValue );
/**
* Returns the value of the configuration element as a
<code>boolean</code>.
* If the configuration value is not set, the default value will be
* used.
*
* @pre defaultValue != null
* @post getValueAsBoolean(defaultValue) != null
*
* @param defaultValue The default value desired.
* @return boolean value of the <code>Configuration</code>, or default
* if none specified.
*/
boolean getValueAsBoolean( boolean defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* <code>String</code>, or the default value if no attribute by
* that name exists or is empty.
*
* @pre name != null
* @pre defaultValue != null
* @post getAttribute(name, defaultValue) != null
*
* @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.
*/
String getAttribute( String name, String defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* <code>int</code>, or the default value if no attribute by
* that name exists or is empty.
*
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsInt(name, defaultValue) != null
*
* @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.
*/
int getAttributeAsInt( String name, int defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* <code>long</code>, or the default value if no attribute by
* that name exists or is empty.
*
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsLong(name, defaultValue) != null
*
* @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.
*/
long getAttributeAsLong( String name, long defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* <code>float</code>, or the default value if no attribute by
* that name exists or is empty.
*
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsFloat(name, defaultValue) != null
*
* @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.
*/
float getAttributeAsFloat( String name, float defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* <code>boolean</code>, or the default value if no attribute by
* that name exists or is empty.
*
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsBoolean(name, defaultValue) != null
*
* @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.
*/
boolean getAttributeAsBoolean( String name, boolean defaultValue );
}
1.1
jakarta-avalon/src/java/org/apache/avalon/ConfigurationBuilder.java
Index: ConfigurationBuilder.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 file.
*/
package org.apache.avalon;
import java.io.IOException;
import org.xml.sax.SAXException;
/**
* The interface implemented to build configurations.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @deprecated This has been deprecated in favour of configuration interface
in org.apache.avalon.configuration interface
*/
public interface ConfigurationBuilder
{
Configuration build( String resource )
throws SAXException, IOException, ConfigurationException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/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 file.
*/
package org.apache.avalon;
/**
* Thrown when a <code>Configurable</code> component cannot be configured
* properly, or if a value cannot be retrieved properly.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @deprecated This has been deprecated in favour of configuration interface
in org.apache.avalon.configuration interface
*/
public final class ConfigurationException
extends CascadingException
{
/**
* Construct a new <code>ConfigurationException</code> instance.
*
* @param message The detail message for this exception.
*/
public ConfigurationException( final String message )
{
this( message, null );
}
/**
* Construct a new <code>ConfigurationException</code> 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, throwable );
}
}
1.1 jakarta-avalon/src/java/org/apache/avalon/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 file.
*/
package org.apache.avalon;
/**
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
*/
public interface Context
{
Object get( Object key );
}
1.1
jakarta-avalon/src/java/org/apache/avalon/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 file.
*/
package org.apache.avalon;
/**
* This inteface should be implemented by classes that need
* a Context to work. Context contains runtime generated object
* provided by the parent to this class.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
*/
public interface Contextualizable
{
/**
* Pass the Context to the contextualizable class. This method
* is always called after the constructor and, if present,
* after configure but before any other method.
*
*/
void contextualize( Context context );
}
1.1
jakarta-avalon/src/java/org/apache/avalon/DefaultComponentManager.java
Index: DefaultComponentManager.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 file.
*/
package org.apache.avalon;
import java.util.HashMap;
import java.util.Iterator;
/**
* This class is a static implementation of a ComponentManager. Allow
ineritance
* and extention so you can generate a tree of ComponentManager each defining
* Component scope.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultComponentManager
implements ComponentManager
{
protected final HashMap m_components = new HashMap();
protected final ComponentManager m_parent;
public DefaultComponentManager()
{
this( null );
}
public DefaultComponentManager( final ComponentManager parent )
{
m_parent = parent;
}
public Component lookup( final String role )
throws ComponentManagerException
{
final Component component = (Component)m_components.get( role );
if( null != component )
{
return component;
}
else if( null != m_parent )
{
return m_parent.lookup( role );
}
else
{
throw new ComponentNotFoundException("Unable to provide
implementation for " + role);
}
}
public void put( final String name, final Component component )
{
m_components.put( name, component );
}
public String toString()
{
final StringBuffer buffer = new StringBuffer();
final Iterator components = m_components.keySet().iterator();
buffer.append( "Components:" );
while( components.hasNext() )
{
buffer.append( "[" );
buffer.append( components.next() );
buffer.append( "]" );
}
return buffer.toString();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/DefaultComponentSelector.java
Index: DefaultComponentSelector.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 file.
*/
package org.apache.avalon;
import java.util.HashMap;
/**
* This is the default implementation of the ComponentSelector
*/
public class DefaultComponentSelector implements ComponentSelector {
protected final HashMap components = new HashMap();
public DefaultComponentSelector() {
// do nothing
}
/**
* Select the desired component. It does not cascade, neither
* should it.
*/
public Component select(Object hint)
throws ComponentNotFoundException,
ComponentNotAccessibleException {
final Component component = (Component) components.get(hint);
if ( component != null ) {
return component;
} else {
throw new ComponentNotFoundException("Unable to provide
implementation for " + hint.toString());
}
}
/**
* Populate the ComponentSelector.
*/
public void put(final Object hint, final Component component) {
this.components.put(hint, component);
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/DefaultConfiguration.java
Index: DefaultConfiguration.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 file.
*/
package org.apache.avalon;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
/**
* This is the default <code>Configuration</code> implementation.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @deprecated This has been deprecated in favour of configuration interface
in org.apache.avalon.configuration interface
*/
public class DefaultConfiguration
extends AbstractConfiguration
{
protected final static Iterator EMPTY_ITERATOR = (new
ArrayList(1)).iterator();
protected final String m_name;
protected final String m_location;
protected HashMap m_attributes;
protected ArrayList m_children;
protected String m_value;
/**
* Create a new <code>DefaultConfiguration</code> instance.
*/
public DefaultConfiguration( final String name, final String location )
{
m_name = name;
m_location = location;
}
/**
* Returns the name of this configuration element.
*/
public String getName()
{
return m_name;
}
/**
* Returns a description of location of element.
*/
public String getLocation()
{
return m_location;
}
/**
* Returns the value of the configuration element as a
<code>String</code>.
*
* @exception 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() + "\"" );
}
}
/**
* Returns the value of the attribute specified by its name as a
* <code>String</code>.
*
* @exception 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() + "\"" );
}
}
/**
* Return the first <code>Configuration</code> object child of this
* associated with the given name. If none exists a new one of that name
is created.
*
* @param name The name of the required child <code>Configuration</code>.
*/
public Configuration getChild( final String name )
{
if( null == m_children )
{
return new DefaultConfiguration( name, "-" );
}
else
{
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;
}
}
return new DefaultConfiguration( name, "-" );
}
}
/**
* Return an <code>Enumeration</code> of <code>Configuration</code>
objects
* children of this associated with the given name.
* <br>
* The returned <code>Enumeration</code> may be empty.
*
* @param name The name of the required children
<code>Configuration</code>.
*/
public Iterator getChildren( final String name )
{
if( null == m_children ) return EMPTY_ITERATOR;
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 children.iterator();
}
}
/**
* Append data to the value of this configuration element.
*/
public void appendValueData( final String value )
{
if( null == m_value )
{
m_value = value;
}
else
{
m_value = m_value + value;
}
}
/**
* Add an attribute to this configuration element, returning its old
* value or <b>null</b>.
*/
public String addAttribute( final String name, String value )
{
if( null == m_attributes ) m_attributes = new HashMap();
return (String) m_attributes.put( name, value );
}
/**
* Add a child <code>Configuration</code> to this configuration element.
*/
public void addChild( final Configuration configuration )
{
if( null == m_children )
{
m_children = new ArrayList();
}
m_children.add( configuration );
}
/**
* Return count of children.
*/
public int getChildCount()
{
if( null == m_children )
{
return 0;
}
return m_children.size();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/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 file.
*/
package org.apache.avalon;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* A SAXConfigurationBuilder builds configurations via SAX2 compliant parser.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @deprecated This has been deprecated in favour of configuration interface
in org.apache.avalon.configuration interface
*/
public class DefaultConfigurationBuilder
implements ConfigurationBuilder
{
protected final static String DEFAULT_PARSER =
"org.apache.xerces.parsers.SAXParser";
protected final static String PARSER =
System.getProperty("org.xml.sax.parser", DEFAULT_PARSER );
protected SAXConfigurationHandler m_handler;
protected XMLReader m_parser;
public DefaultConfigurationBuilder()
{
this( PARSER );
}
public DefaultConfigurationBuilder( final String parserClass )
{
//yaya the bugs with some compilers and final variables ..
m_handler = getHandler();
try
{
m_parser = XMLReaderFactory.createXMLReader( parserClass );
//m_parser.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
m_parser.setContentHandler( m_handler );
m_parser.setErrorHandler( m_handler );
}
catch( final SAXException se )
{
throw new Error( "Unable to setup SAX parser" + se );
}
}
protected SAXConfigurationHandler getHandler()
{
return new SAXConfigurationHandler();
}
public Configuration build( final String resource )
throws SAXException, IOException, ConfigurationException
{
final InputStream input = new FileInputStream( resource );
try { return build( input ); }
finally
{
try { input.close(); }
catch( final IOException ioe ) {}
}
}
public Configuration build( final InputStream inputStream )
throws SAXException, IOException, ConfigurationException
{
final InputSource inputSource = new InputSource( inputStream );
return build( inputSource );
}
public Configuration build( final InputSource input )
throws SAXException, IOException, ConfigurationException
{
m_handler.clear();
m_parser.parse( input );
return m_handler.getConfiguration();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/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 file.
*/
package org.apache.avalon;
import java.util.Hashtable;
import java.util.Map;
/**
* Default implementation of Context.
* This implementation is a static hierarchial store.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultContext
implements Context
{
protected final Map m_contextData;
protected final Context m_parent;
public DefaultContext( final Map contextData, final Context parent )
{
m_parent = parent;
m_contextData = contextData;
}
public DefaultContext( final Map contextData )
{
this( contextData, null );
}
public DefaultContext( final Context parent )
{
this( new Hashtable(), parent );
}
public DefaultContext()
{
this( (Context)null );
}
public Object get( final Object key )
{
final Object data = m_contextData.get( key );
if( null == m_parent || null != data )
{
return data;
}
return m_parent.get( key );
}
public void put( final Object key, final Object value )
{
m_contextData.put( key, value );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/DefaultPipeline.java
Index: DefaultPipeline.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 file.
*/
package org.apache.avalon;
import java.util.ArrayList;
import java.util.NoSuchElementException;
/**
* This is basic array based pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultPipeline
implements Pipeline
{
protected final ArrayList m_stages = new ArrayList();
/**
* Retrieve size of pipeline (number of stages).
*
* @return the size of pipeline
*/
public int getSize()
{
return m_stages.size();
}
/**
* Retrieve a particular stage of pipeline
*
* @param index the index of stage
* @return the stage
* @exception NoSuchElementException if index >= getSize() or index < 0
*/
public Stage getStage( final int index )
throws NoSuchElementException
{
return (Stage)m_stages.get( index );
}
public void addStage( final Stage stage )
{
m_stages.add( stage );
}
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Disposable.java
Index: Disposable.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 file.
*/
package org.apache.avalon;
/**
* This interface should be implemented by those classes that
* need to provide a service that requires some resources to be
* initialized before being able to operate and properly destroyed
* before termination and unloading.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Disposable
{
/**
* Destroys the service. This method is guaranteed to be called always
* after the stop() method if this class implements
<code>Stoppable</code>.
*/
void dispose()
throws Exception;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/Initializable.java
Index: Initializable.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 file.
*/
package org.apache.avalon;
/**
* This interface should be implemented by those classes that
* need to provide a service that requires some resources to be
* initialized before being able to operate.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Initializable
{
/**
* Initialize the service. This method is guaranteed to be called always
* after methods in <code>Configurable</code> and <code>Component</code>,
* if the class implements those interfaces and before the run() method
* if the class implements <code>Runnable</code>.
*/
void init()
throws Exception;
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Loggable.java
Index: Loggable.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 file.
*/
package org.apache.avalon;
import org.apache.log.Logger;
/**
* Interface through which to provide Loggers.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Loggable
{
void setLogger( Logger logger );
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Modifiable.java
Index: Modifiable.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 file.
*/
package org.apache.avalon;
/**
* This interface is implemented by those classes that change
* their behavior/results over time (non-ergodic).
*
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
*/
public interface Modifiable
{
/**
* Queries the class to estimate its ergodic period termination.
* <br>
* This method is called to ensure the validity of a cached product. It
* is the class responsibility to provide the fastest possible
* implementation of this method or, whether this is not possible and the
* costs of the change evaluation is comparable to the production costs,
* to return <b>true</b> directly with no further delay, thus reducing
* the evaluation overhead to a minimum.
*
* @return <b>true</b> if the class ergodic period is over and the class
* would behave differently if processed again, <b>false</b> if
the
* resource is still ergodic so that it doesn't require
* reprocessing.
*/
boolean modifiedSince( long date );
}
1.1 jakarta-avalon/src/java/org/apache/avalon/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 file.
*/
package org.apache.avalon;
import java.util.Iterator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import org.apache.avalon.Configuration;
import org.apache.avalon.ConfigurationException;
/**
*
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
*/
public final class Parameters
{
protected HashMap m_parameters;
/**
* Create a new <code>Parameters</code> instance.
*/
public Parameters()
{
m_parameters = new HashMap();
}
/**
* Set the <code>String</code> value of a specified parameter.
* <p />
* If the specified value is <b>null</b> the parameter is removed.
*
* @return The previous value of the parameter or <b>null</b>.
*/
public String setParameter( final String name, final String value )
{
if( null == name )
{
return null;
}
if( null == value )
{
return (String)m_parameters.remove( name );
}
return (String)m_parameters.put( name, value );
}
/**
* Return an <code>Enumeration</code> view of all parameter names.
*/
public Iterator getParameterNames()
{
return m_parameters.keySet().iterator();
}
/**
* Check if the specified parameter can be retrieved.
*/
public boolean isParameter( final String name )
{
return m_parameters.containsKey( name );
}
/**
* Retrieve the <code>String</code> value of the specified parameter.
* <p />
* If the specified parameter cannot be found, <b>null</b> is returned.
*/
protected String getParameter( final String name )
{
if( null == name )
{
return null;
}
return (String)m_parameters.get( name );
}
/**
* Retrieve the <code>String</code> value of the specified parameter.
* <p />
* If the specified parameter cannot be found, <code>defaultValue</code>
* is returned.
*/
public String getParameter( final String name, final String defaultValue )
{
final String value = getParameter( name );
if( null == value )
{
return defaultValue;
}
else
{
return value;
}
}
/**
* Retrieve the <code>int</code> value of the specified parameter.
* <p />
* If the specified parameter cannot be found, <code>defaultValue</code>
* is returned.
*/
public int getParameterAsInteger( final String name, final int
defaultValue )
{
final String value = getParameter( name );
if( null == value )
{
return defaultValue;
}
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 NumberFormatException nfe )
{
return defaultValue;
}
}
/**
* Retrieve the <code>long</code> value of the specified parameter.
* <p />
* If the specified parameter cannot be found, <code>defaultValue</code>
* is returned.
*/
public long getParameterAsLong( final String name, final long
defaultValue )
{
final String value = getParameter( name );
if( null == value )
{
return defaultValue;
}
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 NumberFormatException nfe )
{
return defaultValue;
}
}
/**
* Retrieve the <code>float</code> value of the specified parameter.
* <p />
* If the specified parameter cannot be found, <code>defaultValue</code>
* is returned.
*/
public float getParameterAsFloat( final String name, final float
defaultValue )
{
final String value = getParameter( name );
if( null == value )
{
return defaultValue;
}
try
{
return Float.parseFloat(value);
}
catch( final NumberFormatException nfe )
{
return defaultValue;
}
}
/**
* Retrieve the <code>boolean</code> value of the specified parameter.
* <p />
* If the specified parameter cannot be found, <code>defaultValue</code>
* is returned.
*/
public boolean getParameterAsBoolean( final String name, final boolean
defaultValue )
{
final String value = getParameter( name );
if( null == value )
{
return defaultValue;
}
if( value.equalsIgnoreCase("true") )
{
return true;
}
if( value.equalsIgnoreCase("false") )
{
return(false);
}
return defaultValue;
}
/**
* Merge parameters from another <code>Parameters</code> instance
* into this.
*
* @return This <code>Parameters</code> instance.
*/
public Parameters merge( final Parameters other )
{
final Iterator names = other.getParameterNames();
while( names.hasNext() )
{
final String name = (String) names.next();
final String value = other.getParameter( name );
setParameter( name, value );
}
return this;
}
/**
* Create a <code>Parameters</code> object from a
<code>Configuration</code>
* object.
*/
public static Parameters fromConfiguration( final Configuration
configuration )
throws ConfigurationException
{
if( null == configuration )
{
throw new ConfigurationException( "You cannot convert to
parameters with " +
"a null Configuration");
}
final Iterator parameters = configuration.getChildren("parameter");
final Parameters param = new Parameters();
while( parameters.hasNext() )
{
try {
final Configuration child =(Configuration) parameters.next();
final String name = child.getAttribute("name");
final String value = child.getAttribute("value");
param.setParameter( name, value );
} catch (ClassCastException cce) {
// ignore this. Temporary work around until the Iterator
// is guaranteed to return Configuration values.
Unfortunately
// there are problems with empty strings getting in there.
} catch (Exception e) {
throw new ConfigurationException("Cannot process
Configurable", e);
}
}
return param;
}
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Pipeline.java
Index: Pipeline.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 file.
*/
package org.apache.avalon;
import java.util.NoSuchElementException;
/**
* This represents a pipeline made up of stages.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Pipeline
extends Stage
{
/**
* Retrieve size of pipeline (number of stages).
*
* @return the size of pipeline
*/
int getSize();
/**
* Retrieve a particular stage of pipeline
*
* @param index the index of stage
* @return the stage
* @exception NoSuchElementException if index >= getSize() or index < 0
*/
Stage getStage( int index )
throws NoSuchElementException;
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Poolable.java
Index: Poolable.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 file.
*/
package org.apache.avalon;
/**
* Poolable marker interface.
*
* Components implement this interface if it is reasonable to
* Pool the object. Components that don't implement this interface
* will be created anew via a factory.
*
* NB: It was a deliberat e choice not to extend Component. This will have to
* be reassed once we see it in action.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Poolable
{
}
1.1
jakarta-avalon/src/java/org/apache/avalon/ProcessorPipeline.java
Index: ProcessorPipeline.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 file.
*/
package org.apache.avalon;
import java.util.Iterator;
/**
* This represents a pipeline made up of stages.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class ProcessorPipeline
extends DefaultPipeline
implements ProcessorStage
{
public void process( final Object object )
{
final Iterator stages = m_stages.iterator();
while( stages.hasNext() )
{
((ProcessorStage)stages.next()).process( object );
}
}
public Stage getStage( final int index )
{
return (Stage)m_stages.get( index );
}
public int getSize()
{
return m_stages.size();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/ProcessorStage.java
Index: ProcessorStage.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 file.
*/
package org.apache.avalon;
/**
* This represents a stage in a pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
*/
public interface ProcessorStage
extends Stage
{
void process( Object object );
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Recomposer.java
Index: Recomposer.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 file.
*/
package org.apache.avalon;
/**
* Extends composer to allow recomposing.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Recomposer
extends Composer
{
void recompose( ComponentManager componentManager )
throws ComponentNotAccessibleException, ComponentNotFoundException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/Reconfigurable.java
Index: Reconfigurable.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 file.
*/
package org.apache.avalon;
/**
* Extends Configurable to allow reconfiguration runtime.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="http://java.apache.org/">Java Apache Project</a>
*/
public interface Reconfigurable
extends Configurable
{
void reconfigure( Configuration configuration ) throws
ConfigurationException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/Recontextualizable.java
Index: Recontextualizable.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 file.
*/
package org.apache.avalon;
/**
* Extends composer to allow recontextualizing.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Recontextualizable
extends Composer
{
void recontextualizable( Context context ) ;
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Recyclable.java
Index: Recyclable.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 file.
*/
package org.apache.avalon;
/**
* This interface standardizes the behaviour of a recyclable object.
* A recyclable object is defined as an object that can be used to
* encapsulate another object without being altered by its content.
* Therefore, a recyclable object may be recycled and reused many times.
*
* This is helpful in cases where recyclable objects are continously
* created and destroied, causing a much greater amount of garbage to
* be collected by the JVM garbage collector. By making it recyclable,
* it is possible to reduce the GC execution time thus incrementing the
* overall performance of a process and decrementing the chance of
* memory overflow.
*
* Every implementation must provide their own method to allow this
* recyclable object to be reused by setting its content.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Recyclable
extends Poolable
{
/**
* This method should be implemented to remove all costly resources
* in object. These resources can be object references, database
connections,
* threads etc. What is categorised as "costly" resources is determined on
* a case by case analysis.
*/
void recycle();
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Resolvable.java
Index: Resolvable.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 file.
*/
package org.apache.avalon;
/**
* This interface is used to indicate objects that need to be
* resolved in some particular context.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Resolvable
{
/**
* Resolve a object to a value.
*
* @param context the contextwith respect which to resolve
* @return the resolved object
*/
Object resolve( Context context );
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Resumable.java
Index: Resumable.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 file.
*/
package org.apache.avalon;
/**
* This is used to restart execturion after temporarily halt.
* The halt may have been for some re- configuring|composing|contextualizing
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Resumable
{
/**
* Resumes the component.
*/
void resume();
}
1.1
jakarta-avalon/src/java/org/apache/avalon/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 file.
*/
package org.apache.avalon;
import java.io.IOException;
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;
/**
* A SAXConfigurationHandler helps build Configurations out of sax events.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @deprecated This has been deprecated in favour of configuration interface
in org.apache.avalon.configuration interface
*/
public class SAXConfigurationHandler
extends DefaultHandler
implements ErrorHandler
{
protected final ArrayList m_elements = new
ArrayList();
protected Configuration m_configuration;
protected Locator m_locator;
public Configuration getConfiguration()
{
return m_configuration;
}
public void clear()
{
m_elements.clear();
m_locator = null;
}
public void setDocumentLocator( final Locator locator )
{
m_locator = locator;
}
public void characters( final char[] ch, int start, int end )
throws SAXException
{
final 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() );
}
configuration.appendValueData( value );
}
public void endElement( final String namespaceURI,
final String localName,
final String rawName )
{
final int location = m_elements.size() - 1;
final Object object = m_elements.remove( location );
if( 0 == location )
{
m_configuration = (Configuration)object;
}
}
protected DefaultConfiguration createConfiguration( final String
localName,
final String location
)
{
return new DefaultConfiguration( localName, location );
}
public void startElement( final String namespaceURI,
final String localName,
final String rawName,
final Attributes attributes )
throws SAXException
{
final DefaultConfiguration configuration =
createConfiguration( localName, 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.addAttribute( name, value );
}
}
/**
* This just throws an exception on a parse error.
*/
public void error( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
*/
public void warning( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
*/
public void fatalError( final SAXParseException exception )
throws SAXException
{
throw exception;
}
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/java/org/apache/avalon/SingleThreaded.java
Index: SingleThreaded.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 file.
*/
package org.apache.avalon;
/**
* A interface to mark a component as not ThreadSafe.
*
* NB: It was a deliberat e choice not to extend Component. This will have to
* be reassed once we see it in action.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface SingleThreaded
{
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Stage.java
Index: Stage.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 file.
*/
package org.apache.avalon;
/**
* This represents a stage in a pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
*/
public interface Stage
extends Component
{
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Startable.java
Index: Startable.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 file.
*/
package org.apache.avalon;
/**
* This interface is the dual interface of Stoppable.
*
* It provides a method through which components can be "started"
* without requiring a thread. Useful for reactive or passive objects.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Startable
{
/**
* Starts the component.
*/
void start()
throws Exception;
}
1.1 jakarta-avalon/src/java/org/apache/avalon/Stoppable.java
Index: Stoppable.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 file.
*/
package org.apache.avalon;
/**
* This interface is the dual interface of the <code>java.lang.Runnable</code>
* interface and provides a hook to safely stop the thread of execution.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
*/
public interface Stoppable
{
/**
* Stops the current thread of execution.
*/
void stop()
throws Exception;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/Suspendable.java
Index: Suspendable.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 file.
*/
package org.apache.avalon;
/**
* This is used to temporarily halt execution of a component.
* The execution may be halted so that you can reconfigure/
* recompose/recontextualize component
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Suspendable
{
/**
* Suspends the component.
*/
void suspend();
}
1.1 jakarta-avalon/src/java/org/apache/avalon/ThreadSafe.java
Index: ThreadSafe.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 file.
*/
package org.apache.avalon;
/**
* A interface to mark a component as ThreadSafe or reentrant.
*
* NB: It was a deliberat e choice not to extend Component. This will have to
* be reassed once we see it in action.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface ThreadSafe
{
}
1.1
jakarta-avalon/src/java/org/apache/avalon/atlantis/AbstractKernel.java
Index: AbstractKernel.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 file.
*/
package org.apache.avalon.atlantis;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import org.apache.avalon.AbstractLoggable;
import org.apache.avalon.Component;
import org.apache.avalon.ComponentManager;
import org.apache.avalon.Context;
import org.apache.avalon.DefaultComponentManager;
import org.apache.avalon.DefaultContext;
import org.apache.avalon.camelot.AbstractContainer;
import org.apache.avalon.camelot.Container;
import org.apache.avalon.camelot.Entry;
import org.apache.avalon.camelot.ContainerException;
import org.apache.avalon.camelot.FactoryException;
import org.apache.avalon.camelot.Locator;
import org.apache.log.LogKit;
/**
* This is the basic Kernel that supports functionality most kernels need.
* It builds a DAG of blocks, can load/unload/reload blocks, can
* configure/reconfigure blocks, can start/stop/initialize blocks, provide
* contexts for blocks etc.
*
* When extending this the developer must set the value of m_entryClass and
m_applicationClass.
* ie.
* m_entryClass = ServerApplicationEntry.class;
* m_applicationClass = ServerApplication.class;
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class AbstractKernel
extends AbstractContainer
implements Kernel
{
protected boolean m_initialised = false;
protected boolean m_running = false;
protected Class m_applicationClass;
public void init()
throws Exception
{
final Iterator names = list();
while( names.hasNext() )
{
final String name = (String)names.next();
final Entry entry = getEntry( name );
initializeEntry( name, entry );
}
}
public void start()
throws Exception
{
final Iterator names = list();
while( names.hasNext() )
{
final String name = (String)names.next();
final Entry entry = getEntry( name );
startEntry( name, entry );
}
}
public void run()
{
m_running = true;
while( m_running )
{
try { synchronized( this ) { wait(); } }
catch (InterruptedException e) {}
}
}
public void stop()
throws Exception
{
m_running = false;
synchronized( this ) { notifyAll(); }
final Iterator names = list();
while( names.hasNext() )
{
final String name = (String)names.next();
final Entry entry = getEntry( name );
stopEntry( name, entry );
}
}
public void dispose()
throws Exception
{
m_initialised = false;
final Iterator names = list();
while( names.hasNext() )
{
final String name = (String)names.next();
final Entry entry = getEntry( name );
disposeEntry( name, entry );
}
}
/**
* Retrieve Application from container.
* The Application that is returned must be initialized
* and prepared for manipulation.
*
* @param name the name of application
* @return the application
* @exception ContainerException if an error occurs
*/
public Application getApplication( String name )
throws ContainerException
{
final Entry entry = getEntry( name );
try { initializeEntry( name, entry ); }
catch( final Exception e )
{
throw new ContainerException( "Error prepareing entry", e );
}
return (Application)entry.getInstance();
}
protected void initializeEntry( final String name, final Entry entry )
throws Exception
{
Application application = (Application)entry.getInstance();
if( null == application )
{
preInitializeEntry( name, entry );
application = createApplicationFor( name, entry );
entry.setInstance( application );
prepareApplication( name, entry, application );
application.init();
postInitializeEntry( name, entry );
}
}
protected void startEntry( final String name, final Entry entry )
throws Exception
{
final Application application = (Application)entry.getInstance();
if( null != application )
{
application.start();
}
else
{
getLogger().warn( "Failed to start application " + name +
" as it is not initialized" );
}
}
protected void stopEntry( final String name, final Entry entry )
throws Exception
{
final Application application = (Application)entry.getInstance();
if( null != application )
{
application.stop();
}
else
{
getLogger().warn( "Failed to stop application " + name +
" as it is not initialized/started" );
}
}
protected void disposeEntry( final String name, final Entry entry )
throws Exception
{
Application application = (Application)entry.getInstance();
if( null != application )
{
preDisposeEntry( name, entry );
entry.setInstance( null );
application.dispose();
postDisposeEntry( name, entry );
}
}
/**
* This method is called before an entry is initialized.
* Overide to do something.
*
* @param name the name of the entry
* @param entry the entry
* @exception Exception if an error occurs
*/
protected void preInitializeEntry( final String name, final Entry entry )
throws Exception
{
}
/**
* This method is called after an entry is initialized.
* Overide to do something.
*
* @param name the name of the entry
* @param entry the entry
* @exception Exception if an error occurs
*/
protected void postInitializeEntry( final String name, final Entry entry )
throws Exception
{
}
/**
* This method is called before an entry is disposed.
* Overide to do something.
*
* @param name the name of the entry
* @param entry the entry
* @exception Exception if an error occurs
*/
protected void preDisposeEntry( final String name, final Entry entry )
throws Exception
{
}
/**
* This method is called after an entry is disposed.
* Overide to do something.
*
* @param name the name of the entry
* @param entry the entry
* @exception Exception if an error occurs
*/
protected void postDisposeEntry( final String name, final Entry entry )
throws Exception
{
}
/**
* Prepare an application before it is initialized.
* Overide to provide functionality.
* Usually used to setLogger(), contextualize, compose, configure.
*
* @param name the name of application
* @param entry the application entry
* @param application the application instance
* @exception Exception if an error occurs
*/
protected void prepareApplication( final String name,
final Entry entry,
final Application application )
throws Exception
{
}
protected Application createApplicationFor( final String name, final
Entry entry )
throws Exception
{
final Application application = newApplication( name, entry );
if( !m_applicationClass.isInstance( application ) )
{
throw new IllegalArgumentException( "Created an application that
is not " +
"of type " +
m_applicationClass.getName() +
" but of type " +
application.getClass().getName() );
}
return application;
}
protected Application newApplication( final String name, final Entry
entry )
throws Exception
{
return (Application)m_applicationClass.newInstance();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/atlantis/Application.java
Index: Application.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 file.
*/
package org.apache.avalon.atlantis;
import org.apache.avalon.Disposable;
import org.apache.avalon.Initializable;
import org.apache.avalon.Startable;
import org.apache.avalon.Stoppable;
import org.apache.avalon.camelot.Container;
/**
* The Application is a self-contained component that performs a specific
* function.
*
* Example ServerApplications may be a Mail Server, File Server, Directory
Server etc.
* Example JesktopApplications may be a Spreadsheet program, browser, mail
client
* Example WebApplications may be a particular website or application within
a website
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Application
extends Initializable, Startable, Stoppable, Disposable, Container
{
}
1.1
jakarta-avalon/src/java/org/apache/avalon/atlantis/ApplicationException.java
Index: ApplicationException.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 file.
*/
package org.apache.avalon.atlantis;
import org.apache.avalon.CascadingException;
/**
* The ApplicationException used to indicate problems with applications.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class ApplicationException
extends CascadingException
{
public ApplicationException( final String message )
{
this( message, null );
}
public ApplicationException( final String message, final Throwable
throwable )
{
super( message, throwable );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/atlantis/Facility.java
Index: Facility.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 file.
*/
package org.apache.avalon.atlantis;
import org.apache.avalon.Component;
/**
* A Facility is a horizontal cut through the kernel.
* Unlike Components which offer a Service/Content interface, Facilitys
* are used to facilitate the non-Service/Form interface or life-cycle
orientated
* methods of Components. See documentation for a clearer explanation.
*
* Example Facilities would be
* <ul>
* <li>ConfigurationRepository that stores configuration data for
components</li>
* <li>ThreadFacility that allows components to run in threads</li>
* <li>ContextUtility that builds context information for components</li>
* <li>ExportFacility that exports components to external users (perhaps
via RMI)</li>
* <li>NamingFacility that binds compoents to a name in a directory</li>
* <li>ManagementFacility that manages components via JMX</li>
* </ul>
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Facility
extends Component
{
}
1.1
jakarta-avalon/src/java/org/apache/avalon/atlantis/Kernel.java
Index: Kernel.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 file.
*/
package org.apache.avalon.atlantis;
import org.apache.avalon.camelot.ContainerException;
/**
* The Kernel is the core of any system.
* The kernel is responsible for orchestrating low level services
* such as loading, configuring and destroying applications. It also
* gives access to basic facilities specific to that particular kernel.
* A ServerKernel may offer scheduling, naming, security, classloading etc.
* A JesktopKernel may offer inter-application drag-n-drop support.
* A VEKernel may offer inter-VE transport for Avatars.
*
* Note that no facilities are available until after the Kernel has been
initialized.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Kernel
extends Application, Runnable
{
/**
* Retrieve Application from container.
* The Application that is returned must be initialized
* and prepared for manipulation.
*
* @param name the name of application
* @return the application
* @exception ContainerException if an error occurs
*/
Application getApplication( String name )
throws ContainerException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/blocks/AbstractBlock.java
Index: AbstractBlock.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 file.
*/
package org.apache.avalon.blocks;
/**
* This is an <code>AbstractBlock</code> that makes deployment a bit
* easier.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @version CVS $Revision: 1.1 $ $Date: 2001/02/23 10:47:36 $
* @deprecated This is deprecated in favour of directly extending the class
in atlantis package
*/
public abstract class AbstractBlock {
}
1.1
jakarta-avalon/src/java/org/apache/avalon/blocks/Block.java
Index: Block.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 file.
*/
package org.apache.avalon.blocks;
/**
* The main interface to implement for building servers using Avalon patterns.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @deprecated This is deprecated in favour of directly extending the
interface in atlantis package
*/
public interface Block {
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/AbstractCamelotDeployer.java
Index: AbstractCamelotDeployer.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 file.
*/
package org.apache.avalon.camelot;
import java.net.URL;
import org.apache.avalon.ComponentManager;
import org.apache.avalon.ComponentManagerException;
import org.apache.avalon.ComponentNotFoundException;
import org.apache.avalon.Composer;
/**
* This class deploys resources from camelot based system.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class AbstractCamelotDeployer
extends AbstractDeployer
implements Composer
{
protected boolean m_deployToContainer;
protected boolean m_deployToLocatorRegistry;
protected boolean m_deployToInfoRegistry;
protected LocatorRegistry m_locatorRegistry;
protected Container m_container;
protected Registry m_infoRegistry;
/**
* Retrieve relevent services needed to deploy.
*
* @param componentManager the ComponentManager
* @exception ComponentNotFoundException if an error occurs
* @exception ComponentNotAccessibleException if an error occurs
*/
public void compose( final ComponentManager componentManager )
throws ComponentManagerException
{
if( m_deployToLocatorRegistry )
{
m_locatorRegistry = (LocatorRegistry)componentManager.
lookup( "org.apache.avalon.camelot.LocatorRegistry" );
}
if( m_deployToInfoRegistry )
{
m_infoRegistry = (Registry)componentManager.
lookup( "org.apache.avalon.camelot.Registry" );
}
if( m_deployToContainer )
{
m_container = (Container)componentManager.
lookup( "org.apache.avalon.camelot.Container" );
}
}
protected void addEntry( final String name, final Entry entry )
throws DeploymentException
{
try { m_container.add( name, entry ); }
catch( final ContainerException ce )
{
throw new DeploymentException( "Error adding component to
container", ce );
}
getLogger().debug( "Adding " + m_type + "Entry " + name + " as " +
entry );
}
protected void addLocator( final String name, final String classname,
final URL url )
throws DeploymentException
{
final DefaultLocator locator = new DefaultLocator( classname, url );
try { m_locatorRegistry.register( name, locator ); }
catch( final RegistryException re )
{
throw new DeploymentException( "Error registering " + name + "
due to " + re,
re );
}
getLogger().debug( "Registered " + m_type + " " + name + " as " +
classname );
}
protected void addInfo( final String name, final Info info )
throws DeploymentException
{
try { m_infoRegistry.register( name, info ); }
catch( final RegistryException re )
{
throw new DeploymentException( "Error registering " + name + "
due to " + re,
re );
}
getLogger().debug( "Registered Info " + m_type + " " + name );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/AbstractContainer.java
Index: AbstractContainer.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 file.
*/
package org.apache.avalon.camelot;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.avalon.AbstractLoggable;
import org.apache.avalon.Component;
/**
* This contains it during execution and may provide certain
* facilities (like a thread per EJB etc).
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class AbstractContainer
extends AbstractLoggable
implements Container
{
protected final HashMap m_entries = new HashMap();
protected Class m_entryClass;
/**
* Add a component instance to container.
*
* @param entry the component entry
*/
public void add( final String name, final Entry entry )
throws ContainerException
{
checkEntry( name, entry );
preAdd( name, entry );
m_entries.put( name, entry );
postAdd( name, entry );
}
/**
* Remove a component instance from container.
*
* @param name the name of component
*/
public void remove( final String name )
throws ContainerException
{
final Entry entry = (Entry)m_entries.get( name );
if( null == entry )
{
throw new ContainerException( "Component named " + name + " not
contained" );
}
preRemove( name, entry );
m_entries.remove( name );
postRemove( name, entry );
}
/**
* Retrieve Entry from container
*
* @param name the name of entry
* @return the entry
*/
public Entry getEntry( final String name )
throws ContainerException
{
final Entry entry = (Entry)m_entries.get( name );
if( null == entry )
{
throw new ContainerException( "Name " + name + " not contained" );
}
else
{
return entry;
}
}
/**
* List all names of entries in container.
*
* @return the list of all entries
*/
public Iterator list()
{
return m_entries.keySet().iterator();
}
/**
* This method is called before entry is added to give chance for
* sub-class to veto removal.
*
* @param name the name of entry
* @param entry the entry
* @exception ContainerException to stop removal of entry
*/
protected void preAdd( final String name, final Entry entry )
throws ContainerException
{
}
/**
* This method is called after entry is added to give chance for
* sub-class to do some cleanup.
*
* @param name the name of entry
* @param entry the entry
*/
protected void postAdd( final String name, final Entry entry )
{
}
/**
* This method is called before entry is removed to give chance for
* sub-class to veto removal.
*
* @param name the name of entry
* @param entry the entry
* @exception ContainerException to stop removal of entry
*/
protected void preRemove( final String name, final Entry entry )
throws ContainerException
{
}
/**
* This method is called after entry is removed to give chance for
* sub-class to do some cleanup.
*
* @param name the name of entry
* @param entry the entry
*/
protected void postRemove( final String name, final Entry entry )
{
}
/**
* List all entries in container.
*
* @return the list of all entries
*/
protected Iterator listEntries()
{
return m_entries.values().iterator();
}
protected void checkEntry( final String name, final Entry entry )
throws ContainerException
{
if( null != m_entries.get( name ) )
{
throw new ContainerException( "Can not add component to container
because " +
"entry already exists with name " +
name );
}
if( !isValidName( name ) )
{
throw new ContainerException( "Can not add component to container
because " +
"invalid name " + name );
}
if( !isValidEntry( entry ) )
{
throw new ContainerException( "Can not add component to container
because " +
"invalid entry for " + name );
}
if( !m_entryClass.isAssignableFrom( entry.getClass() ) )
{
throw new ContainerException( "Only Entries of type " +
m_entryClass.getName() +
" may be placed in container." );
}
}
protected boolean isValidName( final String name )
throws ContainerException
{
return true;
}
protected boolean isValidEntry( final Entry entry )
throws ContainerException
{
return true;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/AbstractDeployer.java
Index: AbstractDeployer.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 file.
*/
package org.apache.avalon.camelot;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import org.apache.avalon.AbstractLoggable;
import org.apache.avalon.Component;
import org.apache.avalon.ComponentNotFoundException;
import org.apache.avalon.util.io.FileUtil;
import org.apache.log.Logger;
/**
* A Deployer is responsible for taking a URL (ie a jar/war/ear) and deploying
* it to a particular "location". "location" means different things for
* different containers. For a servlet container it may mean the place to
* mount servlet (ie /myapp --> /myapp/Cocoon.xml is mapping cocoon servlet to
* /myapp context).
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class AbstractDeployer
extends AbstractLoggable
implements Deployer
{
protected final HashMap m_deployments = new HashMap();
protected boolean m_autoUndeploy;
protected String m_type;
public void deploy( final String location, final URL url )
throws DeploymentException
{
checkDeployment( location, url );
final File file = getFileFor( url );
getLogger().info( "Deploying " + m_type + " file (" + file + ") as "
+ location );
deployFromFile( location, file );
}
protected void checkDeployment( final String location, final URL url )
throws DeploymentException
{
if( null != m_deployments.get( location ) )
{
throw new DeploymentException( m_type + " already exists at " +
location );
}
if( !isValidLocation( location ) )
{
throw new DeploymentException( "Invalid location (" + location +
") for " + m_type );
}
}
public void undeploy( final String location )
throws DeploymentException
{
final Component component = (Component)m_deployments.get( location );
if( null == component )
{
throw new DeploymentException( m_type + " does not exist at " +
location );
}
final boolean canUndeploy = canUndeploy( component );
if( !canUndeploy )
{
if( !m_autoUndeploy )
{
//we are midstream but not allowed to automagically undeploy
.. therefore
throw new DeploymentException( m_type + " not ready to
undeploy at " +
location );
}
else
{
shutdownDeployment( component );
}
}
//if everything has gone successful then remove application
m_deployments.remove( location );
}
protected File getCacheLocationFor( final URL url )
throws DeploymentException
{
throw new DeploymentException( "Unable to deploy non-local resources"
);
}
protected File getFileFor( final URL url )
throws DeploymentException
{
File file = null;
if( url.getProtocol().equals( "file" ) )
{
file = new File( url.getFile() );
}
else
{
file = getCacheLocationFor( url );
try { FileUtil.copyURLToFile( url, file ); }
catch( final IOException ioe )
{
throw new DeploymentException( "Failed attempting to copy
from " + url +
" to local file cache " +
file, ioe );
}
}
file = file.getAbsoluteFile();
if( !file.exists() )
{
throw new DeploymentException( "Could not find application
archive at " +
file );
}
if( file.isDirectory() )
{
throw new DeploymentException( "Could not find application
archive at " +
file + " as it is a directory." );
}
return file;
}
protected boolean isValidLocation( String location )
{
return true;
}
protected boolean canUndeploy( Component component )
throws DeploymentException
{
return true;
}
protected void shutdownDeployment( Component component )
throws DeploymentException
{
}
protected abstract void deployFromFile( String location, File file )
throws DeploymentException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/AbstractZipDeployer.java
Index: AbstractZipDeployer.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 file.
*/
package org.apache.avalon.camelot;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.ZipFile;
import org.apache.avalon.Composer;
/**
* This class deploys a .zip file into a registry.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class AbstractZipDeployer
extends AbstractCamelotDeployer
implements Composer
{
/**
* Deploy a file.
* Eventually this should be cached for performance reasons.
*
* @param location the location
* @param file the file
* @exception DeploymentException if an error occurs
*/
protected void deployFromFile( final String location, final File file )
throws DeploymentException
{
final ZipFile zipFile = DeployerUtil.getZipFileFor( file );
URL url = null;
try
{
try { url = file.toURL(); }
catch( final MalformedURLException mue )
{
throw new DeploymentException( "Unable to form url", mue );
}
loadResources( zipFile, location, url );
}
finally
{
try { zipFile.close(); }
catch( final IOException ioe ) {}
}
}
/**
* Overide this method to provide the actual functionality and
* deploy the resources from a zip file.
*
* @param zipFile the ZipFile
* @param location the location that it was deployed to
* @param url the url of deployment
* @exception DeploymentException if an error occurs
*/
protected abstract void loadResources( ZipFile zipFile, String location,
URL url )
throws DeploymentException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/AvalonState.java
Index: AvalonState.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 file.
*/
package org.apache.avalon.camelot;
public final class AvalonState
extends State
{
public final static AvalonState ERROR = new AvalonState(
"ERROR", -10 );
public final static AvalonState BASE = new AvalonState( "BASE",
0 );
public final static AvalonState CREATED = new AvalonState(
"CREATED", 5 );
public final static AvalonState LOGGED = new AvalonState(
"LOGGED", 10 );
public final static AvalonState CONTEXTUALIZED = new AvalonState(
"CONTEXTUALIZED", 20 );
public final static AvalonState COMPOSED = new AvalonState(
"COMPOSED", 30 );
public final static AvalonState CONFIGURED = new AvalonState(
"CONFIGURED", 40 );
public final static AvalonState NAMED = new AvalonState(
"NAMED", 50 );
public final static AvalonState INITIALIZED = new AvalonState(
"INITIALIZED", 60 );
public final static AvalonState STARTED = new AvalonState(
"STARTED", 70 );
public final static AvalonState RUNNING = new AvalonState(
"RUNNING", 70 );
//from here to stopped may want to go to a different class ??
public final static AvalonState EXPORTED = new AvalonState(
"EXPORTED", 80 );
public final static AvalonState UNEXPORTED = new AvalonState(
"UNEXPORTED", 90 );
public final static AvalonState SUSPENDED = new AvalonState(
"SUSPENDED", 100 );
public final static AvalonState RESUMED = new AvalonState(
"RESUMED", 110 );
public final static AvalonState STOPPED = new AvalonState(
"STOPPED", 120 );
public final static AvalonState DISPOSED = new AvalonState(
"DISPOSED", 130 );
public final static AvalonState FINALIZED = new AvalonState(
"FINALIZED", 140 );
protected AvalonState( final String name, final int value )
{
super( name, value );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/CamelotUtil.java
Index: CamelotUtil.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 file.
*/
package org.apache.avalon.camelot;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;
import org.apache.avalon.Component;
import org.apache.avalon.util.io.ExtensionFileFilter;
/**
* Utility methods for Camelot related facilities.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class CamelotUtil
{
/**
* Private constructor so impossible to instantiate.
*/
private CamelotUtil()
{
}
public static void deployFromDirectory( final Deployer deployer,
final File directory,
final String extention )
throws DeploymentException
{
deployFromDirectory( deployer, directory, new String[] { extention }
);
}
public static void deployFromDirectory( final Deployer deployer,
final File directory,
final String[] extentions )
throws DeploymentException
{
final ExtensionFileFilter filter = new ExtensionFileFilter(
extentions );
final File[] files = directory.listFiles( filter );
if( null != files )
{
deployFiles( deployer, files );
}
}
public static void deployFiles( final Deployer deployer, final File[]
files )
throws DeploymentException
{
for( int i = 0; i < files.length; i++ )
{
final String filename = files[ i ].getName();
int index = filename.lastIndexOf( '.' );
if( -1 == index ) index = filename.length();
final String name = filename.substring( 0, index );
try
{
final File file = files[ i ].getCanonicalFile();
deployer.deploy( name, file.toURL() );
}
catch( final MalformedURLException mue )
{
throw new DeploymentException( "Malformed URL for " + files[
i ], mue );
}
catch( final IOException ioe )
{
throw new DeploymentException( "Unable to get canonical
representation " +
"for file " + files[ i ], ioe
);
}
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/ComponentBuilder.java
Index: ComponentBuilder.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.Component;
import org.apache.avalon.ComponentManager;
import org.apache.avalon.ComponentManagerException;
/**
* Component responsible for building componentManager information for entry.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface ComponentBuilder
extends Component
{
Object createComponent( String name, Entry entry )
throws Exception;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/ComponentManagerBuilder.java
Index: ComponentManagerBuilder.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.Component;
import org.apache.avalon.ComponentManager;
import org.apache.avalon.ComponentManagerException;
/**
* Component responsible for building componentManager information for entry.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface ComponentManagerBuilder
extends Component
{
ComponentManager createComponentManager( String name, Entry entry )
throws ComponentManagerException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/ConfigurationRepository.java
Index: ConfigurationRepository.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.Component;
import org.apache.avalon.configuration.Configuration;
import org.apache.avalon.configuration.ConfigurationException;
/**
* Repository from which all configuration data is retrieved.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface ConfigurationRepository
extends Component
{
Configuration getConfiguration( String name, Entry entry )
throws ConfigurationException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/Container.java
Index: Container.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 file.
*/
package org.apache.avalon.camelot;
import java.util.Iterator;
import org.apache.avalon.Component;
/**
* This contains it during execution and may provide certain
* facilities (like a thread per EJB etc).
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Container
extends Component
{
/**
* Add a component instance to container.
*
* @param entry the component entry
*/
void add( String name, Entry entry )
throws ContainerException;
/**
* Remove a component instance from container.
*
* @param name the name of component
*/
void remove( String name )
throws ContainerException;
/**
* Retrieve Entry from container
*
* @param name the name of entry
* @return the entry
*/
Entry getEntry( String name )
throws ContainerException;
/**
* List all names of entries in container.
*
* @return the list of all entries
*/
Iterator list();
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/ContainerException.java
Index: ContainerException.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.CascadingException;
/**
* Exception to indicate error manipulating container.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class ContainerException
extends CascadingException
{
/**
* Construct a new <code>ContainerException</code> instance.
*
* @param message The detail message for this exception.
*/
public ContainerException( final String message )
{
this( message, null );
}
/**
* Construct a new <code>ContainerException</code> instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public ContainerException( final String message, final Throwable
throwable )
{
super( message, throwable );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/ContextBuilder.java
Index: ContextBuilder.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.Component;
import org.apache.avalon.Context;
/**
* Component responsible for building context information for entry.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface ContextBuilder
extends Component
{
Context createContext( String name, Entry entry );
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/DefaultFactory.java
Index: DefaultFactory.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 file.
*/
package org.apache.avalon.camelot;
import java.net.URL;
import java.util.HashMap;
import org.apache.avalon.Component;
import org.apache.avalon.AbstractLoggable;
/**
* This is the component that creates the components.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultFactory
extends AbstractLoggable
implements Factory
{
protected static class LoaderEntry
{
Loader m_loader;
long m_lastModified;
}
protected final HashMap m_loaders = new HashMap();
/**
* Create a component whos position is indicated by locator.
*
* @param locator the locator indicating the component location
* @return the component
* @exception FactoryException if an error occurs
*/
public Object create( final Locator locator )
throws FactoryException
{
final Loader loader = getLoaderFor( locator.getLocation() );
try { return loader.load( locator.getName() ); }
catch( final Exception e )
{
throw new FactoryException( "Unable to create " +
locator.getName() +
" from " + locator.getLocation(), e );
}
}
public Object create( final Locator locator, final Class clazz )
throws FactoryException
{
final Object object = create( locator );
if( !clazz.isInstance( object ) )
{
throw new FactoryException( "Created object of type " +
object.getClass().getName() +
" not compatable with type " +
clazz.getName() );
}
return object;
}
protected Loader getLoaderFor( final URL url )
{
final String location = url.toString();
LoaderEntry loader = (LoaderEntry)m_loaders.get( location );
if( null == loader )
{
getLogger().info( "Creating ClassLoader for " + location );
loader = new LoaderEntry();
loader.m_loader = setupLoader( url );
loader.m_lastModified = System.currentTimeMillis();
m_loaders.put( location, loader );
}
else
{
//TODO: Check it up to date and reload if necessary
}
return loader.m_loader;
}
protected Loader setupLoader( final URL url )
{
final ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
final Loader loader = createLoader( url, classLoader );
setupLogger( loader );
return loader;
}
/**
* Create a new loader.
* Put in another method so that it can be overridden.
*
* @param location the location the Loader will load from
* @return the loader
*/
protected Loader createLoader( final URL url, final ClassLoader
classLoader )
{
return new DefaultLoader( url, classLoader );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/DefaultLoader.java
Index: DefaultLoader.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 file.
*/
package org.apache.avalon.camelot;
import java.net.URL;
import java.net.URLClassLoader;
import org.apache.avalon.util.ObjectUtil;
import org.apache.avalon.util.StringUtil;
/**
* Class used to load resources from a source.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultLoader
implements Loader
{
protected ClassLoader m_classLoader;
public DefaultLoader( final ClassLoader classLoader )
{
m_classLoader = classLoader;
}
public DefaultLoader( final URL location, final ClassLoader classLoader )
{
m_classLoader = new URLClassLoader( new URL[] { location },
classLoader );
}
public DefaultLoader( final URL location )
{
this( location, Thread.currentThread().getContextClassLoader() );
}
public DefaultLoader()
{
final ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
m_classLoader = new URLClassLoader( new URL[0], classLoader );
}
/**
* Retrieve classloader associated with source.
*
* @return the ClassLoader
*/
public ClassLoader getClassLoader()
{
return m_classLoader;
}
public Object load( final String classname, final Class clazz )
throws FactoryException
{
final Object object = load( classname );
if( !clazz.isInstance( object ) )
{
throw new FactoryException( "Created object of type " +
object.getClass().getName() +
" not compatable with type " +
clazz.getName() );
}
return object;
}
/**
* Load an object from source.
*
* @param classname the name of object
* @return the Object
* @exception Exception if an error occurs
*/
public Object load( final String classname )
throws FactoryException
{
try
{
return ObjectUtil.createObject( m_classLoader, classname );
}
catch( final ClassNotFoundException cnfe )
{
throw new FactoryException( "Failed to locate class " +
classname, cnfe );
}
catch( final InstantiationException ie )
{
throw new FactoryException( "Failed to instantiate class " +
classname, ie );
}
catch( final IllegalAccessException iae )
{
throw new FactoryException( "Failed to instantiate class " +
classname +
" as it does not have a publicly
accesable " +
"default constructor", iae );
}
catch( final Throwable t )
{
throw new FactoryException( "Failed to get class " + classname +
" due to " +
StringUtil.printStackTrace( t, 5, true ),
t );
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/DefaultLocator.java
Index: DefaultLocator.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 file.
*/
package org.apache.avalon.camelot;
import java.net.URL;
import org.apache.avalon.Component;
/**
* This contains information required to locate a component.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultLocator
implements Locator
{
protected final String m_name;
protected final URL m_location;
public DefaultLocator( final String name, final URL location )
{
m_name = name;
m_location = location;
}
/**
* Retrieve "name" of component type.
* The "name" usually indicates the classname.
*
* @return the name
*/
public String getName()
{
return m_name;
}
/**
* Retrieve location of component.
* Usually references the archive (zip/jar/war/ear)
* which contains the name (ie classname)
*
* @return the URL of location
*/
public URL getLocation()
{
return m_location;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/DefaultLocatorRegistry.java
Index: DefaultLocatorRegistry.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 file.
*/
package org.apache.avalon.camelot;
/**
* Represents a Registry of locators.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultLocatorRegistry
extends DefaultRegistry
implements LocatorRegistry
{
public DefaultLocatorRegistry()
{
super( Locator.class );
}
/**
* Retrieve a Locator by name.
*
* @param name the name
* @return the Info
* @exception RegistryException if an error occurs
*/
public Locator getLocator( String name )
throws RegistryException
{
return (Locator)getInfo( name );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/DefaultRegistry.java
Index: DefaultRegistry.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 file.
*/
package org.apache.avalon.camelot;
import java.util.HashMap;
import java.util.Iterator;
/**
* Represents a Registry of names to types.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultRegistry
implements Registry
{
protected final HashMap m_infos = new HashMap();
protected final Class m_infoClass;
public DefaultRegistry( final Class clazz )
{
m_infoClass = clazz;
}
public void register( final String name, final Info info )
throws RegistryException
{
if( null != m_infos.get( name ) )
{
throw new RegistryException( "Name " + name + " already
registered" );
}
else
{
checkInfo( name, info );
m_infos.put( name, info );
}
}
public void unregister( final String name )
throws RegistryException
{
if( null == m_infos.remove( name ) )
{
throw new RegistryException( "Name " + name + " not registered" );
}
}
public Info getInfo( final String name )
throws RegistryException
{
final Info info = (Info)m_infos.get( name );
if( null == info )
{
throw new RegistryException( "Name " + name + " not registered" );
}
else
{
return info;
}
}
public Iterator getInfoNames()
{
return m_infos.keySet().iterator();
}
protected void checkInfo( final String name, final Info info )
throws RegistryException
{
if( !m_infoClass.isAssignableFrom( info.getClass() ) )
{
throw new RegistryException( "Only Infos of type " +
m_infoClass.getName() +
" may be placed in registry." );
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/Deployer.java
Index: Deployer.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 file.
*/
package org.apache.avalon.camelot;
import java.net.URL;
import org.apache.avalon.ComponentNotFoundException;
import org.apache.avalon.Component;
/**
* A Deployer is responsible for taking a URL (ie a jar/war/ear) and deploying
* it to a particular "location". "location" means different things for
* different containers. For a servlet container it may mean the place to
* mount servlet (ie /myapp --> /myapp/Cocoon.xml is mapping cocoon servlet to
* /myapp context).
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Deployer
extends Component
{
/**
* Deploy a resource indicate by url to location.
*
* @param location the location to deploy to
* @param url the url of deployment
* @exception DeploymentException if an error occurs
*/
void deploy( String location, URL url )
throws DeploymentException;
/**
* undeploy a resource from a location.
*
* @param location the location
* @exception DeploymentException if an error occurs
*/
void undeploy( String location )
throws DeploymentException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/DeployerUtil.java
Index: DeployerUtil.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 file.
*/
package org.apache.avalon.camelot;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URL;
import java.util.Properties;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.apache.avalon.ComponentManager;
import org.apache.avalon.ComponentNotAccessibleException;
import org.apache.avalon.ComponentNotFoundException;
import org.apache.avalon.Composer;
import org.apache.avalon.Composer;
import org.apache.avalon.configuration.Configuration;
import org.apache.avalon.configuration.ConfigurationException;
import org.apache.avalon.configuration.DefaultConfigurationBuilder;
import org.xml.sax.SAXException;
/**
* This class deploys resources from camelot based system.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class DeployerUtil
{
protected static DefaultConfigurationBuilder c_configurationBuilder;
/**
* Private constructor to block instantiation.
*/
private DeployerUtil()
{
}
protected static DefaultConfigurationBuilder getBuilder()
{
if( null == c_configurationBuilder )
{
c_configurationBuilder = new DefaultConfigurationBuilder();
}
return c_configurationBuilder;
}
/**
* Get zipFile represented by URL.
*
* @param url the URL
* @return the ZipFile
* @exception DeploymentException if an error occurs
*/
/*
public final static ZipFile getZipFileFor( final URL url )
throws DeploymentException
{
final File file = getFileFor( url );
return getZipFileFor( file );
}
*/
/**
* Retrieve zip file for file.
*
* @param file the file
* @return the zipFile
* @exception DeploymentException if an error occurs
*/
public final static ZipFile getZipFileFor( final File file )
throws DeploymentException
{
try { return new ZipFile( file ); }
catch( final IOException ioe )
{
throw new DeploymentException( "Error opening " + file +
" due to " + ioe.getMessage(),
ioe );
}
}
/**
* Utility method to load configuration from zip.
*
* @param zipFile the zip file
* @param filename the property filename
* @return the Configuration
* @exception DeploymentException if an error occurs
*/
public final static Configuration loadConfiguration( final ZipFile
zipFile,
final String
filename )
throws DeploymentException
{
return buildConfiguration( loadResourceStream( zipFile, filename ) );
}
/**
* Build a configuration tree based on input stream.
*
* @param input the InputStream
* @return the Configuration tree
* @exception DeploymentException if an error occurs
*/
public final static Configuration buildConfiguration( final InputStream
input )
throws DeploymentException
{
try { return getBuilder().build( input ); }
catch( final SAXException se )
{
throw new DeploymentException( "Malformed configuration data", se
);
}
catch( final ConfigurationException ce )
{
throw new DeploymentException( "Error building configuration", ce
);
}
catch( final IOException ioe )
{
throw new DeploymentException( "Error reading configuration", ioe
);
}
}
/**
* Utility method to load a manifest from a zip file.
*
* @param zipFile the zip file
* @return the Manifest
*/
public final static Manifest loadManifest( final ZipFile zipFile )
throws DeploymentException
{
final InputStream input = loadResourceStream( zipFile,
"META-INF/MANIFEST.MF" );
try { return new Manifest( input ); }
catch( final IOException ioe )
{
throw new DeploymentException( "Error reading manifest", ioe );
}
finally
{
try { input.close(); }
catch( final IOException ioe ) {}
}
}
/**
* Utility method to load properties from zip.
*
* @param zipFile the zip file
* @param filename the property filename
* @return the Properties
* @exception DeploymentException if an error occurs
*/
public final static Properties loadProperties( final ZipFile zipFile,
final String filename )
throws DeploymentException
{
final Properties properties = new Properties();
try { properties.load( loadResourceStream( zipFile, filename ) ); }
catch( final IOException ioe )
{
throw new DeploymentException( "Error reading " + filename +
" from " + zipFile.getName(),
ioe );
}
return properties;
}
/**
* Load a resource from a zip file.
*
* @param zipFile the ZipFile
* @param filename the filename
* @return the InputStream
* @exception DeploymentException if an error occurs
*/
public final static InputStream loadResourceStream( final ZipFile
zipFile,
final String filename
)
throws DeploymentException
{
final ZipEntry entry = zipFile.getEntry( filename );
if( null == entry )
{
throw new DeploymentException( "Unable to locate " + filename +
" in " + zipFile.getName() );
}
try { return zipFile.getInputStream( entry ); }
catch( final IOException ioe )
{
throw new DeploymentException( "Error reading " + filename +
" from " + zipFile.getName(),
ioe );
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/DeploymentException.java
Index: DeploymentException.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.CascadingException;
/**
* Exception to indicate error deploying.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class DeploymentException
extends CascadingException
{
/**
* Construct a new <code>DeploymentException</code> instance.
*
* @param message The detail message for this exception.
*/
public DeploymentException( final String message )
{
this( message, null );
}
/**
* Construct a new <code>DeploymentException</code> instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public DeploymentException( final String message, final Throwable
throwable )
{
super( message, throwable );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/Entry.java
Index: Entry.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.Component;
/**
* Contains information about a particular instance of contained component.
* This would contain name, configuration data, parameters, log entries etc.
* Basically instance data.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class Entry
implements Component
{
protected Info m_info;
protected Object m_instance;
protected State m_state;
public Entry()
{
}
public Entry( final Info info, final Object instance, final State state )
{
m_info = info;
m_instance = instance;
m_state = state;
}
/**
* Retrieve Info describing instance.
*
* @return the info
*/
public Info getInfo()
{
return m_info;
}
/**
* Mutator for info property.
*
* @param info the Info
*/
public void setInfo( final Info info )
{
m_info = info;
}
/**
* Retrieve instance of component.
*
* @return the component instance
*/
public Object getInstance()
{
return m_instance;
}
/**
* Set instance of component.
*
* @return the component instance
*/
public void setInstance( final Object instance )
{
m_instance = instance;
}
/**
* Retrieve state of a component.
*
* @return the components state
*/
public State getState()
{
return m_state;
}
/**
* set state of a component.
*
* @param state the components state
*/
public void setState( final State state )
{
m_state = state;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/Factory.java
Index: Factory.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.Component;
/**
* This is the component that creates the components.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Factory
extends Component
{
/**
* Create a component whos position is indicated by locator.
*
* @param locator the locator indicating the component location
* @return the component
* @exception FactoryException if an error occurs
*/
Object create( Locator locator )
throws FactoryException;
/**
* Create a component whos position is indicated by locator.
* Make sure it is of the correct type.
*
* @param locator the locator indicating the component location
* @param clazz the expected type of component
* @return the component
* @exception FactoryException if an error occurs
*/
Object create( Locator locator, Class clazz )
throws FactoryException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/FactoryException.java
Index: FactoryException.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.CascadingException;
/**
* Exception to indicate error creating entries in factory.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class FactoryException
extends CascadingException
{
/**
* Construct a new <code>FactoryException</code> instance.
*
* @param message The detail message for this exception.
*/
public FactoryException( final String message )
{
this( message, null );
}
/**
* Construct a new <code>FactoryException</code> instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public FactoryException( final String message, final Throwable throwable
)
{
super( message, throwable );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/Info.java
Index: Info.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.Component;
/**
* This contains information relating to a component.
* There is currently two different sub-interfaces - MetaInfo and Locator.
* MetaInfo describes meta information about component while Locator
* locates it in the system.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Info
extends Component
{
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/Loader.java
Index: Loader.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.Component;
/**
* Class used to load resources from a source.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Loader
extends Component
{
/**
* Retrieve classloader associated with source.
*
* @return the ClassLoader
*/
ClassLoader getClassLoader();
/**
* Load an object from source.
*
* @param component the name of object
* @return the Object
* @exception Exception if an error occurs
*/
Object load( String component )
throws FactoryException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/Locator.java
Index: Locator.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 file.
*/
package org.apache.avalon.camelot;
import java.net.URL;
import org.apache.avalon.Component;
/**
* This contains information required to locate a component.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Locator
extends Info
{
/**
* Retrieve "name" of component type.
* The "name" usually indicates the classname.
*
* @return the name
*/
String getName();
/**
* Retrieve location of component.
* Usually references the archive (zip/jar/war/ear)
* which contains the name (ie classname)
*
* @return the URL of location
*/
URL getLocation();
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/LocatorRegistry.java
Index: LocatorRegistry.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 file.
*/
package org.apache.avalon.camelot;
/**
* Represents a database of Locators.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface LocatorRegistry
extends Registry
{
/**
* Retrieve a Locator by name.
*
* @param name the name
* @return the Info
* @exception RegistryException if an error occurs
*/
Locator getLocator( String name ) throws RegistryException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/LoggerBuilder.java
Index: LoggerBuilder.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.Component;
import org.apache.log.Logger;
/**
* Component responsible for building logger for entry.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface LoggerBuilder
extends Component
{
Logger createLogger( String name, Entry entry );
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/MetaInfo.java
Index: MetaInfo.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 file.
*/
package org.apache.avalon.camelot;
/**
* This contains information about the component.
* (ie would be a BlockInfo, an EJBDescriptor, a MailetInfo etc)
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface MetaInfo
extends Info
{
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/Registry.java
Index: Registry.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 file.
*/
package org.apache.avalon.camelot;
import java.util.Iterator;
import org.apache.avalon.Component;
/**
* Represents a database of Infos.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Registry
extends Component
{
/**
* register an info under a particular name.
*
* @param name the name
* @param info the info
* @exception RegistryException if info is invalid or name already
contains info under name
*/
void register( String name, Info info ) throws RegistryException;
/**
* unregister an info.
*
* @param name the name of info
* @exception RegistryException if no such info exists
*/
void unregister( String name ) throws RegistryException;
/**
* Retrieve an Info by name.
*
* @param name the name
* @return the Info
* @exception RegistryException if an error occurs
*/
Info getInfo( String name ) throws RegistryException;
/**
* Return an iterator of all names of infos registered.
*
* @return the info names
*/
Iterator getInfoNames();
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/RegistryException.java
Index: RegistryException.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.CascadingException;
/**
* Exception to indicate registry error.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class RegistryException
extends CascadingException
{
/**
* Construct a new <code>RegistryException</code> instance.
*
* @param message The detail message for this exception.
*/
public RegistryException( final String message )
{
this( message, null );
}
/**
* Construct a new <code>RegistryException</code> instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public RegistryException( final String message, final Throwable throwable
)
{
super( message, throwable );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/camelot/State.java
Index: State.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 file.
*/
package org.apache.avalon.camelot;
import org.apache.avalon.util.ValuedEnum;
/**
* Defines possible states for contained components.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class State
extends ValuedEnum
{
public State( final String name, final int value )
{
super( name, value );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/configuration/AbstractConfiguration.java
Index: AbstractConfiguration.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 file.
*/
package org.apache.avalon.configuration;
import java.util.Iterator;
/**
* This is an abstract <code>Configuration</code> implementation that deals
* with methods that can be abstracted away from underlying implementations.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @version CVS $Revision: 1.1 $ $Date: 2001/02/23 10:47:37 $
*/
public abstract class AbstractConfiguration
implements Configuration
{
/**
* Returns the value of the configuration element as an <code>int</code>.
*/
public int getValueAsInt()
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 of the
configuration " +
"element \"" + getName() + "\" as
an integer" );
}
}
/**
* Returns the value of the configuration element as an <code>int</code>.
*/
public int getValueAsInt( final int defaultValue )
{
try
{
return getValueAsInt();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a <code>long</code>.
*/
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 of the
" +
"configuration element \"" +
getName() +
"\" as a long" );
}
}
/**
* Returns the value of the configuration element as a <code>long</code>.
*/
public long getValueAsLong( final long defaultValue )
{
try
{
return getValueAsLong();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a <code>float</code>.
*/
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 of the
" +
"configuration element \"" +
getName() +
"\" as a float" );
}
}
/**
* Returns the value of the configuration element as a <code>float</code>.
*/
public float getValueAsFloat( final float defaultValue )
{
try
{
return getValueAsFloat();
}
catch( final ConfigurationException ce )
{
return(defaultValue);
}
}
/**
* Returns the value of the configuration element as a
<code>boolean</code>.
*/
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 of the
" +
"configuration element \"" +
getName() + "\" as a boolean" );
}
}
/**
* Returns the value of the configuration element as a
<code>boolean</code>.
*/
public boolean getValueAsBoolean( final boolean defaultValue )
{
try
{
return getValueAsBoolean();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a
<code>String</code>.
*/
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
* <code>int</code>.
*/
public int getAttributeAsInt( 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 of the
attribute \"" +
name + "\" of the configuration
element \"" +
getName() + "\" as an integer"
);
}
}
/**
* Returns the value of the attribute specified by its name as an
* <code>int</code>.
*/
public int getAttributeAsInt( final String name, final int defaultValue )
{
try
{
return getAttributeAsInt( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as a
* <code>long</code>.
*/
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 Integer.parseInt( value );
}
}
catch( final Exception nfe )
{
throw new ConfigurationException( "Cannot parse the value of the
attribute \"" +
name + "\" of the configuration
element \"" +
getName() + "\" as a long" );
}
}
/**
* Returns the value of the attribute specified by its name as a
* <code>long</code>.
*/
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
* <code>float</code>.
*/
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 of the
attribute \"" +
name + "\" of the configuration
element \"" +
getName() + "\" as a float" );
}
}
/**
* Returns the value of the attribute specified by its name as a
* <code>float</code>.
*/
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
* <code>boolean</code>.
*/
public boolean getAttributeAsBoolean( final String name )
throws ConfigurationException
{
final String value = getAttribute( name );
if( value.equals( "true" ) ) return true;
else if( value.equals( "false" ) ) return false;
else
{
throw new ConfigurationException( "Cannot parse the value of the
attribute \"" +
name + "\" of the configuration
element \"" +
getName() + "\" as a boolean" );
}
}
/**
* Returns the value of the attribute specified by its name as a
* <code>boolean</code>.
*/
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
* <code>String</code>.
*/
public String getAttribute( final String name, final String defaultValue )
{
try
{
return getAttribute( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Return the first <code>Configuration</code> object child of this
* associated with the given name.
*/
public Configuration getChild( final String name )
{
return getChild( name, true );
}
/**
* Return the first <code>Configuration</code> object child of this
* associated with the given name.
*/
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/java/org/apache/avalon/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 file.
*/
package org.apache.avalon.configuration;
/**
* This interface should be implemented by classes that need to be
* configured with custom parameters before initialization.
* <br />
*
* The contract surrounding a <code>Configurable</code> is that the
* instantiating entity must call the <code>configure</code>
* method before it is valid. The <code>configure</code> method
* must be called after the constructor, and before any other method.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Configurable
{
/**
* Pass the <code>Configuration</code> to the <code>Configurable</code>
* class. This method must always be called after the constructor
* and before any other method.
*
* @param configuration the class configurations.
*/
void configure( Configuration configuration )
throws ConfigurationException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/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 file.
*/
package org.apache.avalon.configuration;
/**
* <code>Configuration</code> is a interface encapsulating a configuration
node
* used to retrieve configuration values. This is a "read only" interface
* preventing applications from modifying their own configurations.
* <br />
*
* The contract surrounding the <code>Configuration</code> is that once
* it is created, information never changes. The <code>Configuration</code>
* is built by the <code>SAXConfigurationBuilder</code> and the
* <code>ConfigurationImpl</code> helper classes.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Configuration
{
/**
* Return the name of the node.
*
* @post getName() != null
*
* @return name of the <code>Configuration</code> node.
*/
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();
/**
* Return a new <code>Configuration</code> instance encapsulating the
* specified child node.
*
* @pre child != null
* @post getConfiguration() != null
*
* @param child The name of the child node.
* @return Configuration
*/
Configuration getChild( String child );
/**
* Return a new <code>Configuration</code> instance encapsulating the
* specified child node.
*
* @pre child != null
* @post getConfiguration() != null
*
* @param child The name of the child node.
* @return Configuration
*/
Configuration getChild( String child, boolean createNew );
/**
* Return an <code>Iterator</code> of <code>Configuration<code>
* elements containing all node children.
*
* @return The child nodes with name
*/
Configuration[] getChildren();
/**
* Return an <code>Iterator</code> of <code>Configuration<code>
* elements containing all node children with the specified name.
*
* @pre name != null
* @post getConfigurations() != null
*
* @param name The name of the children to get.
* @return The child nodes with name
*/
Configuration[] getChildren( String name );
/**
* Return an array of all attribute names.
*/
String[] getAttributeNames();
/**
* Return the value of specified attribute.
*
* @pre paramName != null
* @post getAttribute != null
*
* @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.
*/
String getAttribute( String paramName ) throws ConfigurationException;
/**
* Return the <code>int</code> value of the specified attribute contained
* in this node.
*
* @pre paramName != null
* @post getAttributeAsInt() != null
*
* @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 <code>int</code>
fails.
*/
int getAttributeAsInt( String paramName ) throws ConfigurationException;
/**
* Returns the value of the attribute specified by its name as a
* <code>long</code>.
*
* @pre paramName != null
* @post getAttributeAsLong() != null
*
* @param paramName 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
<code>long</code> fails.
*/
long getAttributeAsLong( String name ) throws ConfigurationException;
/**
* Return the <code>float</code> value of the specified parameter
contained
* in this node.
*
* @pre paramName != null
* @post getAttributeAsFloat() != null
*
* @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
<code>float</code> fails.
*/
float getAttributeAsFloat( String paramName ) throws
ConfigurationException;
/**
* Return the <code>boolean</code> value of the specified parameter
contained
* in this node.<br>
*
* @pre paramName != null
* @post getAttributeAsBoolean() != null
*
* @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
<code>boolean</code> fails.
*/
boolean getAttributeAsBoolean( String paramName ) throws
ConfigurationException;
/**
* Return the <code>String</code> value of the node.
*
* @post getValue() != null
*
* @return the value of the node.
*/
String getValue() throws ConfigurationException;
/**
* Return the <code>int</code> value of the node.
*
* @post getValueAsInt() != null
*
* @returns the value of the node.
*
* @exception ConfigurationException If conversion to <code>int</code>
fails.
*/
int getValueAsInt() throws ConfigurationException;
/**
* Return the <code>float</code> value of the node.
*
* @post getValueAsFloat() != null
*
* @return the value of the node.
* @exception ConfigurationException If conversion to <code>float</code>
fails.
*/
float getValueAsFloat() throws ConfigurationException;
/**
* Return the <code>boolean</code> value of the node.
*
* @post getValueAsBoolean() != null
*
* @return the value of the node.
* @exception ConfigurationException If conversion to
<code>boolean</code> fails.
*/
boolean getValueAsBoolean() throws ConfigurationException;
/**
* Return the <code>long</code> value of the node.<br>
*
* @post getValueAsLong() != null
*
* @return the value of the node.
* @exception ConfigurationException If conversion to <code>long</code>
fails.
*/
long getValueAsLong() throws ConfigurationException;
/**
* Returns the value of the configuration element as a
<code>String</code>.
* If the configuration value is not set, the default value will be
* used.
*
* @pre defaultValue != null
* @post getValue(defaultValue) != null
*
* @param defaultValue The default value desired.
* @return String value of the <code>Configuration</code>, or default
* if none specified.
*/
String getValue( String defaultValue );
/**
* Returns the value of the configuration element as an <code>int</code>.
* If the configuration value is not set, the default value will be
* used.
*
* @pre defaultValue != null
* @post getValueAsInt(defaultValue) != null
*
* @param defaultValue The default value desired.
* @return int value of the <code>Configuration</code>, or default
* if none specified.
*/
int getValueAsInt( int defaultValue );
/**
* Returns the value of the configuration element as a <code>long</code>.
* If the configuration value is not set, the default value will be
* used.
*
* @pre defaultValue != null
* @post getValueAsLong(defaultValue) != null
*
* @param defaultValue The default value desired.
* @return long value of the <code>Configuration</code>, or default
* if none specified.
*/
long getValueAsLong( long defaultValue );
/**
* Returns the value of the configuration element as a <code>float</code>.
* If the configuration value is not set, the default value will be
* used.
*
* @pre defaultValue != null
* @post getValueAsFloat(defaultValue) != null
*
* @param defaultValue The default value desired.
* @return float value of the <code>Configuration</code>, or default
* if none specified.
*/
float getValueAsFloat( float defaultValue );
/**
* Returns the value of the configuration element as a
<code>boolean</code>.
* If the configuration value is not set, the default value will be
* used.
*
* @pre defaultValue != null
* @post getValueAsBoolean(defaultValue) != null
*
* @param defaultValue The default value desired.
* @return boolean value of the <code>Configuration</code>, or default
* if none specified.
*/
boolean getValueAsBoolean( boolean defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* <code>String</code>, or the default value if no attribute by
* that name exists or is empty.
*
* @pre name != null
* @pre defaultValue != null
* @post getAttribute(name, defaultValue) != null
*
* @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.
*/
String getAttribute( String name, String defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* <code>int</code>, or the default value if no attribute by
* that name exists or is empty.
*
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsInt(name, defaultValue) != null
*
* @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.
*/
int getAttributeAsInt( String name, int defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* <code>long</code>, or the default value if no attribute by
* that name exists or is empty.
*
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsLong(name, defaultValue) != null
*
* @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.
*/
long getAttributeAsLong( String name, long defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* <code>float</code>, or the default value if no attribute by
* that name exists or is empty.
*
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsFloat(name, defaultValue) != null
*
* @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.
*/
float getAttributeAsFloat( String name, float defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* <code>boolean</code>, or the default value if no attribute by
* that name exists or is empty.
*
* @pre name != null
* @pre defaultValue != null
* @post getAttributeAsBoolean(name, defaultValue) != null
*
* @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.
*/
boolean getAttributeAsBoolean( String name, boolean defaultValue );
}
1.1
jakarta-avalon/src/java/org/apache/avalon/configuration/ConfigurationBuilder.java
Index: ConfigurationBuilder.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 file.
*/
package org.apache.avalon.configuration;
import java.io.IOException;
import org.xml.sax.SAXException;
/**
* The interface implemented to build configurations.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface ConfigurationBuilder
{
Configuration build( String resource )
throws SAXException, IOException, ConfigurationException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/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 file.
*/
package org.apache.avalon.configuration;
import org.apache.avalon.CascadingException;
/**
* Thrown when a <code>Configurable</code> component cannot be configured
* properly, or if a value cannot be retrieved properly.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
*/
public final class ConfigurationException
extends CascadingException
{
/**
* Construct a new <code>ConfigurationException</code> instance.
*
* @param message The detail message for this exception.
*/
public ConfigurationException( final String message )
{
this( message, null );
}
/**
* Construct a new <code>ConfigurationException</code> 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, throwable );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/configuration/DefaultConfiguration.java
Index: DefaultConfiguration.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 file.
*/
package org.apache.avalon.configuration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
/**
* This is the default <code>Configuration</code> implementation.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultConfiguration
extends AbstractConfiguration
{
protected final static Configuration[] EMPTY_ARRAY = new Configuration[
0 ];
protected final String m_name;
protected final String m_location;
protected HashMap m_attributes;
protected ArrayList m_children;
protected String m_value;
/**
* Create a new <code>DefaultConfiguration</code> instance.
*/
public DefaultConfiguration( final String name, final String location )
{
m_name = name;
m_location = location;
}
/**
* Returns the name of this configuration element.
*/
public String getName()
{
return m_name;
}
/**
* Returns a description of location of element.
*/
public String getLocation()
{
return m_location;
}
/**
* Returns the value of the configuration element as a
<code>String</code>.
*
* @exception 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() + "\"" );
}
}
/**
* Return an array of all attribute names.
*/
public String[] getAttributeNames()
{
if( null == m_attributes ) return new String[ 0 ];
else return (String[])m_attributes.keySet().toArray( new String[ 0 ]
);
}
/**
* Return an <code>Iterator</code> of <code>Configuration<code>
* 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
* <code>String</code>.
*
* @exception 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() + "\"" );
}
}
/**
* Return the first <code>Configuration</code> object child of this
* associated with the given name.
*/
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 <code>Enumeration</code> of <code>Configuration</code>
objects
* children of this associated with the given name.
* <br>
* The returned <code>Enumeration</code> may be empty.
*
* @param name The name of the required children
<code>Configuration</code>.
*/
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.
*/
public void appendValueData( final String value )
{
if( null == m_value )
{
m_value = value;
}
else
{
m_value = m_value + value;
}
}
/**
* Add an attribute to this configuration element, returning its old
* value or <b>null</b>.
*/
public String addAttribute( final String name, String value )
{
if( null == m_attributes ) m_attributes = new HashMap();
return (String) m_attributes.put( name, value );
}
/**
* Add a child <code>Configuration</code> to this configuration element.
*/
public void addChild( final Configuration configuration )
{
if( null == m_children )
{
m_children = new ArrayList();
}
m_children.add( configuration );
}
/**
* Return count of children.
*/
public int getChildCount()
{
if( null == m_children )
{
return 0;
}
return m_children.size();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/configuration/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 file.
*/
package org.apache.avalon.configuration;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* A SAXConfigurationBuilder builds configurations via SAX2 compliant parser.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultConfigurationBuilder
implements ConfigurationBuilder
{
protected final static String DEFAULT_PARSER =
"org.apache.xerces.parsers.SAXParser";
protected final static String PARSER =
System.getProperty("org.xml.sax.parser", DEFAULT_PARSER );
protected SAXConfigurationHandler m_handler;
protected XMLReader m_parser;
public DefaultConfigurationBuilder()
{
this( PARSER );
}
public DefaultConfigurationBuilder( final String parserClass )
{
//yaya the bugs with some compilers and final variables ..
m_handler = getHandler();
try
{
m_parser = XMLReaderFactory.createXMLReader( parserClass );
//m_parser.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
m_parser.setContentHandler( m_handler );
m_parser.setErrorHandler( m_handler );
}
catch( final SAXException se )
{
throw new Error( "Unable to setup SAX parser" + se );
}
}
protected SAXConfigurationHandler getHandler()
{
return new SAXConfigurationHandler();
}
public Configuration build( final String resource )
throws SAXException, IOException, ConfigurationException
{
final InputStream input = new FileInputStream( resource );
try { return build( input ); }
finally
{
try { input.close(); }
catch( final IOException ioe ) {}
}
}
public Configuration build( final InputStream inputStream )
throws SAXException, IOException, ConfigurationException
{
final InputSource inputSource = new InputSource( inputStream );
return build( inputSource );
}
public Configuration build( final InputSource input )
throws SAXException, IOException, ConfigurationException
{
m_handler.clear();
m_parser.parse( input );
return m_handler.getConfiguration();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/configuration/Reconfigurable.java
Index: Reconfigurable.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 file.
*/
package org.apache.avalon.configuration;
/**
* Extends Configurable to allow reconfiguration runtime.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Reconfigurable
extends Configurable
{
void reconfigure( Configuration configuration ) throws
ConfigurationException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/configuration/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 file.
*/
package org.apache.avalon.configuration;
import java.io.IOException;
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;
/**
* A SAXConfigurationHandler helps build Configurations out of sax events.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class SAXConfigurationHandler
extends DefaultHandler
implements ErrorHandler
{
protected final ArrayList m_elements = new
ArrayList();
protected Configuration m_configuration;
protected Locator m_locator;
public Configuration getConfiguration()
{
return m_configuration;
}
public void clear()
{
m_elements.clear();
m_locator = null;
}
public void setDocumentLocator( final Locator locator )
{
m_locator = locator;
}
public void characters( final char[] ch, int start, int end )
throws SAXException
{
final 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() );
}
configuration.appendValueData( value );
}
public void endElement( final String namespaceURI,
final String localName,
final String rawName )
{
final int location = m_elements.size() - 1;
final Object object = m_elements.remove( location );
if( 0 == location )
{
m_configuration = (Configuration)object;
}
}
protected DefaultConfiguration createConfiguration( final String
localName,
final String location
)
{
return new DefaultConfiguration( localName, location );
}
public void startElement( final String namespaceURI,
final String localName,
final String rawName,
final Attributes attributes )
throws SAXException
{
final DefaultConfiguration configuration =
createConfiguration( localName, 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.addAttribute( name, value );
}
}
/**
* This just throws an exception on a parse error.
*/
public void error( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
*/
public void warning( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
*/
public void fatalError( final SAXParseException exception )
throws SAXException
{
throw exception;
}
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/java/org/apache/avalon/services/Service.java
Index: Service.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 file.
*/
package org.apache.avalon.services;
/**
* This is a marker interface that all Services must implement.
* A Service is a behavioural contract that an object implements.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @deprecated This is deprecated in favour of directly extending the
interface in phoenix package
*/
public interface Service {
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/ArrayEnumeration.java
Index: ArrayEnumeration.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 file.
*/
package org.apache.avalon.util;
import java.util.Enumeration;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Enumeration wrapper for array.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class ArrayEnumeration
implements Enumeration
{
protected Object[] m_elements;
protected int m_index;
public ArrayEnumeration( final List elements )
{
m_elements = elements.toArray();
}
public ArrayEnumeration( final Object[] elements )
{
m_elements = elements;
}
public boolean hasMoreElements()
{
return ( m_index < m_elements.length );
}
public Object nextElement()
{
if( !hasMoreElements() )
{
throw new NoSuchElementException("No more elements exist");
}
return m_elements[ m_index++ ];
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/ArrayStack.java
Index: ArrayStack.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 file.
*/
package org.apache.avalon.util;
import java.util.ArrayList;
import java.util.EmptyStackException;
/**
* Unsynchronized stakc.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class ArrayStack
extends ArrayList
{
public void setSize( final int size )
{
if( 0 == size ) clear();
else
{
removeRange( size, size() - 1 );
}
}
/**
* Adds the object to the top of the stack.
*
* @param element object to add to stack
* @return the object
*/
public Object push( final Object element )
{
add( element );
return element;
}
/**
* Remove element from top of stack and return it
*
* @return the element from stack
* @exception EmptyStackException if no elements left on stack
*/
public Object pop()
throws EmptyStackException
{
final int size = size();
if( 0 == size ) throw new EmptyStackException();
return remove( size - 1 );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/BinaryHeap.java
Index: BinaryHeap.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 file.
*/
package org.apache.avalon.util;
import java.util.NoSuchElementException;
/**
* Iterface for priority queues.
* This interface does not dictate whether it is min or max heap.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class BinaryHeap
implements PriorityQueue
{
protected final static int DEFAULT_CAPACITY = 13;
protected int m_size;
protected Comparable[] m_elements;
protected boolean m_isMinHeap;
public BinaryHeap()
{
this( DEFAULT_CAPACITY, true );
}
public BinaryHeap( final int capacity )
{
this( capacity, true );
}
public BinaryHeap( final boolean isMinHeap )
{
this( DEFAULT_CAPACITY, isMinHeap );
}
public BinaryHeap( final int capacity, final boolean isMinHeap )
{
m_isMinHeap = isMinHeap;
//+1 as 0 is noop
m_elements = new Comparable[ capacity + 1 ];
}
/**
* Clear all elements from queue.
*/
public void clear()
{
m_size = 0;
}
/**
* Test if queue is empty.
*
* @return true if queue is empty else false.
*/
public boolean isEmpty()
{
return ( 0 == m_size );
}
/**
* Test if queue is full.
*
* @return true if queue is full else false.
*/
public boolean isFull()
{
return ( m_elements.length == m_size );
}
/**
* Insert an element into queue.
*
* @param element the element to be inserted
*/
public void insert( final Comparable element )
{
if( isFull() ) grow();
//percolate element to it's place in tree
if( m_isMinHeap ) percolateUpMinHeap( element );
else percolateUpMaxHeap( element );
}
/**
* Return element on top of heap but don't remove it.
*
* @return the element at top of heap
* @exception NoSuchElementException if isEmpty() == true
*/
public Comparable peek() throws NoSuchElementException
{
if( isEmpty() ) throw new NoSuchElementException();
else return m_elements[ 1 ];
}
/**
* Return element on top of heap and remove it.
*
* @return the element at top of heap
* @exception NoSuchElementException if isEmpty() == true
*/
public Comparable pop() throws NoSuchElementException
{
final Comparable result = peek();
m_elements[ 1 ] = m_elements[ m_size-- ];
if( m_size != 0 )
{
//percolate top element to it's place in tree
if( m_isMinHeap ) percolateDownMinHeap( 1 );
else percolateDownMaxHeap( 1 );
}
return result;
}
/**
* Percolate element down heap from top.
* Assume it is a maximum heap.
*
* @param element the element
*/
protected void percolateDownMinHeap( final int index )
{
final Comparable element = m_elements[ index ];
int hole = index;
while( (hole * 2) <= m_size )
{
int child = hole * 2;
//if we have a right child and that child can not be percolated
//up then move onto other child
if( child != m_size &&
m_elements[ child + 1 ].compareTo( m_elements[ child ] ) < 0 )
{
child++;
}
//if we found resting place of bubble then terminate search
if( m_elements[ child ].compareTo( element ) >= 0 )
{
break;
}
m_elements[ hole ] = m_elements[ child ];
hole = child;
}
m_elements[ hole ] = element;
}
/**
* Percolate element down heap from top.
* Assume it is a maximum heap.
*
* @param element the element
*/
protected void percolateDownMaxHeap( final int index )
{
final Comparable element = m_elements[ index ];
int hole = index;
while( (hole * 2) <= m_size )
{
int child = hole * 2;
//if we have a right child and that child can not be percolated
//up then move onto other child
if( child != m_size &&
m_elements[ child + 1 ].compareTo( m_elements[ child ] ) > 0 )
{
child++;
}
//if we found resting place of bubble then terminate search
if( m_elements[ child ].compareTo( element ) <= 0 )
{
break;
}
m_elements[ hole ] = m_elements[ child ];
hole = child;
}
m_elements[ hole ] = element;
}
/**
* Percolate element up heap from bottom.
* Assume it is a maximum heap.
*
* @param element the element
*/
protected void percolateUpMinHeap( final Comparable element )
{
int hole = ++m_size;
m_elements[ hole ] = element;
while( hole > 1 &&
element.compareTo( m_elements[ hole / 2 ] ) < 0 )
{
//save element that is being pushed down
//as the element "bubble" is percolated up
final int next = hole / 2;
m_elements[ hole ] = m_elements[ next ];
hole = next;
}
m_elements[ hole ] = element;
}
/**
* Percolate element up heap from bottom.
* Assume it is a maximum heap.
*
* @param element the element
*/
protected void percolateUpMaxHeap( final Comparable element )
{
int hole = ++m_size;
while( hole > 1 &&
element.compareTo( m_elements[ hole / 2 ] ) > 0 )
{
//save element that is being pushed down
//as the element "bubble" is percolated up
final int next = hole / 2;
m_elements[ hole ] = m_elements[ next ];
hole = next;
}
m_elements[ hole ] = element;
}
protected void grow()
{
final Comparable[] elements =
new Comparable[ m_elements.length * 2 ];
System.arraycopy( m_elements, 0, elements, 0, m_elements.length );
m_elements = elements;
}
public String toString()
{
final StringBuffer sb = new StringBuffer();
sb.append( "[ " );
for( int i = 1; i < m_size + 1; i++ )
{
if( i != 1 ) sb.append( ", " );
sb.append( m_elements[ i ] );
}
sb.append( " ]" );
return sb.toString();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/Circuit.java
Index: Circuit.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 file.
*/
package org.apache.avalon.util;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
*
* @version 0.0.20, 04/07/1998
* @author Federico Barbieri <[EMAIL PROTECTED]>
* @author Stefano Mazzocchi <[EMAIL PROTECTED]>
*/
public class Circuit
{
protected Hashtable m_map;
public Circuit()
{
m_map = new Hashtable();
}
public void addNode( final String name )
{
if( null == m_map.get( name ) )
{
m_map.put( name, new Node( name ) );
}
}
public void removeNode( final String name )
{
String tmp = null;
Enumeration e = m_map.keys();
while( e.hasMoreElements() )
{
tmp = (String)e.nextElement();
if( !tmp.equals( name ) )
{
try { unlink( tmp, name ); }
catch( final CircuitException ce) {}
try { unlink( name, tmp ); }
catch( final CircuitException ce ) {}
}
}
m_map.remove( name );
}
public void link( final String parent, final String child )
throws CircuitException
{
Node tempNode = null;
Node pnode = (Node)m_map.get( parent );
Node cnode = (Node)m_map.get( child );
if( null == pnode )
{
throw new CircuitException( "Unknown node " + parent );
}
else if( null == cnode )
{
throw new CircuitException( "Unknown node " + child );
}
else if( pnode.isChildOf( cnode ) )
{
throw new CircuitException( "Loop! Node " + parent +
" is already child of node " + child
);
}
else
{
final Enumeration e = m_map.elements();
while( e.hasMoreElements() )
{
tempNode = (Node)e.nextElement();
if( tempNode.isChildOf( cnode ) )
{
tempNode.m_parents.addAll( pnode.m_parents );
}
}
}
}
public void unlink( final String parent, final String child )
throws CircuitException
{
Node cnode = (Node)m_map.get( child );
Node pnode = (Node)m_map.get( parent );
if( cnode.m_parents.contains( pnode ) )
{
Node tempNode = null;
Enumeration e = m_map.elements();
while( e.hasMoreElements() )
{
tempNode = (Node)e.nextElement();
if( tempNode.m_parents.contains( cnode ) )
{
tempNode.m_parents.removeAll( pnode.m_parents );
}
}
}
else
{
throw new CircuitException( "Node " + parent + " is not parent of
node " + child );
}
}
public Vector getAncestors()
{
Vector ancestors = new Vector();
String name = null;
Node tempNode = null;
Enumeration e = m_map.keys();
while( e.hasMoreElements() )
{
name = (String)e.nextElement();
tempNode = (Node)m_map.get( name );
if( 1 == tempNode.m_parents.size() )
{
ancestors.addElement( name );
}
}
return ancestors;
}
public String getAncestor()
{
String name = null;
Node tempNode = null;
Enumeration e = m_map.keys();
while( e.hasMoreElements() )
{
name = (String)e.nextElement();
tempNode = (Node)m_map.get( name );
if( 1 == tempNode.m_parents.size() )
{
return name;
}
}
return null;
}
public boolean isEmpty()
{
return m_map.isEmpty();
}
protected final class Node
{
protected Vector m_parents;
protected String m_name;
protected Node( final String name )
{
m_parents = new Vector( 5 );
m_parents.addElement( this );
m_name = name;
}
protected boolean isChildOf( final Node parent )
{
return m_parents.contains( parent );
}
public String toString()
{
StringBuffer buffer = new StringBuffer();
Enumeration e = m_parents.elements();
buffer.append( m_name + "[" );
while( e.hasMoreElements() )
{
buffer.append(((Node) e.nextElement()).m_name + " ");
}
buffer.append("]");
return buffer.toString();
}
}
public final class CircuitException
extends RuntimeException
{
public CircuitException()
{
}
public CircuitException( final String message )
{
super( message );
}
}
public String toString()
{
StringBuffer buffer = new StringBuffer();
String name = null;
Node tempNode = null;
Enumeration e = m_map.keys();
while( e.hasMoreElements() )
{
name = (String)e.nextElement();
tempNode = (Node)m_map.get( name );
buffer.append( name + "(" + ( tempNode.m_parents.size() - 1 ) +
") " );
}
return buffer.toString();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/CircularBuffer.java
Index: CircularBuffer.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 file.
*/
package org.apache.avalon.util;
/**
*
* @author Federico Barbieri <[EMAIL PROTECTED]>
*/
public class CircularBuffer
{
protected Object[] m_buffer;
protected int m_bufferSize;
protected int m_contentSize;
protected int m_head;
protected int m_tail;
public CircularBuffer( int size )
{
m_buffer = new Object[size];
m_bufferSize = size;
m_contentSize = 0;
m_head = 0;
m_tail = 0;
}
public CircularBuffer()
{
this( 32 );
}
public boolean isEmpty()
{
return (m_contentSize == 0);
}
public int getContentSize()
{
return m_contentSize;
}
public int getBufferSize()
{
return m_bufferSize;
}
public void append( final Object o )
{
if( m_contentSize >= m_bufferSize )
{
int j = 0;
int i = m_tail;
Object[] tmp = new Object[ m_bufferSize * 2 ];
while( m_contentSize > 0 )
{
i++;
i %= m_bufferSize;
j++;
m_contentSize--;
tmp[ j ] = m_buffer[ i ];
}
m_buffer = tmp;
m_tail = 0;
m_head = j;
m_contentSize = j;
m_bufferSize *= 2;
}
m_buffer[ m_head ] = o;
m_head++;
m_head %= m_bufferSize;
m_contentSize++;
}
public Object get()
{
if( m_contentSize <= 0 )
{
return null;
}
Object o = m_buffer[ m_tail ];
m_tail++;
m_tail %= m_bufferSize;
m_contentSize--;
return o;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/CircularDependencyException.java
Index: CircularDependencyException.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 file.
*/
package org.apache.avalon.util;
import java.util.List;
import org.apache.avalon.CascadingException;
/**
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class CircularDependencyException
extends CascadingException
{
protected List m_stack;
public CircularDependencyException( final String dependee,
final String dependent,
final List stack )
{
super( dependee + " depends upon " + dependent + " which depends
upong " + dependee );
m_stack = stack;
}
public List getStack()
{
return m_stack;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/DependencyGraph.java
Index: DependencyGraph.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 file.
*/
package org.apache.avalon.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* DirectedGraph is a acyclic Directed graph implementation.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DependencyGraph
{
protected final HashMap m_map = new HashMap();
protected boolean m_allowCircularity = true;
public void setAllowCircularity( final boolean allowCircularity )
{
m_allowCircularity = allowCircularity;
}
public void add( final String name, final String[] dependencies )
{
m_map.put( name, new GraphNode( name, dependencies ) );
}
public void remove( final String name )
{
m_map.remove( name );
}
public Dependency[] getDependencyList( final String name )
throws CircularDependencyException
{
final ArrayList list = new ArrayList();
final Dependency dependency = new Dependency( name , null );
list.add( dependency );
if( null != m_map.get( name ) )
{
final ArrayList stack = new ArrayList();
stack.add( name );
buildDependencyList( name, list, new ArrayList(), stack );
}
return (Dependency[])list.toArray( new Dependency[ 0 ] );
}
protected void buildDependencyList( final String name,
final ArrayList list,
final ArrayList done,
final ArrayList stack )
throws CircularDependencyException
{
if( done.contains( name ) ) return;
done.add( name );
final GraphNode node = (GraphNode)m_map.get( name );
if( null == node ) return;
final String[] dependencies = node.getDependencies();
for( int i = 0; i < dependencies.length; i++ )
{
if( stack.contains( dependencies[ i ] ) )
{
if( m_allowCircularity ) continue;
else
{
throw new CircularDependencyException( dependencies[ i ],
name, stack );
}
}
if( done.contains( dependencies[ i ] ) ) continue;
final Dependency dependency = new Dependency( dependencies[ i ],
name );
list.add( dependency );
stack.add( dependencies[ i ] );
buildDependencyList( dependencies[ i ], list, done, stack );
stack.remove( stack.size() - 1 );
}
}
public final static class Dependency
{
protected final String m_name;
protected final String m_requiredBy;
protected Dependency( final String name, final String requiredBy )
{
m_name = name;
m_requiredBy = requiredBy;
}
public String getName()
{
return m_name;
}
public String getRequiredBy()
{
return m_requiredBy;
}
public String toString()
{
return getName();
}
}
protected final static class GraphNode
{
protected final String m_name;
protected final String[] m_dependencies;
protected GraphNode( final String name, final String[] dependencies )
{
m_name = name;
m_dependencies = dependencies;
}
public String getName()
{
return m_name;
}
public String[] getDependencies()
{
return m_dependencies;
}
}
}
1.1 jakarta-avalon/src/java/org/apache/avalon/util/Enum.java
Index: Enum.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 file.
*/
package org.apache.avalon.util;
import java.util.Map;
/**
* Basic enum class for type-safe enums. Should be used as an abstract base.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class Enum
{
protected final String m_name;
public Enum( final String name )
{
this( name, null );
}
public Enum( final String name, final Map map )
{
m_name = name;
if( null != map )
{
map.put( name, this );
}
}
public final String getName()
{
return m_name;
}
public String toString()
{
return getClass().getName() + "[" + m_name + "]";
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/IteratorEnumeration.java
Index: IteratorEnumeration.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 file.
*/
package org.apache.avalon.util;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Enumeration wrapper for iterator.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class IteratorEnumeration
implements Enumeration
{
protected Iterator m_iterator;
public IteratorEnumeration( final Iterator iterator )
{
m_iterator = iterator;
}
public boolean hasMoreElements()
{
return m_iterator.hasNext();
}
public Object nextElement()
{
return m_iterator.next();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/ListUtils.java
Index: ListUtils.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 file.
*/
package org.apache.avalon.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Miscelaneous utilities to manipulate Lists.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class ListUtils
{
public static List intersection( final List list1, final List list2 )
{
final ArrayList result = new ArrayList();
final Iterator iterator = list2.iterator();
while( iterator.hasNext() )
{
final Object o = iterator.next();
if ( list1.contains( o ) )
{
result.add( o );
}
}
return result;
}
public static List subtract( final List list1, final List list2 )
{
final ArrayList result = new ArrayList( list1 );
final Iterator iterator = list2.iterator();
while( iterator.hasNext() )
{
result.remove( iterator.next() );
}
return result;
}
public static List sum( final List list1, final List list2 )
{
return subtract( union( list1, list2 ),
intersection( list1, list2 ) );
}
public static List union( final List list1, final List list2 )
{
final ArrayList result = new ArrayList( list1 );
result.addAll( list2 );
return result;
}
}
1.1 jakarta-avalon/src/java/org/apache/avalon/util/Lock.java
Index: Lock.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 file.
*/
package org.apache.avalon.util;
import java.util.Hashtable;
/**
* @author Federico Barbieri <[EMAIL PROTECTED]>
*/
public class Lock
{
private Hashtable locks = new Hashtable();
public boolean isLocked( final Object key )
{
return (locks.get(key) != null);
}
public boolean canI( final Object key )
{
Object o = locks.get( key );
if( null == o || o == this.getCallerId() )
{
return true;
}
return false;
}
public boolean lock( final Object key )
{
Object theLock;
synchronized( this )
{
theLock = locks.get( key );
}
if( null == theLock )
{
locks.put( key, getCallerId() );
return true;
}
else if( getCallerId() == theLock )
{
return true;
}
else
{
return false;
}
}
public boolean unlock( final Object key )
{
Object theLock;
synchronized( this )
{
theLock = locks.get( key );
}
if( null == theLock )
{
return true;
}
else if( getCallerId() == theLock )
{
locks.remove( key );
return true;
}
else
{
return false;
}
}
private Object getCallerId()
{
return Thread.currentThread();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/LockException.java
Index: LockException.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 file.
*/
package org.apache.avalon.util;
public class LockException
extends RuntimeException
{
public LockException( final String message )
{
super( message );
}
public LockException()
{
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/ObjectUtil.java
Index: ObjectUtil.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 file.
*/
package org.apache.avalon.util;
/**
* This class provides basic facilities for manipulating objects.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class ObjectUtil
{
/**
* Private constructor to prevent instantiation.
*/
private ObjectUtil()
{
}
public static boolean isEqual( final Object o1, final Object o2 )
{
if( null == o1 )
{
if( null == o2 )
{
return true;
}
else
{
return false;
}
}
else if( null == o2 )
{
return false;
}
else
{
return o1.equals( o2 );
}
}
public static Object createObject( final ClassLoader classLoader, final
String classname )
throws ClassNotFoundException, InstantiationException,
IllegalAccessException
{
final Class clazz = classLoader.loadClass( classname );
return clazz.newInstance();
}
public static Object createObject( final String classname )
throws ClassNotFoundException, InstantiationException,
IllegalAccessException
{
final Class clazz = Class.forName( classname );
return clazz.newInstance();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/Primes.java
Index: Primes.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 file.
*/
package org.apache.avalon.util;
/**
*
* @author Federico Barbieri <[EMAIL PROTECTED]>
* @author Stefano Mazzocchi <[EMAIL PROTECTED]>
*/
public class Primes
{
/**
* Last prime found.
*
*/
protected static long c_lastPrime = 1;
/**
* Return next prime.
*
*/
public static long nextPrime()
{
long l = c_lastPrime + 1;
long v = 2;
while( true )
{
l++;
while( v < l )
{
v++;
if( (l % v) == 0 )
{
v = 0;
break;
}
} // while v < l
if( v == l )
{
c_lastPrime = l;
return l;
} // if v is l
} // while true (break is used to escape)
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/PriorityQueue.java
Index: PriorityQueue.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 file.
*/
package org.apache.avalon.util;
import java.util.NoSuchElementException;
/**
* Iterface for priority queues.
* This interface does not dictate whether it is min or max heap.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface PriorityQueue
{
/**
* Clear all elements from queue.
*/
void clear();
/**
* Test if queue is empty.
*
* @return true if queue is empty else false.
*/
boolean isEmpty();
/**
* Insert an element into queue.
*
* @param element the element to be inserted
*/
void insert( Comparable element );
/**
* Return element on top of heap but don't remove it.
*
* @return the element at top of heap
* @exception NoSuchElementException if isEmpty() == true
*/
Comparable peek() throws NoSuchElementException;
/**
* Return element on top of heap and remove it.
*
* @return the element at top of heap
* @exception NoSuchElementException if isEmpty() == true
*/
Comparable pop() throws NoSuchElementException;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/PropertyException.java
Index: PropertyException.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 file.
*/
package org.apache.avalon.util;
import org.apache.avalon.CascadingException;
/**
* Thrown when a property can not be resolved properly.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class PropertyException
extends CascadingException
{
/**
* Construct a new <code>PropertyException</code> instance.
*
* @param message The detail message for this exception.
*/
public PropertyException( final String message )
{
this( message, null );
}
/**
* Construct a new <code>PropertyException</code> instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public PropertyException( final String message, final Throwable throwable
)
{
super( message, throwable );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/PropertyUtil.java
Index: PropertyUtil.java
===================================================================
package org.apache.avalon.util;
import org.apache.avalon.Context;
import org.apache.avalon.Resolvable;
/**
* This provides utility methods for properties.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class PropertyUtil
{
private PropertyUtil()
{
}
/**
* Resolve property.
* This evaluates all property substitutions based on current context.
*
* @param property the property to resolve
* @param context the context in which to resolve property
* @param ignoreUndefined if false will throw an PropertyException if
property is not found
* @return the reolved property
* @exception PropertyException if an error occurs
*/
public static Object resolveProperty( final String property,
final Context context,
final boolean ignoreUndefined )
throws PropertyException
{
int start = property.indexOf( "${" );
if( -1 == start ) return property;
int end = property.indexOf( '}', start );
if( -1 == end ) return property;
final int length = property.length();
if( 0 == start && end == (length - 1) )
{
return resolveValue( property.substring( start + 2, end ),
context,
ignoreUndefined );
}
final StringBuffer sb = new StringBuffer();
int lastPlace = 0;
while( true )
{
final Object value =
resolveValue( property.substring( start + 2, end ),
context,
ignoreUndefined );
sb.append( property.substring( lastPlace, start ) );
sb.append( value );
lastPlace = end + 1;
start = property.indexOf( "${", end );
if( -1 == start ) break;
end = property.indexOf( '}', start );
if( -1 == end ) break;
}
sb.append( property.substring( lastPlace, length ) );
return sb.toString();
}
protected static Object resolveValue( final String key,
final Context context,
final boolean ignoreUndefined )
throws PropertyException
{
Object value = context.get( key );
while( null != value && value instanceof Resolvable )
{
value = ((Resolvable)value).resolve( context );
}
if( null == value )
{
if( ignoreUndefined )
{
return "";
}
else
{
throw new PropertyException( "Unable to find " + key + " to
expand during " +
"property resolution." );
}
}
return value;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/ProxyClassLoader.java
Index: ProxyClassLoader.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 file.
*/
package org.apache.avalon.util;
/**
* Utility class to help load dynamically generated classes.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class ProxyClassLoader
extends ClassLoader
{
public ProxyClassLoader( final ClassLoader parent )
{
super( parent );
}
public Class loadClass( final String name,
final boolean resolve,
final byte[] classData )
throws ClassNotFoundException
{
final Class result =
defineClass( name, classData, 0, classData.length );
if( resolve )
{
resolveClass( result );
}
return result;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/ProxyGenerator.java
Index: ProxyGenerator.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 file.
*/
package org.apache.avalon.util;
import gnu.bytecode.Access;
import gnu.bytecode.ClassType;
import gnu.bytecode.ClassTypeWriter;
import gnu.bytecode.CodeAttr;
import gnu.bytecode.Field;
import gnu.bytecode.Scope;
import gnu.bytecode.Type;
import gnu.bytecode.Variable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.log.LogKit;
import org.apache.log.Logger;
/**
* A class to generate proxies for objects.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class ProxyGenerator
{
protected final static boolean DEBUG = false;
protected final static Logger LOGGER =
( DEBUG ) ? LogKit.getLoggerFor( "ProxyGenerator" ) : null;
protected final static Object MONITOR = new Object();
protected final static ClassType BASE_CLASS =
(ClassType)Type.getType( "java.lang.Object" );
protected static long c_currentId;
/**
* Private constructor to block subclassing.
*
*/
private ProxyGenerator()
{
}
/**
* Way to generate unique id for each class.
*
* @return a unique id
*/
protected static long getNextId()
{
synchronized( MONITOR )
{
return c_currentId++;
}
}
/**
* Generate a proxy for object with certain interfaces.
*
* @param object the object
* @param interfaces[] the interfaces
* @return the proxy object
* @exception IllegalArgumentException if an error occurs
*/
public static Object generateProxy( final Object object,
final Class[] interfaces )
throws IllegalArgumentException
{
if( DEBUG )
{
LOGGER.debug( "Generating proxy for " +
object.getClass().getName() );
LOGGER.debug( "Interfaces generating:" );
for( int i = 0; i < interfaces.length; i++ )
{
LOGGER.debug( interfaces[ i ].getName() );
}
}
for( int i = 0; i < interfaces.length; i++ )
{
if( !interfaces[ i ].isInterface() )
{
throw new IllegalArgumentException( "Class " + interfaces[ i
].getName() +
" is not an interface" );
}
else if( !interfaces[ i ].isInstance( object ) )
{
throw new IllegalArgumentException( "Object does not
implement interface " +
interfaces[ i ].getName()
);
}
}
final HashMap methodSet = determineMethods( interfaces );
final String classname = "org.apache.avalon.tmp.Proxy" + getNextId();
if( DEBUG ) { LOGGER.debug( "Generating proxy named " + classname ); }
final ClassType proxy = createProxyType( classname );
//generate all interface declarations
generateInterfaces( proxy, interfaces );
final ClassType target =
(ClassType)Type.make( object.getClass() );
target.doFixups();
//generate variables/constructor
generateBase( proxy, target );
//generate methods
final Iterator methods = methodSet.values().iterator();
while( methods.hasNext() )
{
generateMethod( proxy, target, (Method)methods.next() );
}
if( DEBUG )
{
//help while debugging
//ClassTypeWriter.print( target, System.out, 0 );
//try { proxy.writeToFile( "/tmp/" + classname.replace('.','/') +
".class" ); }
//catch( final Throwable throwable ) {
throwable.printStackTrace(); }
}
proxy.doFixups();
Class proxyClass = null;
try
{
final byte[] classData = proxy.writeToArray();
//extremely inneficient - must fix in future
final ProxyClassLoader classLoader =
new ProxyClassLoader( object.getClass().getClassLoader() );
proxyClass = classLoader.loadClass( classname, true, classData );
final Constructor ctor =
proxyClass.getConstructor( new Class[] { object.getClass() }
);
return ctor.newInstance( new Object[] { object } );
}
catch( final Throwable throwable ) { throwable.printStackTrace(); }
return null;
}
/**
* Create Proxy class.
*
* @param classname name of class
* @return the proxy class
*/
protected static ClassType createProxyType( final String classname )
{
final ClassType proxy = new ClassType( classname );
proxy.setModifiers( Access.PUBLIC | /*ACC_SUPER*/ 0x0020 |
Access.FINAL );
proxy.setSuper( BASE_CLASS );
return proxy;
}
/**
* generate the list of Interfaces class implements.
*
* @param proxy the proxy class
* @param interfaces[] the interfaces to add
*/
protected static void generateInterfaces( final ClassType proxy,
final Class[] interfaces )
{
final ClassType[] interfaceTypes = new ClassType[ interfaces.length ];
for( int i = 0; i < interfaceTypes.length; i++ )
{
interfaceTypes[ i ] = (ClassType)Type.getType( interfaces[ i
].getName() );
}
proxy.setInterfaces( interfaceTypes );
}
/**
* Generate code for wrapper method.
*
* @param proxy the class to add to
* @param target the class wrapping
* @param method the method to wrap
*/
protected static void generateMethod( final ClassType proxy,
final ClassType target,
final Method method )
{
final Class[] parameters = method.getParameterTypes();
final Type[] parameterTypes = new Type[ parameters.length ];
for( int i = 0; i < parameterTypes.length; i++ )
{
parameterTypes[ i ] = Type.getType( parameters[ i ].getName() );
}
final Type returnType =
Type.getType( method.getReturnType().getName() );
final gnu.bytecode.Method newMethod =
proxy.addMethod( method.getName(),
Access.PUBLIC,
parameterTypes,
returnType );
newMethod.init_param_slots();
newMethod.pushScope();
final CodeAttr code = newMethod.getCode();
//put m_core on stack;
final Field field = proxy.getField( "m_core" );
code.emitPushThis();
code.emitGetField( field );
for( int i = 0; i < parameterTypes.length; i++ )
{
code.emitLoad( code.getArg( 1 + i ) );
}
//call target method
final gnu.bytecode.Method targetMethod =
target.getMethod( method.getName(), parameterTypes );
code.emitInvokeVirtual( targetMethod );
//return
code.emitReturn();
newMethod.popScope();
}
/**
* Generate constructor code and field data.
*
* @param proxy the representation of class so far
* @param target the type that is wrapped
*/
protected static void generateBase( final ClassType proxy,
final Type target )
{
final Field field = proxy.addField( "m_core", target );
field.flags |= Access.PRIVATE;
final gnu.bytecode.Method constructor =
proxy.addMethod( "<init>",
Access.PUBLIC,
new Type[] { target },
Type.void_type );
final gnu.bytecode.Method superConstructor
= proxy.getSuperclass().addMethod( "<init>",
Access.PUBLIC,
null,
Type.void_type );
constructor.init_param_slots();
constructor.pushScope();
final CodeAttr code = constructor.getCode();
//super();
code.emitPushThis();
code.emitInvokeSpecial( superConstructor );
//m_core = param1;
code.emitPushThis();
code.emitLoad( code.getArg( 1 ) );
code.emitPutField( field );
//return
code.emitReturn();
constructor.popScope();
}
/**
* Determine the methods that must be implemented to
* implement interface, eliminating duplicates.
*
* @param interfaces[] the interfaces to extract methods from
* @return methods
*/
protected static HashMap determineMethods( final Class[] interfaces )
{
final HashMap methodSet = new HashMap();
final StringBuffer sb = new StringBuffer();
for( int i = 0; i < interfaces.length; i++ )
{
if( DEBUG )
{
LOGGER.debug( "Scanning interface " + interfaces[ i
].getName() +
" for methods" );
}
final Method[] methods = interfaces[ i ].getMethods();
//for each method generate a pseudo signature
//Add the method to methodSet under that signature.
//This is to ensure that only one version of a method is
//entered into set even if multiple interfaces declare it
for( int j = 0; j < methods.length; j++ )
{
sb.append( methods[ j ].getName() );
sb.append( '(' );
final Class[] parameters = methods[ j ].getParameterTypes();
for( int k = 0; k < parameters.length; k++ )
{
sb.append( parameters[ k ].getName() );
sb.append( ' ' );
}
sb.append( ";)" );
if( DEBUG )
{
LOGGER.debug( "Found method with pseudo-signature " + sb
);
}
methodSet.put( sb.toString(), methods[ j ] );
sb.setLength( 0 );
}
}
return methodSet;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/StringUtil.java
Index: StringUtil.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 file.
*/
package org.apache.avalon.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
import org.apache.avalon.CascadingThrowable;
/**
* This class provides basic facilities for manipulating strings.
*
* Some exception handling stuff thieved from Turbine...
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Rafal Krzewski</a>
*/
public final class StringUtil
{
/**
* Private constructor to prevent instantiation.
*/
private StringUtil()
{
}
/**
* Replace substrings of one string with another string and return
altered string.
*
* @param original input string
* @param oldString the substring section to replace
* @param newString the new substring replacing old substring section
* @return converted string
*/
public static String replaceSubString( final String original,
final String oldString,
final String newString )
{
final StringBuffer sb = new StringBuffer();
int end = original.indexOf( oldString );
int start = 0;
final int stringSize = oldString.length();
while( end != -1 )
{
sb.append( original.substring( start, end ) );
sb.append( newString );
start = end + stringSize;
end = original.indexOf( oldString, start );
}
end = original.length();
sb.append( original.substring( start, end ) );
return sb.toString();
}
public static String printStackTrace( final Throwable throwable )
{
return printStackTrace( throwable, 0, true );
}
public static String printStackTrace( final Throwable throwable,
final boolean printCascading )
{
return printStackTrace( throwable, 0, printCascading );
}
public static String printStackTrace( final Throwable throwable, int
depth )
{
final String[] lines = captureStackTrace( throwable );
if( 0 == depth || depth > lines.length ) depth = lines.length;
final StringBuffer sb = new StringBuffer();
for( int i = 0; i < depth; i++ )
{
sb.append( lines[ i ] );
sb.append( '\n' );
}
return sb.toString();
}
public static String printStackTrace( Throwable throwable,
final int depth,
final boolean printCascading )
{
final String result = printStackTrace( throwable, depth );
if( !printCascading || !(throwable instanceof CascadingThrowable) )
{
return result;
}
else
{
final StringBuffer sb = new StringBuffer();
sb.append( result );
throwable = ((CascadingThrowable)throwable).getCause();
while( null != throwable )
{
sb.append( "rethrown from\n" );
sb.append( printStackTrace( throwable, depth ) );
if( throwable instanceof CascadingThrowable )
{
throwable = ((CascadingThrowable)throwable).getCause();
}
else
{
throwable = null;
}
}
return sb.toString();
}
}
/**
* Captures the stack trace associated with this exception.
*
* @return an array of Strings describing stack frames.
*/
public static String[] captureStackTrace( final Throwable throwable )
{
final StringWriter sw = new StringWriter();
throwable.printStackTrace( new PrintWriter( sw, true ) );
return splitString( sw.toString(), "\n" );
}
/**
* Splits the string on every token into an array of stack frames.
*
* @param string the string
* @param onToken the token
* @return the resultant array
*/
public static String[] splitString( final String string, final String
onToken )
{
final StringTokenizer tokenizer = new StringTokenizer( string,
onToken );
final ArrayList lines = new ArrayList();
while( tokenizer.hasMoreTokens() )
{
lines.add( tokenizer.nextToken() );
}
return (String[])lines.toArray( new String[ 0 ] );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/ValuedEnum.java
Index: ValuedEnum.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 file.
*/
package org.apache.avalon.util;
/**
* Basic enum class for type-safe enums with values. Should be used as an
abstract base.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class ValuedEnum
extends Enum
{
protected final int m_value;
public ValuedEnum( final String name, final int value )
{
super( name );
m_value = value;
}
public final int getValue()
{
return m_value;
}
public final boolean isEqualTo( final ValuedEnum enum )
{
return m_value == enum.m_value;
}
public final boolean isGreaterThan( final ValuedEnum enum )
{
return m_value > enum.m_value;
}
public final boolean isGreaterThanOrEqual( final ValuedEnum enum )
{
return m_value >= enum.m_value;
}
public final boolean isLessThan( final ValuedEnum enum )
{
return m_value < enum.m_value;
}
public final boolean isLessThanOrEqual( final ValuedEnum enum )
{
return m_value <= enum.m_value;
}
public String toString()
{
return getClass().getName() + "[" + m_name + "=" + m_value + "]";
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/Version.java
Index: Version.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 file.
*/
package org.apache.avalon.util;
/**
* This document is NOT RIGHT.
* <p />
*
* The version number of a <code>Block</code> is made up of three
* dot-separated fields:
* <p />
* "<b>major.minor.patchlevel</b>"
* <p />
* and (optionally) by a fourth field (always <b>"-dev"</b>)
* specifying that this version is under development.
* <p />
* The <b>major</b>, <b>minor</b> and <b>patchlevel</b> fields are
* <i>integer</i> numbers represented in decimal notation and have the
* following meaning:
* <ul>
* <p /><li><b>major</b> - When the major version changes (in ex. from
* "1.5.12" to "2.0.0"), then backward compatibility
* with previous releases is not granted (this usually happens this
* <code>Block</code> is implementing a new major version of an interface
* specified in <b>org.apache.avalon.blocks</b> package).
* </li><p />
* <p /><li><b>minor</b> - When the minor version changes (in ex. from
* "1.5.12" to "1.6.0"), then backward compatibility
* with previous releases is granted, but something changed in the
* implementation (in ex. new features were added, the configuration
* syntax may be different, or the <code>Block</code> is implementing a
* new minor version of an interface specified in
* <b>org.apache.avalon.blocks</b> package).
* </li><p />
* <p /><li><b>patchlevel</b> - When the patchlevel version changes (in ex.
* from "1.5.12" to "1.5.13"), then the only changed
* things are fixes in the code implementation, but no new features or
* changes were made to the behaviour of the code.
* </li>
* </ul>
* <p />
* The fourth field, optional and always "<b>-dev</b>" (in ex.
* "1.5.12-dev") specifies that current <code>Block</code>
* implementation is under development, and so may contain not-working
* code or not all features were implemented.
* <p />
* <p />
* <b>NOTE: The absence of the "-dev" tag does not endorse
* any warranty of particular stability, safety or compliancy.
* The only source for such informations is the (usually provided) license
* file accompaining the block itself.</b>
*
* The class defining versioning pattern.
* <p />
* <p />
* Any interface in <b>org.apache.avalon.blocks</b> package <b>MUST</b>
provides
* a Version instance containing versioning informations on this interface.<p
/>
* Any BlockInfo returned by a Block implementation <b>MUST</b> provides a
* Version instances containing versioning informations on this
implementation.
* <p /><p />
* Version numbers are:<p />
* "<b>major.minor.revision.dev</b>"
* <p />
* The <b>major</b> , <b>minor</b> and <b>revision</b>fields are
<i>integer</i>
* numbers represented in decimal notation and have the following meaning:
* <ul><b> - Refering to an interface</b>
* <ul>
* <li><b>major</b> - When the major version changes (in ex. from
* "1.5" to "2.0"), then backward compatibility with
* previous releases is not granted.
* </li><p />
* <p /><li><b>minor</b> - When the minor version changes (in ex. from
* "1.5" to "1.6"), then backward compatibility
* with previous releases is granted, but something changed in the
* interface (in ex. new methods were added).
* </li><p />
* <li><b>revision</b> - When refering to an interface may represent a change
* in documentation or other minor changes. If some methods are modified a
minor
* version changes is needed.<p />
* - When refering to a Block implementation this represent minor changes in
* implementation like bugs fix.
* </li><p />
* <li><b>dev</b> - The boolean dev field specify if this Block or interface
* is under development and not yet approved by the Java Apache
org.apache.avalon.interfaces;
* developers group (mailing-list).
* </li><p />
* </ul>
* </ul>
* <ul><b> - Refering to a Block</b>
* <ul>
* <li><b>major</b> - When the major version changes (in ex. from
* "1.5" to "2.0"), then backward compatibility with
* previous releases is not granted.
* </li><p />
* <p /><li><b>minor</b> - When the minor version changes (in ex. from
* "1.5" to "1.6"), then backward compatibility
* with previous releases is granted, but something changed in the
* interface (in ex. new methods were added).
* </li><p />
* <li><b>revision</b> - When refering to an interface may represent a change
* in documentation or other minor changes. If some methods are modified a
minor
* version changes is needed.<p />
* - When refering to a Block implementation this represent minor changes in
* implementation like bugs fix.
* </li><p />
* <li><b>dev</b> - The boolean dev field specify if this Block or interface
* is under development and not yet approved by the Java Apache
org.apache.avalon.interfaces;
* developers group (mailing-list).
* </li><p />
* </ul>
* </ul>
* The third field, optional and always "<b>-dev</b>" (in ex.
* "1.5-dev") specifies that the interface is currently under
* development, or it was not yet approved by the Java Apache
org.apache.avalon.interfaces;
* developers group (mailing-list) and so, not yet integrated with the
* org.apache.avalon.interfaces; distributions.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Pierpaolo Fumagalli</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Roberto Lo Giacco</a>
* @author <a href="http://java.apache.org/">Java Apache Project</a>
*/
public final class Version
{
protected int m_major;
protected int m_minor;
protected int m_revision;
/**
* Create a new instance of a <code>Version</code> object with the
* specified version numbers.
*
* @param major This <code>Version</code> major number.
* @param minor This <code>Version</code> minor number.
* @param rev This <code>Version</code> revision number.
*/
public Version( final int major, final int minor, final int revision )
{
m_major = major;
m_minor = minor;
m_revision = revision;
}
/**
* Check this <code>Version</code> against another for equality.
* <p />
* If this <code>Version</code> is compatible with the specified one, then
* <b>true</b> is returned, otherwise <b>false</b>.
*
* @param other The other <code>Version</code> object to be compared with
this
* for equality.
*/
public boolean equals( final Version other )
{
if( m_major != other.m_major) return false;
else if( m_minor != other.m_minor) return false;
else if( m_revision != other.m_revision ) return false;
else return true;
}
/**
* Check this <code>Version</code> against another for compliancy
* (compatibility).
* <p />
* If this <code>Version</code> is compatible with the specified one, then
* <b>true</b> is returned, otherwise <b>false</b>. Be careful when using
* this method since, in example, version 1.3.7 is compliant to version
* 1.3.6, while the opposite is not.
*
* @param v The other <code>Version</code> object to be compared with this
* for compliancy (compatibility).
*/
public boolean complies( final Version other )
{
if( m_major != other.m_major) return false;
else if( m_minor < other.m_minor) return false;
else return true;
}
/**
* Overload toString to report version correctly.
*
* @return the dot seperated version string
*/
public String toString()
{
return m_major + "." + m_minor + "." + m_revision;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/cli/AbstractMain.java
Index: AbstractMain.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 file.
*/
package org.apache.avalon.util.cli;
import java.util.List;
import org.apache.avalon.AbstractLoggable;
/**
* Abstract main entry point.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class AbstractMain
extends AbstractLoggable
{
protected CLOptionDescriptor[] m_options;
/**
* Return string describing how command is executed.
*
* @return the string describing exectution command
*/
protected String getExecutionCommand()
{
return "java " + getClass().getName() + " [options]";
}
/**
* Display usage report.
*
*/
protected void usage()
{
System.out.println( getExecutionCommand() );
System.out.println( "\tAvailable options:");
System.out.println( CLUtil.describeOptions( m_options ) );
}
/**
* Initialise the options for command line parser.
*
*/
protected abstract CLOptionDescriptor[] createCLOptions();
/**
* Main entry point.
*
* @param args[] the command line arguments
* @Throwable Throwable if an error occurs
*/
public void execute( final String[] args )
throws Exception
{
m_options = createCLOptions();
final CLArgsParser parser = new CLArgsParser( args, m_options );
if( null != parser.getErrorString() )
{
System.err.println( "Error: " + parser.getErrorString() );
return;
}
execute( parser.getArguments() );
}
/**
* Overide this method to provide functionality for your application.
*
* @param clOptions the list of command line options
*/
protected abstract void execute( final List clOptions )
throws Exception;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/cli/AbstractParserControl.java
Index: AbstractParserControl.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 file.
*/
package org.apache.avalon.util.cli;
/**
* Class to inherit from so when in future when new controls are added
* clients will no have to implement them.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class AbstractParserControl
implements ParserControl
{
public boolean isFinished( int lastOptionCode )
{
return false;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/cli/CLArgsParser.java
Index: CLArgsParser.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 file.
*/
package org.apache.avalon.util.cli;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Vector;
/**
* Parser for command line arguments.
*
* This parses command lines according to the standard (?) of
* gnu utilities.
*
* Note: This is still used in 1.1 libraries so do not add 1.2+ dependancies.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class CLArgsParser
{
protected class Token
{
protected final int m_type;
protected final String m_value;
public Token( final int type, final String value )
{
m_type = type;
m_value = value;
}
public String getValue()
{
return m_value;
}
public int getType()
{
return m_type;
}
public String toString()
{
return "" + m_type + ":" + m_value;
}
}
private final static int STATE_NORMAL = 0;
private final static int STATE_REQUIRE_2ARGS = 1;
private final static int STATE_REQUIRE_ARG = 2;
private final static int STATE_OPTIONAL_ARG = 3;
private final static int STATE_NO_OPTIONS = 4;
private final static int STATE_OPTION_MODE = 5;
protected final static int TOKEN_SEPERATOR = 0;
protected final static int TOKEN_STRING = 1;
protected final static char[] ARG2_SEPERATORS =
new char[] { (char)0, '=', '-' };
protected final static char[] ARG_SEPERATORS =
new char[] { (char)0, '=' };
protected final static char[] NULL_SEPERATORS =
new char[] { (char)0 };
protected final CLOptionDescriptor[] m_optionDescriptors;
protected final Vector m_options;
protected final ParserControl m_control;
protected String m_errorMessage;
protected String[] m_unparsedArgs = new
String[] {};
//variables used while parsing options.
protected char ch;
protected String[] args;
protected boolean isLong;
protected int argIndex;
protected int stringIndex;
protected int stringLength;
//cached character == Integer.MAX_VALUE when invalid
protected final static int INVALID =
Integer.MAX_VALUE;
protected int m_lastChar = INVALID;
protected int m_lastOptionId;
protected CLOption m_option;
protected int m_state = STATE_NORMAL;
public String[] getUnparsedArgs()
{
return m_unparsedArgs;
}
/**
* Retrieve a list of options that were parsed from command list.
*
* @return the list of options
*/
public Vector getArguments()
{
//System.out.println( "Arguments: " + m_options );
return m_options;
}
/**
* Get Descriptor for option id.
*
* @param id the id
* @return the descriptor
*/
private CLOptionDescriptor getDescriptorFor( final int id )
{
for( int i = 0; i < m_optionDescriptors.length; i++ )
{
if( m_optionDescriptors[i].getId() == id )
{
return m_optionDescriptors[i];
}
}
return null;
}
/**
* Retrieve a descriptor by name.
*
* @param name the name
* @return the descriptor
*/
private CLOptionDescriptor getDescriptorFor( final String name )
{
for( int i = 0; i < m_optionDescriptors.length; i++ )
{
if( m_optionDescriptors[i].getName().equals( name ) )
{
return m_optionDescriptors[i];
}
}
return null;
}
/**
* Retrieve an error message that occured during parsing if one existed.
*
* @return the error string
*/
public String getErrorString()
{
//System.out.println( "ErrorString: " + m_errorMessage );
return m_errorMessage;
}
/**
* Requier state to be placed in for option.
*
* @param descriptor the Option Descriptor
* @return the state
*/
private int getStateFor( final CLOptionDescriptor descriptor )
{
int flags = descriptor.getFlags();
if( ( flags & CLOptionDescriptor.ARGUMENTS_REQUIRED_2 ) ==
CLOptionDescriptor.ARGUMENTS_REQUIRED_2 )
{
return STATE_REQUIRE_2ARGS;
}
else if( ( flags & CLOptionDescriptor.ARGUMENT_REQUIRED ) ==
CLOptionDescriptor.ARGUMENT_REQUIRED )
{
return STATE_REQUIRE_ARG;
}
else if( ( flags & CLOptionDescriptor.ARGUMENT_OPTIONAL ) ==
CLOptionDescriptor.ARGUMENT_OPTIONAL )
{
return STATE_OPTIONAL_ARG;
}
else
{
return STATE_NORMAL;
}
}
/**
* Create a parser that can deals with options and parses certain args.
*
* @param args[] the args
* @param optionDescriptors[] the option descriptors
*/
public CLArgsParser( final String[] args,
final CLOptionDescriptor[] optionDescriptors,
final ParserControl control )
{
m_optionDescriptors = optionDescriptors;
m_control = control;
m_options = new Vector();
this.args = args;
try
{
parse();
checkIncompatabilities( m_options );
}
catch( final ParseException pe )
{
m_errorMessage = pe.getMessage();
}
//System.out.println( "Built : " + m_options );
//System.out.println( "From : " + Arrays.asList( args ) );
}
/**
* Check for duplicates of an option.
* It is an error to have duplicates unless appropriate flags is set in
descriptor.
*
* @param arguments the arguments
*/
protected void checkIncompatabilities( final Vector arguments )
throws ParseException
{
final int size = arguments.size();
for( int i = 0; i < size; i++ )
{
final CLOption option = (CLOption)arguments.elementAt( i );
final int id = option.getId();
final CLOptionDescriptor descriptor = getDescriptorFor( id );
//this occurs when id == 0 and user has not supplied a descriptor
//for arguments
if( null == descriptor ) continue;
final int[] incompatable = descriptor.getIncompatble();
checkIncompatable( arguments, incompatable, i );
}
}
protected void checkIncompatable( final Vector arguments,
final int[] incompatable,
final int original )
throws ParseException
{
final int size = arguments.size();
for( int i = 0; i < size; i++ )
{
if( original == i ) continue;
final CLOption option = (CLOption)arguments.elementAt( i );
final int id = option.getId();
final CLOptionDescriptor descriptor = getDescriptorFor( id );
for( int j = 0; j < incompatable.length; j++ )
{
if( id == incompatable[ j ] )
{
final CLOption originalOption =
(CLOption)arguments.elementAt( original );
final int originalId = originalOption.getId();
String message = null;
if( id == originalId )
{
message =
"Duplicate options for " + describeDualOption(
originalId ) +
" found.";
}
else
{
message = "Incompatable options -" +
describeDualOption( id ) + " and " +
describeDualOption( originalId ) + " found.";
}
throw new ParseException( message, 0 );
}
}
}
}
protected String describeDualOption( final int id )
{
final CLOptionDescriptor descriptor = getDescriptorFor( id );
if( null == descriptor ) return "<parameter>";
else
{
final StringBuffer sb = new StringBuffer();
boolean hasCharOption = false;
if( Character.isLetter( (char)id ) )
{
sb.append( '-' );
sb.append( (char)id );
hasCharOption = true;
}
final String longOption = descriptor.getName();
if( null != longOption )
{
if( hasCharOption ) sb.append( '/' );
sb.append( "--" );
sb.append( longOption );
}
return sb.toString();
}
}
/**
* Create a parser that can deals with options and parses certain args.
*
* @param args[] the args
* @param optionDescriptors[] the option descriptors
*/
public CLArgsParser( final String[] args,
final CLOptionDescriptor[] optionDescriptors )
{
this( args, optionDescriptors, null );
}
/**
* Create a string array that is subset of input array.
* The sub-array should start at array entry indicated by index. That
array element
* should only include characters from charIndex onwards.
*
* @param array[] the original array
* @param index the cut-point in array
* @param charIndex the cut-point in element of array
* @return the result array
*/
protected String[] subArray( final String[] array,
final int index,
final int charIndex )
{
final int remaining = array.length - index;
final String[] result = new String[ remaining ];
if( remaining > 1 )
{
System.arraycopy( array, index + 1, result, 1, remaining - 1 );
}
result[0] = array[ index ].substring( charIndex - 1 );
return result;
}
/**
* Actually parse arguments
*
* @param args[] arguments
*/
protected void parse()
throws ParseException
{
if( 0 == args.length ) return;
stringLength = args[ argIndex ].length();
//ch = peekAtChar();
while( true )
{
ch = peekAtChar();
if( argIndex >= args.length ) break;
if( null != m_control && m_control.isFinished( m_lastOptionId ) )
{
//this may need mangling due to peeks
m_unparsedArgs = subArray( args, argIndex, stringIndex );
return;
}
//System.out.println( "State=" + m_state );
//System.out.println( "Char=" + (char)ch );
if( STATE_OPTION_MODE == m_state )
{
//if get to an arg barrier then return to normal mode
//else continue accumulating options
if( 0 == ch )
{
getChar(); //strip the null
m_state = STATE_NORMAL;
}
else parseShortOption();
}
else if( STATE_NORMAL == m_state )
{
parseNormal();
}
else if( STATE_NO_OPTIONS == m_state )
{
//should never get to here when stringIndex != 0
addOption( new CLOption( args[ argIndex++ ] ) );
}
else if( STATE_OPTIONAL_ARG == m_state && '-' == ch )
{
m_state = STATE_NORMAL;
addOption( m_option );
}
else
{
parseArguments();
}
}
if( m_option != null )
{
if( STATE_OPTIONAL_ARG == m_state )
{
m_options.addElement( m_option );
}
else if( STATE_REQUIRE_ARG == m_state )
{
final CLOptionDescriptor descriptor = getDescriptorFor(
m_option.getId() );
final String message =
"Missing argument to option " + getOptionDescription(
descriptor );
throw new ParseException( message, 0 );
}
else if( STATE_REQUIRE_2ARGS == m_state )
{
if( 1 == m_option.getArgumentCount() )
{
m_option.addArgument( "" );
m_options.addElement( m_option );
}
else
{
final CLOptionDescriptor descriptor = getDescriptorFor(
m_option.getId() );
final String message =
"Missing argument to option " + getOptionDescription(
descriptor );
throw new ParseException( message, 0 );
}
}
else
{
throw new ParseException( "IllegalState " + m_state + ": " +
m_option, 0 );
}
}
}
protected final String getOptionDescription( final CLOptionDescriptor
descriptor )
{
if( isLong ) return "--" + descriptor.getName();
else return "-" + (char)descriptor.getId();
}
protected final char peekAtChar()
{
if( INVALID == m_lastChar ) m_lastChar = readChar();
return (char)m_lastChar;
}
protected final char getChar()
{
if( INVALID != m_lastChar )
{
final char result = (char)m_lastChar;
m_lastChar = INVALID;
return result;
}
else return readChar();
}
private final char readChar()
{
if( stringIndex >= stringLength )
{
argIndex++;
stringIndex = 0;
if( argIndex < args.length ) stringLength = args[ argIndex
].length();
else stringLength = 0;
return 0;
}
if( argIndex >= args.length ) return 0;
return args[ argIndex ].charAt( stringIndex++ );
}
protected final Token nextToken( final char[] seperators )
{
ch = getChar();
if( isSeperator( ch, seperators ) )
{
ch = getChar();
return new Token( TOKEN_SEPERATOR, null );
}
final StringBuffer sb = new StringBuffer();
do
{
sb.append( ch );
ch = getChar();
}
while( !isSeperator( ch, seperators ) );
return new Token( TOKEN_STRING, sb.toString() );
}
private final boolean isSeperator( final char ch, final char[] seperators
)
{
for( int i = 0; i < seperators.length; i++ )
{
if( ch == seperators[ i ] ) return true;
}
return false;
}
protected void addOption( final CLOption option )
{
m_options.addElement( option );
m_lastOptionId = option.getId();
m_option = null;
}
protected void parseOption( final CLOptionDescriptor descriptor,
final String optionString )
throws ParseException
{
if( null == descriptor )
{
throw new ParseException( "Unknown option " + optionString, 0 );
}
m_state = getStateFor( descriptor );
m_option = new CLOption( descriptor.getId() );
if( STATE_NORMAL == m_state ) addOption( m_option );
}
protected void parseShortOption()
throws ParseException
{
ch = getChar();
final CLOptionDescriptor descriptor = getDescriptorFor( (int)ch );
isLong = false;
parseOption( descriptor, "-" + ch );
if( STATE_NORMAL == m_state ) m_state = STATE_OPTION_MODE;
}
protected boolean parseArguments()
throws ParseException
{
if( STATE_REQUIRE_ARG == m_state )
{
if( '=' == ch || 0 == ch ) getChar();
final Token token = nextToken( NULL_SEPERATORS );
m_option.addArgument( token.getValue() );
addOption( m_option );
m_state = STATE_NORMAL;
}
else if( STATE_REQUIRE_2ARGS == m_state )
{
if( 0 == m_option.getArgumentCount() )
{
final Token token = nextToken( ARG_SEPERATORS );
if( TOKEN_SEPERATOR == token.getType() )
{
final CLOptionDescriptor descriptor = getDescriptorFor(
m_option.getId() );
final String message =
"Unable to parse first argument for option " +
getOptionDescription( descriptor );
throw new ParseException( message, 0 );
}
else
{
m_option.addArgument( token.getValue() );
}
}
else //2nd argument
{
final StringBuffer sb = new StringBuffer();
ch = getChar();
if( '-' == ch ) m_lastChar = ch;
while( !isSeperator( ch, ARG2_SEPERATORS ) )
{
sb.append( ch );
ch = getChar();
}
final String argument = sb.toString();
//System.out.println( "Arguement:" + argument );
m_option.addArgument( argument );
addOption( m_option );
m_option = null;
m_state = STATE_NORMAL;
}
}
return true;
}
/**
* Parse Options from Normal mode.
*/
protected void parseNormal()
throws ParseException
{
if( '-' != ch )
{
//Parse the arguments that are not options
final String argument = nextToken( NULL_SEPERATORS ).getValue();
addOption( new CLOption( argument ) );
m_state = STATE_NORMAL;
}
else
{
getChar(); // strip the -
if( 0 == peekAtChar() )
{
throw new ParseException( "Malformed option -", 0 );
}
else
{
ch = peekAtChar();
//if it is a short option then parse it else ...
if( '-' != ch ) parseShortOption();
else
{
getChar(); // strip the -
//-- sequence .. it can either mean a change of state
//to STATE_NO_OPTIONS or else a long option
if( 0 == peekAtChar() )
{
getChar();
m_state = STATE_NO_OPTIONS;
}
else
{
//its a long option
final String optionName = nextToken( ARG_SEPERATORS
).getValue();
final CLOptionDescriptor descriptor =
getDescriptorFor( optionName );
isLong = true;
parseOption( descriptor, "--" + optionName );
}
}
}
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/cli/CLOption.java
Index: CLOption.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 file.
*/
package org.apache.avalon.util.cli;
import java.util.Arrays;
/**
* Basic class describing an instance of option.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class CLOption
{
protected final int m_id;
protected String[] m_arguments;
/**
* Retrieve argument to option if it takes arguments.
*
* @return the argument
*/
public final String getArgument()
{
return getArgument( 0 );
}
/**
* Retrieve argument to option if it takes arguments.
*
* @return the argument
*/
public final String getArgument( final int index )
{
if( null == m_arguments || index < 0 || index >= m_arguments.length )
{
return null;
}
else return m_arguments[ index ];
}
/**
* Retrieve id of option.
*
* The id is eqivelent to character code if it can be a single letter
option.
*
* @return the id
*/
public final int getId()
{
return m_id;
}
/**
* Constructor taking an id (that must be a proper character code)
*
* @param id the new id
*/
public CLOption( final int id )
{
m_id = id;
}
/**
* Constructor taking argument for option.
*
* @param argument the argument
*/
public CLOption( final String argument )
{
this( 0 );
addArgument( argument );
}
/**
* Mutator fo Argument property.
*
* @param argument the argument
*/
public final void addArgument( final String argument )
{
if( null == m_arguments ) m_arguments = new String[] { argument };
else
{
final String[] arguments = new String[ m_arguments.length + 1 ];
System.arraycopy( m_arguments, 0, arguments, 0,
m_arguments.length );
arguments[ m_arguments.length ] = argument;
m_arguments = arguments;
}
}
public int getArgumentCount()
{
if( null == m_arguments ) return 0;
else return m_arguments.length;
}
/**
* Convert to String.
*
* @return the string value
*/
public String toString()
{
final StringBuffer sb = new StringBuffer();
sb.append( "[Option " );
sb.append( (char)m_id );
if( null != m_arguments )
{
sb.append( ", " );
sb.append( Arrays.asList( m_arguments ) );
}
sb.append( " ]" );
return sb.toString();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/cli/CLOptionDescriptor.java
Index: CLOptionDescriptor.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 file.
*/
package org.apache.avalon.util.cli;
/**
* Basic class describing an type of option.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class CLOptionDescriptor
{
public final static int ARGUMENT_REQUIRED = 1 <<
1;
public final static int ARGUMENT_OPTIONAL = 1 <<
2;
public final static int ARGUMENT_DISALLOWED = 1 <<
3;
public final static int ARGUMENTS_REQUIRED_2 = 1 <<
4;
protected final int m_id;
protected final int m_flags;
protected final String m_name;
protected final String m_description;
protected final int[] m_incompatable;
/**
* Constructor.
*
* @param name the name/long option
* @param flags the flags
* @param id the id/character option
* @param description description of option usage
*/
public CLOptionDescriptor( final String name,
final int flags,
final int id,
final String description )
{
this( name, flags, id, description, new int[] { id } );
}
/**
* Constructor.
*
* @param name the name/long option
* @param flags the flags
* @param id the id/character option
* @param description description of option usage
*/
public CLOptionDescriptor( final String name,
final int flags,
final int id,
final String description,
final int[] incompatable )
{
m_id = id;
m_name = name;
m_flags = flags;
m_description = description;
m_incompatable = incompatable;
}
protected int[] getIncompatble()
{
return m_incompatable;
}
/**
* Retrieve textual description.
*
* @return the description
*/
public final String getDescription()
{
return m_description;
}
/**
* Retrieve flags about option.
* Flags include details such as whether it allows parameters etc.
*
* @return the flags
*/
public final int getFlags()
{
return m_flags;
}
/**
* Retrieve the id for option.
* The id is also the character if using single character options.
*
* @return the id
*/
public final int getId()
{
return m_id;
}
/**
* Retrieve name of option which is also text for long option.
*
* @return name/long option
*/
public final String getName()
{
return m_name;
}
/**
* Convert to String.
*
* @return the converted value to string.
*/
public String toString()
{
return
"[OptionDescriptor " + m_name +
", " + m_id + ", " + m_flags +
", " + m_description + " ]";
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/cli/CLUtil.java
Index: CLUtil.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 file.
*/
package org.apache.avalon.util.cli;
/**
* CLUtil offers basic utility operations for use both internal and external
to package.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class CLUtil
{
protected static int MAX_DESCRIPTION_COLUMN_LENGTH = 60;
/**
* Format options into StringBuffer and return.
*
* @param options[] the option descriptors
* @return the formatted description/help for options
*/
public static StringBuffer describeOptions( final CLOptionDescriptor[]
options )
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < options.length; i++)
{
final char ch = (char) options[i].getId();
final String name = options[i].getName();
String description = options[i].getDescription();
boolean needComma = false;
sb.append('\t');
if( Character.isLetter(ch) )
{
sb.append("-");
sb.append(ch);
needComma = true;
}
if (null != name)
{
if( needComma ) sb.append(", ");
sb.append("--");
sb.append(name);
sb.append('\n');
}
if( null != description )
{
while( description.length() > MAX_DESCRIPTION_COLUMN_LENGTH )
{
final String descriptionPart =
description.substring( 0,
MAX_DESCRIPTION_COLUMN_LENGTH );
description =
description.substring( MAX_DESCRIPTION_COLUMN_LENGTH
);
sb.append( "\t\t" );
sb.append( descriptionPart );
sb.append( '\n' );
}
sb.append( "\t\t" );
sb.append( description );
sb.append( '\n' );
}
}
return sb;
}
/**
* Private Constructor so that no instance can ever be created.
*
*/
private CLUtil()
{
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/cli/ParserControl.java
Index: ParserControl.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 file.
*/
package org.apache.avalon.util.cli;
/**
* ParserControl is used to control particular behaviour of the parser.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface ParserControl
{
boolean isFinished( int lastOptionCode );
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/cli/test/ClutilTestlet.java
Index: ClutilTestlet.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 file.
*/
package org.apache.avalon.util.cli.test;
import java.util.List;
import org.apache.avalon.util.cli.AbstractParserControl;
import org.apache.avalon.util.cli.CLArgsParser;
import org.apache.avalon.util.cli.CLOption;
import org.apache.avalon.util.cli.CLOptionDescriptor;
import org.apache.avalon.util.cli.ParserControl;
import org.apache.testlet.AbstractTestlet;
/**
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class ClutilTestlet
extends AbstractTestlet
{
protected final static String[] ARGLIST1 =
{
"--you","are","--all","-cler","kid"
};
protected final static String[] ARGLIST2 =
{
"-Dstupid=idiot","are","--all","here"
};
protected final static String[] ARGLIST3 =
{
//duplicates
"-Dstupid=idiot","are","--all","--all","here"
};
protected final static String[] ARGLIST4 =
{
//incompatable (blee/all)
"-Dstupid=idiot","are","--all","--blee","here"
};
protected final static String[] ARGLIST5 =
{
"-f","myfile.txt"
};
private static final int DEFINE_OPT = 'D';
private static final int YOU_OPT = 'y';
private static final int ALL_OPT = 'a';
private static final int CLEAR1_OPT = 'c';
private static final int CLEAR2_OPT = 'l';
private static final int CLEAR3_OPT = 'e';
private static final int CLEAR5_OPT = 'r';
private static final int BLEE_OPT = 'b';
private static final int FILE_OPT = 'f';
protected final static CLOptionDescriptor DEFINE =
new CLOptionDescriptor( "define",
CLOptionDescriptor.ARGUMENTS_REQUIRED_2,
DEFINE_OPT,
"define" );
protected final static CLOptionDescriptor YOU =
new CLOptionDescriptor( "you",
CLOptionDescriptor.ARGUMENT_DISALLOWED, YOU_OPT, "you" );
protected final static CLOptionDescriptor ALL =
new CLOptionDescriptor( "all",
CLOptionDescriptor.ARGUMENT_DISALLOWED,
ALL_OPT,
"all",
new int[] { BLEE_OPT } );
protected final static CLOptionDescriptor CLEAR1 =
new CLOptionDescriptor( "c", CLOptionDescriptor.ARGUMENT_DISALLOWED,
CLEAR1_OPT, "c" );
protected final static CLOptionDescriptor CLEAR2 =
new CLOptionDescriptor( "l", CLOptionDescriptor.ARGUMENT_DISALLOWED,
CLEAR2_OPT, "l" );
protected final static CLOptionDescriptor CLEAR3 =
new CLOptionDescriptor( "e", CLOptionDescriptor.ARGUMENT_DISALLOWED,
CLEAR3_OPT, "e" );
protected final static CLOptionDescriptor CLEAR5 =
new CLOptionDescriptor( "r", CLOptionDescriptor.ARGUMENT_DISALLOWED,
CLEAR5_OPT, "r" );
protected final static CLOptionDescriptor BLEE =
new CLOptionDescriptor( "blee",
CLOptionDescriptor.ARGUMENT_DISALLOWED,
BLEE_OPT,
"blee" );
protected final static CLOptionDescriptor FILE =
new CLOptionDescriptor( "file",
CLOptionDescriptor.ARGUMENT_REQUIRED,
FILE_OPT,
"the build file." );
public void testFullParse()
{
final CLOptionDescriptor[] options = new CLOptionDescriptor[]
{
YOU, ALL, CLEAR1, CLEAR2, CLEAR3, CLEAR5
};
final CLArgsParser parser = new CLArgsParser( ARGLIST1, options );
assertNull( parser.getErrorString() );
final List clOptions = parser.getArguments();
final int size = clOptions.size();
assertEquality( size, 8 );
assertEquality( ((CLOption)clOptions.get( 0 )).getId(), YOU_OPT );
assertEquality( ((CLOption)clOptions.get( 1 )).getId(), 0 );
assertEquality( ((CLOption)clOptions.get( 2 )).getId(), ALL_OPT );
assertEquality( ((CLOption)clOptions.get( 3 )).getId(), CLEAR1_OPT );
assertEquality( ((CLOption)clOptions.get( 4 )).getId(), CLEAR2_OPT );
assertEquality( ((CLOption)clOptions.get( 5 )).getId(), CLEAR3_OPT );
assertEquality( ((CLOption)clOptions.get( 6 )).getId(), CLEAR5_OPT );
assertEquality( ((CLOption)clOptions.get( 7 )).getId(), 0 );
}
public void testDuplicateOptions()
{
//"-Dstupid=idiot","are","--all","--all","here"
final CLOptionDescriptor[] options = new CLOptionDescriptor[]
{
DEFINE, ALL, CLEAR1
};
final CLArgsParser parser = new CLArgsParser( ARGLIST3, options );
assertNull( parser.getErrorString() );
final List clOptions = parser.getArguments();
final int size = clOptions.size();
assertEquality( size, 5 );
assertEquality( ((CLOption)clOptions.get( 0 )).getId(), DEFINE_OPT );
assertEquality( ((CLOption)clOptions.get( 1 )).getId(), 0 );
assertEquality( ((CLOption)clOptions.get( 2 )).getId(), ALL_OPT );
assertEquality( ((CLOption)clOptions.get( 3 )).getId(), ALL_OPT );
assertEquality( ((CLOption)clOptions.get( 4 )).getId(), 0 );
}
public void testIncompatableOptions()
{
final CLOptionDescriptor[] options = new CLOptionDescriptor[]
{
DEFINE, ALL, CLEAR1, BLEE
};
final CLArgsParser parser = new CLArgsParser( ARGLIST4, options );
assertNotNull( parser.getErrorString() );
final List clOptions = parser.getArguments();
final int size = clOptions.size();
assertEquality( size, 5 );
assertEquality( ((CLOption)clOptions.get( 0 )).getId(), DEFINE_OPT );
assertEquality( ((CLOption)clOptions.get( 1 )).getId(), 0 );
assertEquality( ((CLOption)clOptions.get( 2 )).getId(), ALL_OPT );
assertEquality( ((CLOption)clOptions.get( 3 )).getId(), BLEE_OPT );
assertEquality( ((CLOption)clOptions.get( 4 )).getId(), 0 );
}
public void testSingleArg()
{
final CLOptionDescriptor[] options = new CLOptionDescriptor[]
{
FILE
};
final CLArgsParser parser = new CLArgsParser( ARGLIST5, options );
assertNull( parser.getErrorString() );
final List clOptions = parser.getArguments();
final int size = clOptions.size();
assertEquality( size, 1 );
assertEquality( ((CLOption)clOptions.get( 0 )).getId(), FILE_OPT );
assertEquality( ((CLOption)clOptions.get( 0 )).getArgument(),
"myfile.txt" );
}
public void test2ArgsParse()
{
//"-Dstupid=idiot","are","--all","here"
final CLOptionDescriptor[] options = new CLOptionDescriptor[]
{
DEFINE, ALL, CLEAR1
};
final CLArgsParser parser = new CLArgsParser( ARGLIST2, options );
assertNull( parser.getErrorString() );
final List clOptions = parser.getArguments();
final int size = clOptions.size();
assertEquality( size, 4 );
assertEquality( ((CLOption)clOptions.get( 0 )).getId(), DEFINE_OPT );
assertEquality( ((CLOption)clOptions.get( 1 )).getId(), 0 );
assertEquality( ((CLOption)clOptions.get( 2 )).getId(), ALL_OPT );
assertEquality( ((CLOption)clOptions.get( 3 )).getId(), 0 );
final CLOption option = (CLOption)clOptions.get( 0 );
assertEquality( "stupid", option.getArgument( 0 ) );
assertEquality( "idiot", option.getArgument( 1 ) );
}
public void testPartParse()
{
final CLOptionDescriptor[] options = new CLOptionDescriptor[]
{
YOU
};
final ParserControl control = new AbstractParserControl()
{
public boolean isFinished( int lastOptionCode )
{
return (lastOptionCode == YOU_OPT);
}
};
final CLArgsParser parser = new CLArgsParser( ARGLIST1, options,
control );
assertNull( parser.getErrorString() );
final List clOptions = parser.getArguments();
final int size = clOptions.size();
assertEquality( size, 1 );
assertEquality( ((CLOption)clOptions.get( 0 )).getId(), YOU_OPT );
}
public void test2PartParse()
{
final CLOptionDescriptor[] options1 = new CLOptionDescriptor[]
{
YOU
};
final CLOptionDescriptor[] options2 = new CLOptionDescriptor[]
{
ALL, CLEAR1, CLEAR2, CLEAR3, CLEAR5
};
final ParserControl control1 = new AbstractParserControl()
{
public boolean isFinished( int lastOptionCode )
{
return (lastOptionCode == YOU_OPT);
}
};
final CLArgsParser parser1 = new CLArgsParser( ARGLIST1, options1,
control1 );
assertNull( parser1.getErrorString() );
final List clOptions1 = parser1.getArguments();
final int size1 = clOptions1.size();
assertEquality( size1, 1 );
assertEquality( ((CLOption)clOptions1.get( 0 )).getId(), YOU_OPT );
final CLArgsParser parser2 =
new CLArgsParser( parser1.getUnparsedArgs(), options2 );
assertNull( parser2.getErrorString() );
final List clOptions2 = parser2.getArguments();
final int size2 = clOptions2.size();
assertEquality( size2, 7 );
assertEquality( ((CLOption)clOptions2.get( 0 )).getId(), 0 );
assertEquality( ((CLOption)clOptions2.get( 1 )).getId(), ALL_OPT );
assertEquality( ((CLOption)clOptions2.get( 2 )).getId(), CLEAR1_OPT );
assertEquality( ((CLOption)clOptions2.get( 3 )).getId(), CLEAR2_OPT );
assertEquality( ((CLOption)clOptions2.get( 4 )).getId(), CLEAR3_OPT );
assertEquality( ((CLOption)clOptions2.get( 5 )).getId(), CLEAR5_OPT );
assertEquality( ((CLOption)clOptions2.get( 6 )).getId(), 0 );
}
public void test2PartPartialParse()
{
final CLOptionDescriptor[] options1 = new CLOptionDescriptor[]
{
YOU, ALL, CLEAR1
};
final CLOptionDescriptor[] options2 = new CLOptionDescriptor[] {};
final ParserControl control1 = new AbstractParserControl()
{
public boolean isFinished( final int lastOptionCode )
{
return (lastOptionCode == CLEAR1_OPT);
}
};
final CLArgsParser parser1 = new CLArgsParser( ARGLIST1, options1,
control1 );
assertNull( parser1.getErrorString() );
final List clOptions1 = parser1.getArguments();
final int size1 = clOptions1.size();
assertEquality( size1, 4 );
assertEquality( ((CLOption)clOptions1.get( 0 )).getId(), YOU_OPT );
assertEquality( ((CLOption)clOptions1.get( 1 )).getId(), 0 );
assertEquality( ((CLOption)clOptions1.get( 2 )).getId(), ALL_OPT );
assertEquality( ((CLOption)clOptions1.get( 3 )).getId(), CLEAR1_OPT );
assert( parser1.getUnparsedArgs()[0].equals("ler") );
final CLArgsParser parser2 =
new CLArgsParser( parser1.getUnparsedArgs(), options2 );
assertNull( parser2.getErrorString() );
final List clOptions2 = parser2.getArguments();
final int size2 = clOptions2.size();
assertEquality( size2, 2 );
assertEquality( ((CLOption)clOptions2.get( 0 )).getId(), 0 );
assertEquality( ((CLOption)clOptions2.get( 1 )).getId(), 0 );
}
public void testDuplicatesFail()
{
final CLOptionDescriptor[] options = new CLOptionDescriptor[]
{
YOU, ALL, CLEAR1, CLEAR2, CLEAR3, CLEAR5
};
//duplicate as
final String[] DUPLICATE_ARGLIST =
{
"--you","are","--all","-clear","kid"
};
final CLArgsParser parser = new CLArgsParser( ARGLIST1, options );
assertNull( parser.getErrorString() );
}
public void testIncomplete2Args()
{
//"-Dstupid="
final CLOptionDescriptor[] options = new CLOptionDescriptor[]
{
DEFINE
};
final CLArgsParser parser = new CLArgsParser( new String[] {
"-Dstupid=" }, options );
assertNull( parser.getErrorString() );
final List clOptions = parser.getArguments();
final int size = clOptions.size();
assertEquality( size, 1 );
final CLOption option = (CLOption)clOptions.get( 0 );
assertEquality( option.getId(), DEFINE_OPT );
assertEquality( option.getArgument( 0 ), "stupid" );
assertEquality( option.getArgument( 1 ), "" );
}
public void testIncomplete2ArgsMixed()
{
//"-Dstupid=","-c"
final CLOptionDescriptor[] options = new CLOptionDescriptor[]
{
DEFINE, CLEAR1
};
final String[] args = new String[] { "-Dstupid=", "-c" };
final CLArgsParser parser = new CLArgsParser( args, options );
assertNull( parser.getErrorString() );
final List clOptions = parser.getArguments();
final int size = clOptions.size();
assertEquality( size, 2 );
assertEquality( ((CLOption)clOptions.get( 1 )).getId(), CLEAR1_OPT );
final CLOption option = (CLOption)clOptions.get( 0 );
assertEquality( option.getId(), DEFINE_OPT );
assertEquality( option.getArgument( 0 ), "stupid" );
assertEquality( option.getArgument( 1 ), "" );
}
public void fail_testIncomplete2ArgsMixedNoEq()
{
//"-Dstupid","-c"
final CLOptionDescriptor[] options = new CLOptionDescriptor[]
{
DEFINE, CLEAR1
};
final String[] args = new String[] { "-Dstupid", "-c" };
final CLArgsParser parser = new CLArgsParser( args, options );
assertNull( parser.getErrorString() );
final List clOptions = parser.getArguments();
final int size = clOptions.size();
assertEquality( size, 2 );
assertEquality( ((CLOption)clOptions.get( 1 )).getId(), CLEAR1_OPT );
final CLOption option = (CLOption)clOptions.get( 0 );
assertEquality( option.getId(), DEFINE_OPT );
assertEquality( option.getArgument( 0 ), "stupid" );
assertEquality( option.getArgument( 1 ), "" );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/i18n/ResourceGroup.java
Index: ResourceGroup.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 file.
*/
package org.apache.avalon.util.i18n;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Random;
import java.util.ResourceBundle;
/**
* A class used to manage resource bundles.
*/
public class ResourceGroup
{
protected final static Random RANDOM = new Random();
protected final HashMap m_bundles = new HashMap();
protected final Locale m_locale;
/**
* Create a ResourceGroup to manage resource bundles for a particular
locale.
*
* @param locale the locale
*/
public ResourceGroup( final Locale locale )
{
m_locale = locale;
}
public Locale getLocale()
{
return m_locale;
}
public String format( final String base, final String key, final Object[]
args )
{
final String pattern = getPattern( base, key );
final MessageFormat messageFormat = new MessageFormat( pattern );
messageFormat.setLocale( m_locale );
return messageFormat.format( args );
}
public ResourceBundle getBundle( final String base )
throws MissingResourceException
{
ResourceBundle result = (ResourceBundle) m_bundles.get( base );
if( null != result ) return result;
// bundle wasn't cached, so load it, cache it, and return it.
final ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
result = ResourceBundle.getBundle( base, m_locale, classLoader );
m_bundles.put( base, result );
return result;
}
public String getPattern( final String base, final String key )
throws MissingResourceException
{
final ResourceBundle bundle = getBundle( base );
final Object object = bundle.getObject( key );
// is the resource a single string
if( object instanceof String )
{
return (String)object;
}
else if( object instanceof String[] )
{
//if string array then randomly pick one
final String[] strings = (String[])object;
return strings[ RANDOM.nextInt( strings.length ) ];
}
else
{
throw new MissingResourceException( "Unable to find resource of
appropriate type.",
"java.lang.String",
key );
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/i18n/XMLResourceBundle.java
Index: XMLResourceBundle.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 file.
*/
package org.apache.avalon.util.i18n;
/**
* @author <a href="mailto:[EMAIL PROTECTED]">Mike Engelhart</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Neeme Praks</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Oleg Podolsky</a>
* @version $Id: XMLResourceBundle.java,v 1.1 2001/02/23 10:47:40 fede Exp $
*/
/** JDK classes **/
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.Hashtable;
import java.util.Locale;
import java.util.MissingResourceException;
/** W3C DOM classes **/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;
/** Xerces classes **/
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xerces.dom.TextImpl;
import org.apache.xerces.parsers.DOMParser;
import org.xml.sax.SAXException;
/** Xalan classes **/
import org.apache.xalan.xpath.XPathSupport;
import org.apache.xalan.xpath.XPath;
import org.apache.xalan.xpath.XPathProcessorImpl;
import org.apache.xalan.xpath.xml.XMLParserLiaisonDefault;
import org.apache.xalan.xpath.xml.PrefixResolverDefault;
import org.apache.xalan.xpath.XObject;
public class XMLResourceBundle {
// Cache for storing string values for existing XPaths
private Hashtable cacheIS = new Hashtable();
// Cache for storing non-existing XPaths
private Hashtable cacheNO = new Hashtable();
private Document resource;
public String bundleName = ""; //used by getLocale()
protected XMLResourceBundle parent = null;
public XMLResourceBundle( Document doc, String name, XMLResourceBundle p
) {
System.out.print( "Constructing XMLResourceBundle: " + name );
if ( p != null )
System.out.println( " --> parent: " + p.bundleName );
else
System.out.println( " --> parent: " + p );
this.resource = doc;
this.bundleName = name;
this.parent = p;
}
public void addToCache( String key, String value ) {
cacheIS.put( key, value );
}
public Document getResource() {
return this.resource;
}
// gets string without throwing an exception, returns empty string instead
public String getStringSimple( String xPathKey ) {
String result = "";
try {
result = getString( xPathKey );
} catch ( MissingResourceException e ) {
// do nothing
}
return result;
}
public String getString( String xPathKey ) throws
MissingResourceException {
if ( cacheIS.containsKey( xPathKey ) )
return ( String ) cacheIS.get( xPathKey );
if ( cacheNO.containsKey( xPathKey ) )
new MissingResourceException( "Unable to locate resource: " +
xPathKey, "XMLResourceBundle", xPathKey );
Node root = this.resource.getDocumentElement();
try {
Node node = XPathAPI.selectSingleNode( root, xPathKey );
if ( node != null ) {
String temp = getTextNodeAsString( node );
addToCache( xPathKey, temp );
return temp;
} else {
if ( this.parent != null )
return this.parent.getString( xPathKey );
else
throw new Exception();
}
} catch ( Exception e ) {
// no nodes returned??
cacheNO.put( xPathKey, "" );
throw new MissingResourceException( "Unable to locate resource: "
+ xPathKey, "XMLResourceBundle", xPathKey );
}
}
public String getString( Node role, String key ) throws
MissingResourceException {
try {
Node node = XPathAPI.selectSingleNode( role, key );
if ( node != null )
return getTextNodeAsString( node );
else
throw new Exception();
} catch ( Exception e ) {
// no nodes returned??
throw new MissingResourceException( "Unable to locate resource: "
+ key, "XMLResourceBundle", key );
}
}
private String getTextNodeAsString( Node node ) throws
MissingResourceException {
node = node.getFirstChild();
if ( node.getNodeType() == Node.TEXT_NODE )
return ( ( TextImpl ) node ).getData();
else
throw new MissingResourceException( "Unable to locate
XMLResourceBundle", "XMLResourceBundleFactory", "" );
}
public Node getRole( String xPath ) {
Node root = resource.getDocumentElement();
try {
Node node = XPathAPI.selectSingleNode( root, xPath );
if ( node != null )
return node;
else
throw new Exception();
} catch ( Exception e ) {
// no nodes returned??
throw new MissingResourceException( "Unable to locate resource: "
+ xPath, "XMLResourceBundle", xPath );
}
}
public Node getRole( Node role, String xPath ) {
try {
Node node = XPathAPI.selectSingleNode( role, xPath );
if ( node != null )
return node;
else
throw new Exception();
} catch ( Exception e ) {
// no nodes returned??
throw new MissingResourceException( "Unable to locate resource: "
+ xPath, "XMLResourceBundle", xPath );
}
}
public XPath createXPath( String str, Node namespaceNode ) throws
SAXException {
XPathSupport xpathSupport = new XMLParserLiaisonDefault();
if ( null == namespaceNode )
throw new SAXException( "A namespace node is required to resolve
prefixes!" );
PrefixResolverDefault prefixResolver = new PrefixResolverDefault( (
namespaceNode.getNodeType() == Node.DOCUMENT_NODE ) ? ( ( Document )
namespaceNode ).getDocumentElement() : namespaceNode );
// Create the XPath object.
XPath xpath = new XPath();
// Create a XPath parser.
XPathProcessorImpl parser = new XPathProcessorImpl( xpathSupport );
parser.initXPath( xpath, str, prefixResolver );
return xpath;
}
public Locale getLocale() {
String bundle = bundleName.substring( 0, bundleName.indexOf( ".xml" )
);
int localeStart = bundle.indexOf( "_" );
if ( localeStart == -1 )
return new Locale( "", "", "" );
bundle = bundle.substring( localeStart + 1 );
localeStart = bundle.indexOf( "_" );
if ( localeStart == -1 )
return new Locale( bundle, "", "" );
String lang = bundle.substring( 0, localeStart );
bundle = bundle.substring( localeStart + 1 );
localeStart = bundle.indexOf( "_" );
if ( localeStart == -1 )
return new Locale( lang, bundle, "" );
String country = bundle.substring( 0, localeStart );
bundle = bundle.substring( localeStart + 1 );
return new Locale( lang, country, bundle );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/i18n/XMLResourceBundleFactory.java
Index: XMLResourceBundleFactory.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 file.
*/
package org.apache.avalon.util.i18n;
/**
* @author <a href="mailto:[EMAIL PROTECTED]">Mike Engelhart</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Neeme Praks</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Oleg Podolsky</a>
* @version $Id: XMLResourceBundleFactory.java,v 1.1 2001/02/23 10:47:40 fede
Exp $
*/
/** JDK classes **/
/** W3C DOM classes **/
/** Xerces-J classes **/
//import java.lang.ref.SoftReference;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Vector;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xerces.dom.TextImpl;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XMLResourceBundleFactory {
protected static Hashtable cache = new Hashtable();
protected static String directory;
protected XMLResourceBundleFactory() {}
public static XMLResourceBundle getBundle( String name ) throws
MissingResourceException {
return getBundle( name, Locale.getDefault() );
}
public static XMLResourceBundle getBundle( String name, Locale loc )
throws MissingResourceException {
return getBundle( name, loc, false );
}
public static XMLResourceBundle getBundle( String name, Locale loc,
boolean cacheAtStartup ) throws MissingResourceException {
XMLResourceBundle parent = null;
String bundleName = getBundleName( name, loc );
// first look in the cache - if there grab it
XMLResourceBundle bundle = getCachedBundle( bundleName );
if ( bundle != null )
return bundle;
// if bundle is not in cache try loading the bundle using the given
name and locale bundleName
Document doc = null;
doc = loadResourceBundle( bundleName );
if ( doc != null ) {
if ( ! loc.getLanguage().equals( "" ) )
parent = getParentBundle( name, loc, cacheAtStartup );
bundle = new XMLResourceBundle( doc, bundleName, parent );
if ( cacheAtStartup )
storeTextElements( bundle, bundle.getResource(), "" );
updateCache( bundleName, bundle );
return bundle;
}
// if the locale's language is "" then we've already tried to load
the default resource and it's not available
while ( ! loc.getLanguage().equals( "" ) ) {
// if the given bundle name is not found, then try loading using
a shortened Locale
loc = getParentLocale( loc );
bundleName = getBundleName( name, loc );
// first look in the cache - if there grab it and return
bundle = getCachedBundle( bundleName );
if ( bundle != null )
return bundle;
// try loading the bundle using the given name and locale
bundleName
doc = loadResourceBundle( bundleName );
if ( doc != null ) {
if ( ! loc.getLanguage().equals( "" ) )
parent = getParentBundle( name, loc, cacheAtStartup );
bundle = new XMLResourceBundle( doc, bundleName, parent );
if ( cacheAtStartup )
storeTextElements( bundle, bundle.getResource(), "" );
updateCache( bundleName, bundle );
return bundle;
}
}
throw new MissingResourceException( "Unable to locate resource: " +
bundleName, "XMLResourceBundleFactory", "" );
}
protected synchronized static XMLResourceBundle getParentBundle( String
name, Locale loc ) {
return getParentBundle( name, loc, false );
}
protected synchronized static XMLResourceBundle getParentBundle( String
name, Locale loc, boolean cacheAtStartup ) {
loc = getParentLocale( loc );
String bundleName = getBundleName( name, loc );
Document doc = loadResourceBundle( bundleName );
XMLResourceBundle bundle = null;
if ( doc != null ) {
if ( ! loc.getLanguage().equals( "" ) )
bundle = getParentBundle( name, loc );
bundle = new XMLResourceBundle( doc, bundleName, bundle );
if ( cacheAtStartup )
storeTextElements( bundle, bundle.getResource(), "" );
updateCache( bundleName, bundle );
}
return bundle;
}
// this method returns the next locale up the parent hierarchy
// e.g.; the parent of new Locale("en","us","mac")
// would be new Locale("en", "us", "");
protected static Locale getParentLocale( Locale loc ) {
if ( loc.getVariant().equals( "" ) ) {
if ( loc.getCountry().equals( "" ) )
loc = new Locale( "", "", "" );
else
loc = new Locale( loc.getLanguage(), "", "" );
} else
loc = new Locale( loc.getLanguage(), loc.getCountry(), "" );
return loc;
}
protected synchronized static XMLResourceBundle getCachedBundle( String
bundleName ) {
/*
SoftReference ref = (SoftReference)(cache.get(bundleName));
if (ref != null)
return (XMLResourceBundle) ref.get();
else
return null;
*/
return ( XMLResourceBundle ) ( cache.get( bundleName ) );
}
protected synchronized static void updateCache( String bundleName,
XMLResourceBundle bundle ) {
cache.put( bundleName, bundle );
}
/* protected static String getBundleName(String name, Locale loc)
{
StringBuffer sb = new StringBuffer(name);
if (! loc.getLanguage().equals(""))
{
sb.append("_");
sb.append(loc.getLanguage());
}
if (! loc.getCountry().equals(""))
{
sb.append("_");
sb.append(loc.getCountry());
}
if (! loc.getVariant().equals(""))
{
sb.append("_");
sb.append(loc.getVariant());
}
// should all the files have an extension of .xml? Seems reasonable
sb.append(".xml");
return sb.toString();
}
*/
protected static String getBundleName( String name, Locale loc ) {
String lang = loc.getLanguage();
StringBuffer sb = new StringBuffer( getDirectory() );
if ( lang.length() > 0 ) sb.append( "/" ).append( lang );
sb.append( "/" ).append( name ).append( ".xml" );
return sb.toString();
}
public static XMLResourceBundle getBundle( String fileName, String
localeName ) throws MissingResourceException {
return getBundle( fileName, new Locale( localeName, localeName ) );
}
public static XMLResourceBundle getBundleFromFilename( String bundleName
) throws MissingResourceException {
return getBundleFromFilename( bundleName, true );
}
public static XMLResourceBundle getBundleFromFilename( String bundleName,
boolean cacheAtStartup ) throws MissingResourceException {
Document doc = null;
doc = loadResourceBundle( getDirectory() + "/" + bundleName );
XMLResourceBundle bundle = getCachedBundle( bundleName );
if ( bundle != null )
return bundle;
if ( doc != null ) {
bundle = new XMLResourceBundle( doc, bundleName, null );
if ( cacheAtStartup )
storeTextElements( bundle, bundle.getResource(), "" );
updateCache( bundleName, bundle );
return bundle;
}
throw new MissingResourceException( "Unable to locate resource: " +
bundleName, "XMLResourceBundleFactory", "" );
}
// Load the XML document based on bundleName
protected static Document loadResourceBundle( String bundleName ) {
try {
DOMParser parser = new DOMParser();
parser.parse( bundleName );
return parser.getDocument();
} catch ( IOException e ) {
return null;
}
catch ( SAXException e ) {
return null;
}
}
public static void setDirectory( String dir ) {
directory = dir;
}
public static String getDirectory() {
return ( directory != null ? directory : "" );
}
// Steps through the bundle tree and stores all text element values
// in bundle's cache, and also stores attributes for all element nodes.
// Parent must be am element-type node.
private static void storeTextElements( XMLResourceBundle bundle, Node
parent, String pathToParent ) {
NodeList children = parent.getChildNodes();
int childnum = children.getLength();
for ( int i = 0; i < childnum; i++ ) {
Node child = children.item( i );
if ( child.getNodeType() == Node.ELEMENT_NODE ) {
String pathToChild = pathToParent + '/' + child.getNodeName();
NamedNodeMap attrs = child.getAttributes();
if ( attrs != null ) {
Node temp = null;
String pathToAttr = null;
int attrnum = attrs.getLength();
for ( int j = 0; j < attrnum; j++ ) {
temp = attrs.item( j );
pathToAttr = "/@" + temp.getNodeName();
bundle.addToCache( pathToChild + pathToAttr,
temp.getNodeValue() );
}
}
String childValue = getTextValue( child );
if ( childValue != null )
bundle.addToCache( pathToChild, childValue );
else
storeTextElements( bundle, child, pathToChild );
}
}
}
private static String getTextValue( Node element ) {
NodeList list = element.getChildNodes();
int listsize = list.getLength();
Node item = null;
String itemValue = null;
for ( int i = 0; i < listsize; i++ ) {
item = list.item( i );
if ( item.getNodeType() != Node.TEXT_NODE ) return null;
itemValue = item.getNodeValue(); if ( itemValue == null ) return
null;
itemValue = itemValue.trim(); if ( itemValue.length() == 0 )
return null;
return itemValue;
}
return null;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/i18n/XPathAPI.java
Index: XPathAPI.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 file.
*/
package org.apache.avalon.util.i18n;
import org.xml.sax.SAXException;
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.apache.xalan.xpath.XPathSupport;
import org.apache.xalan.xpath.XPath;
import org.apache.xalan.xpath.XPathProcessorImpl;
import org.apache.xalan.xpath.xml.XMLParserLiaisonDefault;
import org.apache.xalan.xpath.xml.PrefixResolverDefault;
import org.apache.xalan.xpath.XObject;
/**
* The methods in this class are convenience methods into the
* low-level XPath API. We would like to eventually move these
* methods into the XPath core, but would like to do some peer
* review first to make sure we have it right.
* Please note that these methods execute pure XPaths. They do not
* implement those parts of XPath extended by XSLT, such as the
* document() function). If you want to install XSLT functions, you
* have to use the low-level API.
* These functions tend to be a little slow, since a number of objects must be
* created for each evaluation. A faster way is to precompile the
* XPaths using the low-level API, and then just use the XPaths
* over and over.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Mike Engelhart</a>
* @see http://www.w3.org/TR/xpath
* @version $Id: XPathAPI.java,v 1.1 2001/02/23 10:47:40 fede Exp $
*/
public class XPathAPI {
/**
* Use an XPath string to select a single node. XPath namespace
* prefixes are resolved from the context node, which may not
* be what you want (see the next method).
*
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @return The first node found that matches the XPath, or null.
*/
public static Node selectSingleNode( Node contextNode, String str )
throws SAXException {
return selectSingleNode( contextNode, str, contextNode );
}
/**
* Use an XPath string to select a single node.
* XPath namespace prefixes are resolved from the namespaceNode.
*
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be
resolved to namespaces.
* @return The first node found that matches the XPath, or null.
*/
public static Node selectSingleNode( Node contextNode, String str, Node
namespaceNode )
throws SAXException {
// Have the XObject return its result as a NodeSet.
NodeList nl = selectNodeList( contextNode, str, namespaceNode );
// Return the first node, or null
return ( nl.getLength() > 0 ) ? nl.item( 0 ) : null;
}
/**
* Use an XPath string to select a nodelist.
* XPath namespace prefixes are resolved from the contextNode.
*
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @return A nodelist, should never be null.
*/
public static NodeList selectNodeList( Node contextNode, String str )
throws SAXException {
return selectNodeList( contextNode, str, contextNode );
}
/**
* Use an XPath string to select a nodelist.
* XPath namespace prefixes are resolved from the namespaceNode.
*
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will
be resolved to namespaces.
* @return A nodelist, should never be null.
*/
public static NodeList selectNodeList( Node contextNode, String str, Node
namespaceNode )
throws SAXException {
// Execute the XPath, and have it return the result
XObject list = eval( contextNode, str, namespaceNode );
// Have the XObject return its result as a NodeSet.
return list.nodeset();
}
/**
* Evaluate XPath string to an XObject. Using this method,
* XPath namespace prefixes will be resolved from the namespaceNode.
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be
resolved to namespaces.
* @return An XObject, which can be used to obtain a string, number,
nodelist, etc, should never be null.
* @see org.apache.xalan.xpath.XObject
* @see org.apache.xalan.xpath.XNull
* @see org.apache.xalan.xpath.XBoolean
* @see org.apache.xalan.xpath.XNumber
* @see org.apache.xalan.xpath.XString
* @see org.apache.xalan.xpath.XRTreeFrag
*/
public static XObject eval( Node contextNode, String str )
throws SAXException {
return eval( contextNode, str, contextNode );
}
/**
* Evaluate XPath string to an XObject.
* XPath namespace prefixes are resolved from the namespaceNode.
* The implementation of this is a little slow, since it creates
* a number of objects each time it is called. This could be optimized
* to keep the same objects around, but then thread-safety issues would
arise.
*
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be
resolved to namespaces.
* @return An XObject, which can be used to obtain a string, number,
nodelist, etc, should never be null.
* @see org.apache.xalan.xpath.XObject
* @see org.apache.xalan.xpath.XNull
* @see org.apache.xalan.xpath.XBoolean
* @see org.apache.xalan.xpath.XNumber
* @see org.apache.xalan.xpath.XString
* @see org.apache.xalan.xpath.XRTreeFrag */
public static XObject eval( Node contextNode, String str, Node
namespaceNode )
throws SAXException {
// Since we don't have a XML Parser involved here, install some
default support
// for things like namespaces, etc.
// (Changed from: XPathSupportDefault xpathSupport = new
XPathSupportDefault();
// because XPathSupportDefault is weak in a number of areas...
perhaps
// XPathSupportDefault should be done away with.)
XPathSupport xpathSupport = new XMLParserLiaisonDefault();
if ( null == namespaceNode )
namespaceNode = contextNode;
// Create an object to resolve namespace prefixes.
// XPath namespaces are resolved from the input context node's
document element
// if it is a root node, or else the current context node (for lack
of a better
// resolution space, given the simplicity of this sample code).
PrefixResolverDefault prefixResolver = new PrefixResolverDefault( (
namespaceNode.getNodeType() == Node.DOCUMENT_NODE )
? ( ( Document ) namespaceNode
).getDocumentElement() :
namespaceNode );
// Create the XPath object.
XPath xpath = new XPath();
// Create a XPath parser.
XPathProcessorImpl parser = new XPathProcessorImpl( xpathSupport );
parser.initXPath( xpath, str, prefixResolver );
// Execute the XPath, and have it return the result
return xpath.execute( xpathSupport, contextNode, prefixResolver );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/internet/CRLFInputStream.java
Index: CRLFInputStream.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 file.
*/
package org.apache.avalon.util.internet;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Transform line endings to CRLF in input stream.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class CRLFInputStream
extends FilterInputStream
{
protected int m_lastChar;
public CRLFInputStream( final InputStream inputStream )
{
super( inputStream );
m_lastChar = -1;
}
public int read()
throws IOException
{
if( '\r' != m_lastChar )
{
final int result = m_lastChar;
m_lastChar = -1;
return result;
}
final int data = in.read();
if( -1 == data )
{
if( -1 != m_lastChar ) return m_lastChar;
else return data;
}
else if( '\r' == data )
{
m_lastChar = data;
return read();
}
else if( '\n' != data )
{
if( -1 != m_lastChar )
{
final int result = m_lastChar;
m_lastChar = -1;
return result;
}
else return data;
}
else return data;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/internet/CRLFOutputStream.java
Index: CRLFOutputStream.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 file.
*/
package org.apache.avalon.util.internet;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Transform line endings to CRLF in output stream.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class CRLFOutputStream
extends FilterOutputStream
{
public CRLFOutputStream( final OutputStream outputStream )
{
super( outputStream );
}
public void write( final int data )
throws IOException
{
if( '\n' == data ) out.write( '\r' );
out.write( data );
}
public void write( final byte data[], final int offset, final int len )
throws IOException
{
for( int i = 0; i < len; i++)
{
final byte element = data[ offset + i ];
if( '\n' == element ) out.write( '\r' );
out.write( element );
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/internet/InternetException.java
Index: InternetException.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 file.
*/
package org.apache.avalon.util.internet;
import org.apache.avalon.CascadingException;
/**
* Connection thrown during various internet related protocol handling.
* The code field will handle the common 3 digit code + message
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class InternetException
extends CascadingException
{
protected InternetReply m_reply;
public InternetException( final int code, final String description )
{
this( code, description, null );
}
public InternetException( final int code,
final String description,
final Throwable throwable )
{
super( description, throwable );
m_reply = new InternetReply( code, description );
}
public InternetReply getReply()
{
return m_reply;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/internet/InternetReply.java
Index: InternetReply.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 file.
*/
package org.apache.avalon.util.internet;
/**
* This is for holding Internet reply codes + descriptions.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class InternetReply
{
protected int m_code;
protected String m_description;
public InternetReply( final int code, final String description )
{
m_code = code;
m_description = description;
}
public int getCode()
{
return m_code;
}
public String getDescription()
{
return m_description;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/internet/InternetStream.java
Index: InternetStream.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 file.
*/
package org.apache.avalon.util.internet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ProtocolException;
/**
* This is the Internet output/input stream.
* Used for such things as SMTP, NNTP, FTP? etc.
*
* TODO: Need to be able to set a flag to allow lax input-reading
* to cope with some non-compliant sources
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class InternetStream
{
protected final static int MAX_OUTGOING_LINE_LENGTH = 512;
protected LineReader m_reader;
protected LineWriter m_writer;
protected String m_lastLine;
protected String m_responseText;
protected int m_responseCode;
protected String m_requestVerb;
protected String m_requestParameter;
/**
* Constructor taking an input and output.
*
* @param input the InputStream
* @param output the OutputStream
*/
public InternetStream( final InputStream input, final OutputStream output
)
{
m_reader = new LineReader( input );
m_writer = new LineWriter( output );
}
/**
* Retrieve request verb last received.
*
* @return the request verb
*/
public String getRequestVerb()
{
return m_requestVerb;
}
/**
* Retrieve request parameter
*
* @return the request parameter
*/
public String getRequestParameter()
{
return m_requestParameter;
}
public String getResponseText()
{
return m_responseText;
}
public int getResponseCode()
{
return m_responseCode;
}
/**
* Retrieve last line received from connection.
*
* @return the last line received
*/
public String getLastLine()
{
return m_lastLine;
}
/**
* Send a request to server.
*
* @param verb the request verb
* @exception IOException if an error occurs
*/
public void sendRequest( final String verb )
throws IOException
{
sendRequest( verb, null );
}
/**
* Send a Request to server.
*
* @param verb the request verb
* @param parameter the parameter (or null if none)
* @exception IOException if an error occurs
*/
public void sendRequest( final String verb, final String parameter )
throws IOException
{
final StringBuffer sb = new StringBuffer();
sb.append( verb );
if( null != parameter )
{
sb.append( ' ' );
sb.append( parameter );
}
m_writer.println( sb.toString() );
}
/**
* Send a response.
* Format the message so that it conforms to line length/contents rules.
*
* @param responseCode the response code
* @param message the message
* @exception IOException if an error occurs
*/
public void sendResponse( final int responseCode, final String message )
throws IOException
{
int start = 0;
int end = message.indexOf( '\n' );
while( -1 != end )
{
sendResponseLines( responseCode, false, message.substring( start,
end ) );
start = end + 1;
end = message.indexOf( '\n', start );
}
end = message.length();
sendResponseLines( responseCode, true, message.substring( start, end
) );
}
/**
* Receive a Request from client.
*
* @exception IOException if an error occurs
*/
public void receiveRequest()
throws IOException
{
m_requestVerb = null;
m_requestParameter = null;
final String line = m_reader.readln();
int space = line.indexOf( ' ' );
if( -1 == space )
{
m_requestVerb = line.toUpperCase();
}
else
{
m_requestVerb = line.substring( 0, space ).toUpperCase();
m_requestParameter = line.substring( space + 1 ).trim();
if( m_requestParameter.equals( "" ) )
{
m_requestParameter = null;
}
}
}
/**
* receive a response from server.
*
* @exception IOException if an error occurs
*/
public void receiveResponse()
throws IOException
{
boolean lastLine = false;
m_responseCode = 0;
m_responseText = null;
while( !lastLine )
{
final String line = m_reader.readln();
int responseCode = Integer.parseInt( line.substring( 0, 3 ) );
if( 0 != m_responseCode && responseCode != m_responseCode )
{
throw new ProtocolException( "Badly formed response with
differing codes" );
}
m_responseCode = responseCode;
lastLine = ( ' ' == line.charAt( 3 ) );
final String messagePart = line.substring( 4, line.length() );
if( null == m_responseText ) m_responseText = messagePart;
else m_responseText += '\n' + messagePart;
}
}
/**
* Helper method to build a response line.
* If message is greater than MAX_OUTGOING_LINE_LENGTH it is broken into
multiple lines.
*
* @param responseCode the response code.
* @param isLastLine true if this is last line in response
* @param message the message
* @exception IOException if an error occurs
*/
protected void sendResponseLines( final int responseCode,
final boolean isLastLine,
final String message )
throws IOException
{
final int size = message.length();
if( size < MAX_OUTGOING_LINE_LENGTH )
{
sendResponseLine( responseCode, isLastLine, message );
}
else
{
int start = 0;
int end = MAX_OUTGOING_LINE_LENGTH;
while( end < size )
{
sendResponseLine( responseCode, false, message.substring(
start, end ) );
start = end + 1;
end = end + MAX_OUTGOING_LINE_LENGTH;
}
sendResponseLine( responseCode, isLastLine, message.substring(
start, size ) );
}
}
/**
* Helper method to build a response line.
*
* @param responseCode the response code.
* @param isLastLine true if this is last line in response
* @param message the message
* @exception IOException if an error occurs
*/
protected void sendResponseLine( final int responseCode,
final boolean isLastLine,
final String message )
throws IOException
{
final char seperator = ( isLastLine ) ? ' ' : '-';
final String responseLine = Integer.toString( responseCode ) +
seperator + message;
sendLine( responseLine );
}
/**
* Send a raw line and terminate it with a \r\n.
* This assumes thaat the parameters does not have \r\n
* sequence in it (or \n byitself).
*
* @param line the line
* @exception IOException if an error occurs
*/
public final void sendLine( final String line )
throws IOException
{
m_writer.println( line );
}
/**
* Receive a line.
*
* @return the line received
* @exception IOException if an error occurs
*/
public final String receiveLine()
throws IOException
{
m_lastLine = m_reader.readln();
return m_lastLine;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/internet/LineReader.java
Index: LineReader.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 file.
*/
package org.apache.avalon.util.internet;
import java.io.IOException;
import java.io.InputStream;
import java.net.ProtocolException;
/**
* Used to write lines with appropriate line endings.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class LineReader
{
protected final static byte[] LINE_TERMINATOR = { (byte)'\r',
(byte)'\n' };
protected InputStream m_input;
protected boolean m_laxLineFormat;
public LineReader( final InputStream input )
{
m_input = input;
}
public void setLaxLineFormat( final boolean laxLineFormat )
{
m_laxLineFormat = laxLineFormat;
}
public String readln()
throws IOException
{
final StringBuffer sb = new StringBuffer();
int data = m_input.read();
int last = -1;
while( LINE_TERMINATOR[ 1 ] != data )
{
if( last == LINE_TERMINATOR[ 0 ] )
{
if( data == LINE_TERMINATOR[ 1 ] ) break;
else sb.append( (char)last );
}
else if( data == LINE_TERMINATOR[ 1 ] )
{
break;
}
else
{
last = data;
if( data != LINE_TERMINATOR[ 0 ] ) sb.append( (char)data );
}
data = m_input.read();
}
return sb.toString();
}
public void close()
throws IOException
{
m_input.close();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/internet/LineWriter.java
Index: LineWriter.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 file.
*/
package org.apache.avalon.util.internet;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ProtocolException;
/**
* Used to write lines with appropriate line endings.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class LineWriter
{
protected final static byte[] LINE_TERMINATOR = { (byte)'\r',
(byte)'\n' };
protected OutputStream m_output;
public LineWriter( final OutputStream output )
{
m_output = output;
}
public void println( final String data )
throws IOException
{
m_output.write( data.getBytes() );
m_output.write( LINE_TERMINATOR );
m_output.flush();
}
public void close()
throws IOException
{
m_output.close();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/io/ByteTerminatedInputStream.java
Index: ByteTerminatedInputStream.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 file.
*/
package org.apache.avalon.util.io;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author Federico Barbieri <[EMAIL PROTECTED]>
*/
public class ByteTerminatedInputStream
extends InputStream
{
protected final boolean m_includeTerminator;
protected final InputStream m_inputStream;
protected final byte[] m_terminator;
protected final int m_matchLength;
protected int m_match;
public ByteTerminatedInputStream( final InputStream inputStream,
final byte[] terminator,
final boolean includeTerminator )
{
m_includeTerminator = includeTerminator;
m_matchLength = terminator.length;
m_terminator = terminator;
m_inputStream = inputStream;
m_match = 0;
}
public int read()
throws IOException
{
if( m_match == m_matchLength ) return -1;
int next = getNext();
if( !m_includeTerminator && 0 != m_match )
{
m_inputStream.mark( m_matchLength );
int matchTest = next;
while( -1 != matchTest )
{
matchTest = getNext();
if( m_match == m_matchLength ) return -1;
else if( m_match == 0 ) break;
}
m_match = 0;
m_inputStream.reset();
}
return next;
}
protected final int getNext()
throws IOException
{
final int next = m_inputStream.read();
if( next == m_terminator[ m_match ] ) m_match++;
else if( next == m_terminator[ 0 ] ) m_match = 1;
else m_match = 0;
return next;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/io/DirectoryFileFilter.java
Index: DirectoryFileFilter.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 file.
*/
package org.apache.avalon.util.io;
import java.io.File;
import java.io.FilenameFilter;
/**
* This filters files based if not a directory.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DirectoryFileFilter
implements FilenameFilter
{
public boolean accept( final File file, final String name )
{
return file.isDirectory();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/io/ExtensionFileFilter.java
Index: ExtensionFileFilter.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 file.
*/
package org.apache.avalon.util.io;
import java.io.File;
import java.io.FilenameFilter;
/**
* This filters files based on the extension (what the filename
* ends with). This is used in retrieving all the files of a
* particular type.
*
* @author Federico Barbieri <[EMAIL PROTECTED]>
* @author Serge Knystautas <[EMAIL PROTECTED]>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class ExtensionFileFilter
implements FilenameFilter
{
private String[] m_extensions;
public ExtensionFileFilter( final String[] extensions )
{
m_extensions = extensions;
}
public ExtensionFileFilter( final String extension )
{
m_extensions = new String[] { extension };
}
public boolean accept( final File file, final String name )
{
for( int i = 0; i < m_extensions.length; i++ )
{
if( name.endsWith( m_extensions[ i ] ) ) return true;
}
return false;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/io/FileUtil.java
Index: FileUtil.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 file.
*/
package org.apache.avalon.util.io;
import java.io.*;
import java.net.URL;
import org.apache.avalon.util.StringUtil;
/**
* This class provides basic facilities for manipulating files.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class FileUtil
{
/**
* Private constructor to prevent instantiation.
*
*/
private FileUtil()
{
}
public static File toFile( final URL url )
{
if( !url.getProtocol().equals( "file" ) )
{
return null;
}
else
{
final String filename = url.getFile().replace( '/',
File.separatorChar );
return new File( filename );
}
}
/**
* Remove extention from filename.
* ie
* fo.txt --> foo
* a\b\c.jpg --> a\b\c
* a\b\c --> a\b\c
*
* @param filename the filename
* @return the filename minus extention
*/
public static String removeExtention( final String filename )
{
final int index = filename.lastIndexOf( '.' );
if( -1 == index )
{
return filename;
}
else
{
return filename.substring( 0, index );
}
}
/**
* remove path from filename.
* ie.
* a/b/c.txt --> c.txt
* a.txt --> a.txt
*
* @param filepath the filepath
* @return the filename minus path
*/
public static String removePath( final String filepath )
{
final int index = filepath.lastIndexOf( File.separator );
if( -1 == index )
{
return filepath;
}
else
{
return filepath.substring( index + 1 );
}
}
/**
* Copy file from source to destination.
*/
public static void copyFileToDirectory( final String source,
final String destinationDirectory
)
throws IOException
{
copyFileToDirectory( new File( source ), new File(
destinationDirectory ) );
}
/**
* Copy file from source to destination.
*/
public static void copyFileToDirectory( final File source,
final File destinationDirectory )
throws IOException
{
if( destinationDirectory.exists() &&
!destinationDirectory.isDirectory() )
{
throw new IllegalArgumentException( "Destination is not a
directory" );
}
copyFile( source, new File( destinationDirectory, source.getName() )
);
}
/**
* Copy file from source to destination.
*/
public static void copyFile( final File source, final File destination )
throws IOException
{
//check source exists
if( !source.exists() )
{
throw new IOException( "File " + source + " does not exist" );
}
//does destinations directory exist ?
if( !destination.getParentFile().exists() )
{
destination.mkdirs();
}
//make sure we can write to destination
if( destination.exists() && !destination.canWrite() )
{
throw new IOException( "Unable to open file " + destination + "
for writing." );
}
IOUtil.copy( new FileInputStream( source ), new FileOutputStream(
destination ) );
if( source.length() != destination.length() )
{
throw new IOException( "Failed to copy full contents from " +
source +
" to " + destination );
}
}
public static void copyURLToFile( final URL source, final File
destination )
throws IOException
{
//does destinations directory exist ?
if( !destination.getParentFile().exists() )
{
destination.mkdirs();
}
//make sure we can write to destination
if( destination.exists() && !destination.canWrite() )
{
throw new IOException( "Unable to open file " + destination + "
for writing." );
}
IOUtil.copy( source.openStream(), new FileOutputStream( destination )
);
}
public static String normalize( String location )
{
location = StringUtil.replaceSubString( location, "/./", "/" );
final StringBuffer sb = new StringBuffer();
int trail = 0;
int end = location.indexOf( "/../" );
int start = 0;
while( end != -1 )
{
//TODO: fix when starts with /../
trail = location.lastIndexOf( "/", end - 1 );
sb.append( location.substring( start, trail ) );
sb.append( '/' );
start = end + 4;
end = location.indexOf( "/../", start );
}
end = location.length();
sb.append( location.substring( start, end ) );
return sb.toString();
}
/** Will concatenate 2 paths, dealing with ..
* ( /a/b/c + d = /a/b/d, /a/b/c + ../d = /a/d )
*
* Thieved from Tomcat sources...
*
* @return null if error occurs
*/
public static String catPath( String lookupPath, String path )
{
// Cut off the last slash and everything beyond
int index = lookupPath.lastIndexOf( "/" );
lookupPath = lookupPath.substring( 0, index );
// Deal with .. by chopping dirs off the lookup path
while( path.startsWith( "../" ) )
{
if( lookupPath.length() > 0 )
{
index = lookupPath.lastIndexOf( "/" );
lookupPath = lookupPath.substring( 0, index );
}
else
{
// More ..'s than dirs, return null
return null;
}
index = path.indexOf( "../" ) + 3;
path = path.substring( index );
}
return lookupPath + "/" + path;
}
public static File resolveFile( final File baseFile, String filename )
{
if( '/' != File.separatorChar )
{
filename = filename.replace( '/', File.separatorChar );
}
if( '\\' != File.separatorChar )
{
filename = filename.replace( '\\', File.separatorChar );
}
// deal with absolute files
if( filename.startsWith( File.separator ) )
{
File file = new File( filename );
try { file = file.getCanonicalFile(); }
catch( final IOException ioe ) {}
return file;
}
final char[] chars = filename.toCharArray();
final StringBuffer sb = new StringBuffer();
//remove duplicate file seperators in succession - except
//on win32 as UNC filenames can be \\AComputer\AShare\myfile.txt
int start = 0;
if( '\\' == File.separatorChar )
{
sb.append( filename.charAt( 0 ) );
start++;
}
for( int i = start; i < chars.length; i++ )
{
final boolean doubleSeperator =
File.separatorChar == chars[ i ] && File.separatorChar ==
chars[ i - 1 ];
if( !doubleSeperator ) sb.append( chars[ i ] );
}
filename = sb.toString();
//must be relative
File file = (new File( baseFile, filename )).getAbsoluteFile();
try { file = file.getCanonicalFile(); }
catch( final IOException ioe ) {}
return file;
}
/**
* Delete a file. If file is directory delete it and all sub-directories.
*/
public static void forceDelete( final String file )
throws IOException
{
forceDelete( new File( file ) );
}
/**
* Delete a file. If file is directory delete it and all sub-directories.
*/
public static void forceDelete( final File file )
throws IOException
{
if( file.isDirectory() ) deleteDirectory( file );
else
{
if( false == file.delete() )
{
throw new IOException( "File " + file + " unable to be
deleted." );
}
}
}
/**
* Recursively delete a directory.
*/
public static void deleteDirectory( final String directory )
throws IOException
{
deleteDirectory( new File( directory ) );
}
/**
* Recursively delete a directory.
*/
public static void deleteDirectory( final File directory )
throws IOException
{
if( !directory.exists() ) return;
cleanDirectory( directory );
if( false == directory.delete() )
{
throw new IOException( "Directory " + directory + " unable to be
deleted." );
}
}
/**
* Clean a directory without deleting it.
*/
public static void cleanDirectory( final String directory )
throws IOException
{
cleanDirectory( new File( directory ) );
}
/**
* Clean a directory without deleting it.
*/
public static void cleanDirectory( final File directory )
throws IOException
{
if( !directory.exists() )
{
throw new IllegalArgumentException( directory + " does not exist"
);
}
if( !directory.isDirectory() )
{
throw new IllegalArgumentException( directory + " is not a
directory" );
}
final File[] files = directory.listFiles();
for( int i = 0; i < files.length; i++ )
{
final File file = files[ i ];
if( file.isFile() ) file.delete();
else if( file.isDirectory() )
{
cleanDirectory( file );
if( false == file.delete() )
{
throw new IOException( "Directory " + file + " unable to
be deleted." );
}
}
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/io/IOUtil.java
Index: IOUtil.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 file.
*/
package org.apache.avalon.util.io;
import java.io.*;
/**
* This class provides basic facilities for manipulating io streams.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class IOUtil
{
/**
* Private constructor to prevent instantiation.
*/
private IOUtil()
{
}
public static void shutdownStream( final OutputStream output )
{
if( null == output ) return;
try { output.close(); }
catch( final IOException ioe ) {}
}
public static void shutdownStream( final InputStream input )
{
if( null == input ) return;
try { input.close(); }
catch( final IOException ioe ) {}
}
/**
* Copy stream-data from source to destination.
*/
public static void copy( final InputStream source, final OutputStream
destination )
throws IOException
{
try
{
final BufferedInputStream input = new BufferedInputStream( source
);
final BufferedOutputStream output = new BufferedOutputStream(
destination );
final int BUFFER_SIZE = 1024 * 4;
final byte[] buffer = new byte[ BUFFER_SIZE ];
while( true )
{
final int count = input.read( buffer, 0, BUFFER_SIZE );
if( -1 == count ) break;
// write out those same bytes
output.write( buffer, 0, count );
}
//needed to flush cache
output.flush();
}
finally
{
shutdownStream( source );
shutdownStream( destination );
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/io/MergedInputStreams.java
Index: MergedInputStreams.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 file.
*/
package org.apache.avalon.util.io;
import java.io.IOException;
import java.io.InputStream;
/**
* Merges multiple input streams into one.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class MergedInputStreams
extends InputStream
{
protected final InputStream[] m_streams;
protected int m_index;
public MergedInputStreams( final InputStream[] inputStreams )
{
super();
m_streams = inputStreams;
}
public int read()
throws IOException
{
if( m_index >= m_streams.length ) return -1;
int returnVal = m_streams[ m_index ].read();
if( -1 == returnVal && (++m_index) < m_streams.length )
{
returnVal = m_streams[ m_index ].read();
}
return returnVal;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/io/ResettableFileInputStream.java
Index: ResettableFileInputStream.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 file.
*/
package org.apache.avalon.util.io;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Federico Barbieri <[EMAIL PROTECTED]>
*/
public class ResettableFileInputStream
extends InputStream
{
protected static final int DEFAULT_BUFFER_SIZE = 1024;
protected final String m_filename;
protected int m_bufferSize;
protected InputStream m_inputStream;
protected long m_position;
protected long m_mark;
protected boolean m_isMarkSet;
public ResettableFileInputStream( final File file )
throws IOException
{
this( file.getCanonicalPath() );
}
public ResettableFileInputStream( final String filename )
throws IOException
{
this( filename, DEFAULT_BUFFER_SIZE );
}
public ResettableFileInputStream( final String filename, final int
bufferSize )
throws IOException
{
m_bufferSize = bufferSize;
m_filename = filename;
m_position = 0;
m_inputStream = newStream();
}
public void mark( final int readLimit )
{
m_isMarkSet = true;
m_mark = m_position;
m_inputStream.mark( readLimit );
}
public boolean markSupported()
{
return true;
}
public void reset()
throws IOException
{
if( !m_isMarkSet )
{
throw new IOException( "Unmarked Stream" );
}
try
{
m_inputStream.reset();
}
catch( final IOException ioe )
{
try
{
m_inputStream.close();
m_inputStream = newStream();
m_inputStream.skip( m_mark );
m_position = m_mark;
}
catch( final Exception e )
{
throw new IOException( "Cannot reset current Stream: " +
e.getMessage() );
}
}
}
protected InputStream newStream()
throws IOException
{
return new BufferedInputStream( new FileInputStream( m_filename ),
m_bufferSize );
}
public int available()
throws IOException
{
return m_inputStream.available();
}
public void close() throws IOException
{
m_inputStream.close();
}
public int read() throws IOException
{
m_position++;
return m_inputStream.read();
}
public int read( final byte[] bytes, final int offset, final int length )
throws IOException
{
final int count = m_inputStream.read( bytes, offset, length );
m_position += count;
return count;
}
public long skip( final long count )
throws IOException
{
m_position += count;
return m_inputStream.skip( count );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/io/test/FileUtilTestlet.java
Index: FileUtilTestlet.java
===================================================================
/*
* Copyright 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 file.
*/
package org.apache.avalon.util.io.test;
import java.io.*;
import org.apache.avalon.util.io.FileUtil;
import org.apache.testlet.AbstractTestlet;
import org.apache.testlet.TestFailedException;
/**
* This is used to test FileUtil for correctness.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class FileUtilTestlet
extends AbstractTestlet
{
protected final int FILE1_SIZE = 1;
protected final int FILE2_SIZE = 1024 * 4 + 1;
protected final File m_testDirectory;
protected final File m_testFile1;
protected final File m_testFile2;
public FileUtilTestlet()
throws IOException
{
m_testDirectory = (new File( "test/io/" )).getAbsoluteFile();
if( !m_testDirectory.exists() )
{
m_testDirectory.mkdirs();
}
m_testFile1 = new File( m_testDirectory, "file1-test.txt" );
m_testFile2 = new File( m_testDirectory, "file2-test.txt" );
createFile( m_testFile1, FILE1_SIZE );
createFile( m_testFile2, FILE2_SIZE );
}
protected void createFile( final File file, final long size )
throws IOException
{
final BufferedOutputStream output =
new BufferedOutputStream( new FileOutputStream( file ) );
for( int i = 0; i < size; i++ )
{
output.write( (byte)'X' );
}
output.close();
}
public void testCopyFile1()
throws Exception
{
final File destination = new File( m_testDirectory, "copy1.txt" );
FileUtil.copyFile( m_testFile1, destination );
assert( "Check Exist", destination.exists() );
assert( "Check Full copy", destination.length() == FILE1_SIZE );
}
public void testCopyFile2()
throws Exception
{
final File destination = new File( m_testDirectory, "copy2.txt" );
FileUtil.copyFile( m_testFile2, destination );
assert( "Check Exist", destination.exists() );
assert( "Check Full copy", destination.length() == FILE2_SIZE );
}
public void testForceDeleteFile1()
throws Exception
{
final File destination = new File( m_testDirectory, "copy1.txt" );
FileUtil.forceDelete( destination );
assert( "Check No Exist", !destination.exists() );
}
public void testForceDeleteFile2()
throws Exception
{
final File destination = new File( m_testDirectory, "copy2.txt" );
FileUtil.forceDelete( destination );
assert( "Check No Exist", !destination.exists() );
}
public void testCopyFile1ToDir()
throws Exception
{
final File directory = new File( m_testDirectory, "subdir" );
if( !directory.exists() ) directory.mkdirs();
final File destination = new File( directory, "file1-test.txt" );
FileUtil.copyFileToDirectory( m_testFile1, directory );
assert( "Check Exist", destination.exists() );
assert( "Check Full copy", destination.length() == FILE1_SIZE );
}
public void testCopyFile2ToDir()
throws Exception
{
final File directory = new File( m_testDirectory, "subdir" );
if( !directory.exists() ) directory.mkdirs();
final File destination = new File( directory, "file2-test.txt" );
FileUtil.copyFileToDirectory( m_testFile2, directory );
assert( "Check Exist", destination.exists() );
assert( "Check Full copy", destination.length() == FILE2_SIZE );
}
public void testForceDeleteDir()
throws Exception
{
FileUtil.forceDelete( m_testDirectory.getParentFile() );
assert( "Check No Exist", !m_testDirectory.getParentFile().exists() );
}
public void testResolveFileDotDot()
throws Exception
{
final File file = FileUtil.resolveFile( m_testDirectory, ".." );
assertEquality( "Check .. operator", file,
m_testDirectory.getParentFile() );
}
public void testResolveFileDot()
throws Exception
{
final File file = FileUtil.resolveFile( m_testDirectory, "." );
assertEquality( "Check . operator", file, m_testDirectory );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/lang/ThreadManager.java
Index: ThreadManager.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 file.
*/
package org.apache.avalon.util.lang;
import org.apache.avalon.util.thread.ThreadContext;
import org.apache.avalon.util.thread.ThreadPool;
/**
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
*/
public final class ThreadManager
{
/**
* @deprecated This will be removed in future iterations and is legacy
from old time
*/
public static ThreadPool getWorkerPool( final String name )
{
return ThreadContext.getCurrentThreadPool();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/log/AvalonLogFormatter.java
Index: AvalonLogFormatter.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 file.
*/
package org.apache.avalon.util.log;
import java.util.Date;
import org.apache.avalon.util.StringUtil;
import org.apache.log.format.PatternFormatter;
/**
* Specialized formatter that knows about CascadingThrowables.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class AvalonLogFormatter
extends PatternFormatter
{
protected String getStackTrace( final Throwable throwable, final String
format )
{
if( null == throwable ) return "";
return StringUtil.printStackTrace( throwable, 8, true );
}
/**
* Utility method to format time.
*
* @param time the time
* @param format ancilliary format parameter - allowed to be null
* @return the formatted string
*/
protected String getTime( final long time, final String format )
{
return new Date().toString();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/log/DefaultLogManager.java
Index: DefaultLogManager.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 file.
*/
package org.apache.avalon.util.log;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import org.apache.avalon.AbstractLoggable;
import org.apache.avalon.Component;
import org.apache.avalon.configuration.Configurable;
import org.apache.avalon.configuration.Configuration;
import org.apache.avalon.configuration.ConfigurationException;
import org.apache.avalon.Context;
import org.apache.avalon.Contextualizable;
import org.apache.log.Category;
import org.apache.log.LogKit;
import org.apache.log.LogTarget;
import org.apache.log.output.FileOutputLogTarget;
/**
* Component responsible for managing logs.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultLogManager
extends AbstractLoggable
implements Component, Contextualizable, Configurable
{
protected String m_baseName;
protected File m_baseDirectory;
public void contextualize( final Context context )
{
m_baseName = (String)context.get( "name" );
if( null == m_baseName ) m_baseName = "<base>";
m_baseDirectory = (File)context.get( "directory" );
if( null == m_baseDirectory ) m_baseDirectory = new File( "." );
}
public void configure( final Configuration configuration )
throws ConfigurationException
{
final Configuration[] targets = configuration.getChildren(
"log-target" );
configureTargets( m_baseName, m_baseDirectory, targets );
final Configuration[] categories = configuration.getChildren(
"category" );
configureCategories( m_baseName, categories );
/*
final String logPriority = configuration.getChild(
"global-priority" ).getValue();
final Priority.Enum priority = LogKit.getPriorityForName(
logPriority );
LogKit.setGlobalPriority( priority );
*/
}
protected void configureTargets( final String baseName,
final File baseDirectory,
final Configuration[] targets )
throws ConfigurationException
{
for( int i = 0; i < targets.length; i++ )
{
final Configuration target = targets[ i ];
final String name = baseName + '.' + target.getAttribute( "name"
);
String location = target.getAttribute( "location" ).trim();
final String format = target.getAttribute( "format", null );
if( '/' == location.charAt( 0 ) )
{
location = location.substring( 1 );
}
final File file = new File( baseDirectory, location );
final FileOutputLogTarget logTarget = new FileOutputLogTarget();
final AvalonLogFormatter formatter = new AvalonLogFormatter();
formatter.setFormat( "%{time} [%7.7{priority}] <<%{category}>> " +
"(%{context}): %{message}\\n%{throwable}" );
logTarget.setFormatter( formatter );
try { logTarget.setFilename( file.getAbsolutePath() ); }
catch( final IOException ioe )
{
throw new ConfigurationException( "Error initializing log
files", ioe );
}
if( null != format )
{
logTarget.setFormat( format );
}
LogKit.addLogTarget( name, logTarget );
}
}
protected void configureCategories( final String baseName, final
Configuration[] categories )
throws ConfigurationException
{
for( int i = 0; i < categories.length; i++ )
{
final Configuration category = categories[ i ];
String name = category.getAttribute( "name" );
final String target = baseName + '.' + category.getAttribute(
"target" );
final String priority = category.getAttribute( "priority" );
if( name.trim().equals( "" ) )
{
name = baseName;
}
else
{
name = baseName + '.' + name;
}
final Category logCategory =
LogKit.createCategory( name, LogKit.getPriorityForName(
priority ) );
final LogTarget logTarget = LogKit.getLogTarget( target );
LogTarget logTargets[] = null;
if( null != target ) logTargets = new LogTarget[] { logTarget };
LogKit.createLogger( logCategory, logTargets );
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/AbstractLifeCycleStage.java
Index: AbstractLifeCycleStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.AbstractLoggable;
import org.apache.avalon.Stage;
import org.apache.avalon.camelot.Entry;
/**
* Stage used in managing avalon components.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class AbstractLifeCycleStage
extends AbstractLoggable
implements LifeCycleStage
{
protected Class m_service;
protected String m_serviceName;
/**
* Process an avalon entry.
* Processing includes managing some aspect of blocks lifecycle
* and could be configuring, exporting, replicating, composing etc.
*
* @param entry the entry
* @exception Exception if an error occurs
*/
public void process( final String name, final Entry entry )
throws Exception
{
final Object object = entry.getInstance();
if( m_service.isInstance( object ) )
{
getLogger().debug( "Processing " + m_serviceName + " Stage for "
+ name );
process( name, entry, object );
}
}
protected abstract void process( String name, Entry entry, Object object
)
throws Exception;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/CompositionStage.java
Index: CompositionStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.Composer;
import org.apache.avalon.ComponentManager;
import org.apache.avalon.ComponentManagerException;
import org.apache.avalon.camelot.Entry;
import org.apache.avalon.camelot.ComponentManagerBuilder;
/**
* Composer stage for avalon pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
*/
public class CompositionStage
extends AbstractLifeCycleStage
implements Composer
{
protected ComponentManagerBuilder m_builder;
public CompositionStage()
{
m_service = Composer.class;
m_serviceName = "Compose";
}
public void compose( final ComponentManager componentManager )
throws ComponentManagerException
{
m_builder = (ComponentManagerBuilder)componentManager.
lookup( "org.apache.avalon.camelot.ComponentManagerBuilder" );
}
protected void process( final String name, final Entry entry, final
Object object )
throws Exception
{
((Composer)object).compose( m_builder.createComponentManager( name,
entry ) );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/ConfigurationStage.java
Index: ConfigurationStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.ComponentManager;
import org.apache.avalon.ComponentManagerException;
import org.apache.avalon.Composer;
import org.apache.avalon.camelot.Entry;
import org.apache.avalon.camelot.ConfigurationRepository;
import org.apache.avalon.configuration.Configurable;
/**
* Configuration stage for avalon pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
*/
public class ConfigurationStage
extends AbstractLifeCycleStage
implements Composer
{
protected ConfigurationRepository m_repository;
public ConfigurationStage()
{
m_service = Configurable.class;
m_serviceName = "Configure";
}
public void compose( final ComponentManager componentManager )
throws ComponentManagerException
{
m_repository = (ConfigurationRepository)componentManager.
lookup( "org.apache.avalon.camelot.ConfigurationRepository" );
}
protected void process( final String name, final Entry entry, final
Object object )
throws Exception
{
((Configurable)object).configure( m_repository.getConfiguration(
name, entry ) );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/ContextualizationStage.java
Index: ContextualizationStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.ComponentManager;
import org.apache.avalon.ComponentManagerException;
import org.apache.avalon.Composer;
import org.apache.avalon.Contextualizable;
import org.apache.avalon.camelot.Entry;
import org.apache.avalon.camelot.ContextBuilder;
/**
* Setup context for avalon component.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class ContextualizationStage
extends AbstractLifeCycleStage
implements Composer
{
protected ContextBuilder m_builder;
public ContextualizationStage()
{
m_service = Contextualizable.class;
m_serviceName = "Contextualize";
}
public void compose( final ComponentManager componentManager )
throws ComponentManagerException
{
m_builder = (ContextBuilder)componentManager.
lookup( "org.apache.avalon.camelot.ContextBuilder" );
}
protected void process( final String name, final Entry entry, final
Object object )
throws Exception
{
((Contextualizable)object).contextualize( m_builder.createContext(
name, entry ) );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/CreationStage.java
Index: CreationStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.AbstractLoggable;
import org.apache.avalon.ComponentManager;
import org.apache.avalon.ComponentManagerException;
import org.apache.avalon.Composer;
import org.apache.avalon.camelot.ComponentBuilder;
import org.apache.avalon.camelot.Entry;
/**
* Composer stage for avalon pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class CreationStage
extends AbstractLoggable
implements LifeCycleStage, Composer
{
protected ComponentBuilder m_builder;
public void compose( final ComponentManager componentManager )
throws ComponentManagerException
{
m_builder = (ComponentBuilder)componentManager.
lookup( "org.apache.avalon.camelot.ComponentBuilder" );
}
/**
* Create an object for entry.
*
* @param entry the entry
* @exception Exception if an error occurs
*/
public void process( final String name, final Entry entry )
throws Exception
{
getLogger().debug( "Processing Creation Stage for " + name );
final Object object = m_builder.createComponent( name, entry );
entry.setInstance( object );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/DisposingStage.java
Index: DisposingStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.Disposable;
import org.apache.avalon.camelot.Entry;
/**
* Disposal stage for avalon pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
*/
public class DisposingStage
extends AbstractLifeCycleStage
{
public DisposingStage()
{
m_service = Disposable.class;
m_serviceName = "Dispose";
}
protected void process( final String name, final Entry entry, final
Object object )
throws Exception
{
((Disposable)object).dispose();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/InitializationStage.java
Index: InitializationStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.Initializable;
import org.apache.avalon.camelot.Entry;
/**
* Initializable stage for avalon pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
*/
public class InitializationStage
extends AbstractLifeCycleStage
{
public InitializationStage()
{
m_service = Initializable.class;
m_serviceName = "Initialize";
}
protected void process( final String name, final Entry entry, final
Object object )
throws Exception
{
((Initializable)object).init();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/LifeCyclePipeline.java
Index: LifeCyclePipeline.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 file.
*/
package org.apache.avalon.util.pipeline;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import org.apache.avalon.AbstractLoggable;
import org.apache.avalon.ComponentManager;
import org.apache.avalon.ComponentManagerException;
import org.apache.avalon.Composer;
import org.apache.avalon.Context;
import org.apache.avalon.Contextualizable;
import org.apache.avalon.Initializable;
import org.apache.avalon.Stage;
import org.apache.avalon.camelot.Entry;
import org.apache.avalon.camelot.AvalonState;
/**
* This is basic array based pipeline.
* Stages should only be added *after* (or during) init is called.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class LifeCyclePipeline
extends AbstractLoggable
implements LifeCycleStage, Contextualizable, Composer, Initializable
{
protected ArrayList m_stages = new ArrayList();
protected ArrayList m_states = new ArrayList();
protected boolean m_consumeException;
protected Context m_context;
protected ComponentManager m_componentManager;
public void contextualize( final Context context )
{
m_context = context;
}
public void compose( final ComponentManager componentManager )
throws ComponentManagerException
{
m_componentManager = componentManager;
}
/**
* Retrieve size of pipeline (number of stages).
*
* @return the size of pipeline
*/
public int getSize()
{
return m_stages.size();
}
/**
* Retrieve a particular stage of pipeline
*
* @param index the index of stage
* @return the stage
* @exception NoSuchElementException if index >= getSize() or index < 0
*/
public Stage getStage( final int index )
throws NoSuchElementException
{
return (Stage)m_stages.get( index );
}
public void setConsumeException( final boolean consumeException )
{
m_consumeException = consumeException;
}
/**
* Overide this method to add
*
* @exception Exception if an error occurs
*/
public void init()
throws Exception
{
}
public void addStage( final AvalonState state, final LifeCycleStage stage
)
throws Exception
{
setupStage( stage );
m_states.add( state );
m_stages.add( stage );
}
protected void setupStage( final LifeCycleStage stage )
throws Exception
{
setupLogger( stage );
if( stage instanceof Contextualizable )
{
((Contextualizable)stage).contextualize( m_context );
}
if( stage instanceof Composer )
{
((Composer)stage).compose( m_componentManager );
}
if( stage instanceof Initializable )
{
((Initializable)stage).init();
}
}
/**
* Process an avalon entry.
* Processing includes managing some aspect of blocks lifecycle
* and could be configuring, exporting, replicating, composing etc.
*
* @param entry the entry
* @exception Exception if an error occurs
*/
public void process( final String name, final Entry entry )
throws Exception
{
final int size = m_stages.size();
for( int i = 0; i < size; i++ )
{
final AvalonState state = (AvalonState)m_states.get( i );
try
{
final LifeCycleStage stage = (LifeCycleStage)m_stages.get( i
);
getLogger().debug( "Pre-" + state.getName() + " for component
" + name );
stage.process( name, entry );
entry.setState( state );
getLogger().debug( "Post-" + state.getName() + " for
component " + name );
}
catch( final Exception e )
{
m_logger.debug( "Error in " + state.getName() + " for
component " + name );
entry.setState( AvalonState.ERROR );
if( m_consumeException )
{
m_logger.warn( "Error processing " + name, e );
}
else
{
throw e;
}
}
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/LifeCycleStage.java
Index: LifeCycleStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.Stage;
import org.apache.avalon.camelot.Entry;
/**
* Stage used in managing avalon components.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
*/
public interface LifeCycleStage
extends Stage
{
/**
* Process an avalon entry.
* Processing includes managing some aspect of components lifecycle
* and could be configuring, exporting, replicating, composing etc.
*
* @param entry the entry
* @exception Exception if an error occurs
*/
void process( String name, Entry entry )
throws Exception;
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/LoggerStage.java
Index: LoggerStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.ComponentManager;
import org.apache.avalon.ComponentManagerException;
import org.apache.avalon.Composer;
import org.apache.avalon.Loggable;
import org.apache.avalon.camelot.Entry;
import org.apache.avalon.camelot.LoggerBuilder;
/**
* Loggable stage for avalon pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
*/
public class LoggerStage
extends AbstractLifeCycleStage
implements Composer
{
protected LoggerBuilder m_builder;
public LoggerStage()
{
m_service = Loggable.class;
m_serviceName = "Logger";
}
public void compose( final ComponentManager componentManager )
throws ComponentManagerException
{
m_builder = (LoggerBuilder)componentManager.
lookup( "org.apache.avalon.camelot.LoggerBuilder" );
}
protected void process( final String name, final Entry entry, final
Object object )
throws Exception
{
((Loggable)object).setLogger( m_builder.createLogger( name, entry ) );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/OldConfigurationStage.java
Index: OldConfigurationStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.Configurable;
import org.apache.avalon.DefaultConfiguration;
import org.apache.avalon.camelot.Entry;
import org.apache.avalon.configuration.Configuration;
/**
* Configuration stage for avalon pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @deprecated This has been deprecated in favour of new ConfigurationStage
class
*/
public class OldConfigurationStage
extends ConfigurationStage
{
public OldConfigurationStage()
{
m_service = Configurable.class;
}
protected void process( final String name, final Entry entry, final
Object object )
throws Exception
{
final DefaultConfiguration configuration =
transform( m_repository.getConfiguration( name, entry ) );
((Configurable)object).configure( configuration );
}
public final static DefaultConfiguration transform( final Configuration
configuration )
{
final DefaultConfiguration newConfiguration =
new DefaultConfiguration( configuration.getName(),
configuration.getLocation() );
final Configuration[] children = configuration.getChildren();
for( int i = 0; i < children.length; i++ )
{
newConfiguration.addChild( transform( children[ i ] ) );
}
final String[] attributeNames = configuration.getAttributeNames();
for( int i = 0; i < attributeNames.length; i++ )
{
final String value = configuration.getAttribute( attributeNames[
i ], null );
newConfiguration.addAttribute( attributeNames[ i ], value );
}
final String value = configuration.getValue( null );
if( null != value )
{
newConfiguration.appendValueData( value );
}
return newConfiguration;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/RunnerStage.java
Index: RunnerStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.camelot.Entry;
import org.apache.avalon.util.thread.ThreadContext;
/**
* Runner stage for avalon pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
*/
public class RunnerStage
extends AbstractLifeCycleStage
{
public RunnerStage()
{
m_service = Runnable.class;
m_serviceName = "Run";
}
protected void process( final String name, final Entry entry, final
Object object )
throws Exception
{
ThreadContext.getCurrentThreadPool().execute( (Runnable)object );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/ShutdownPipeline.java
Index: ShutdownPipeline.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.camelot.AvalonState;
/**
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class ShutdownPipeline
extends LifeCyclePipeline
{
public void init()
throws Exception
{
addStage( AvalonState.STOPPED, new StopStage() );
addStage( AvalonState.DISPOSED, new DisposingStage() );
setConsumeException( true );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/StartStage.java
Index: StartStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.Startable;
import org.apache.avalon.camelot.Entry;
/**
* Start stage for avalon pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class StartStage
extends AbstractLifeCycleStage
{
public StartStage()
{
m_service = Startable.class;
m_serviceName = "Start";
}
protected void process( final String name, final Entry entry, final
Object object )
throws Exception
{
((Startable)object).start();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/StartupPipeline.java
Index: StartupPipeline.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.camelot.AvalonState;
/**
* This is basic array based pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class StartupPipeline
extends LifeCyclePipeline
{
public void init()
throws Exception
{
addStage( AvalonState.CREATED, new CreationStage() );
addStage( AvalonState.LOGGED, new LoggerStage() );
addStage( AvalonState.CONTEXTUALIZED, new ContextualizationStage() );
addStage( AvalonState.COMPOSED, new CompositionStage() );
addStage( AvalonState.CONFIGURED, new ConfigurationStage() );
//will be removed in future...
addStage( AvalonState.CONFIGURED, new OldConfigurationStage() );
addStage( AvalonState.INITIALIZED, new InitializationStage() );
addStage( AvalonState.STARTED, new StartStage() );
addStage( AvalonState.RUNNING, new RunnerStage() );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pipeline/StopStage.java
Index: StopStage.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 file.
*/
package org.apache.avalon.util.pipeline;
import org.apache.avalon.Stoppable;
import org.apache.avalon.camelot.Entry;
/**
* Stop stage for avalon pipeline.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class StopStage
extends AbstractLifeCycleStage
{
public StopStage()
{
m_service = Stoppable.class;
m_serviceName = "Stop";
}
protected void process( final String name, final Entry entry, final
Object object )
throws Exception
{
((Stoppable)object).stop();
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pool/AbstractPool.java
Index: AbstractPool.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 file.
*/
package org.apache.avalon.util.pool;
import org.apache.avalon.Poolable;
import org.apache.avalon.Recyclable;
import org.apache.avalon.Initializable;
/**
* This is an <code>Pool</code> that caches Poolable objects for reuse.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class AbstractPool
implements Pool, Initializable
{
protected int m_count;
protected Poolable[] m_pool;
protected ObjectFactory m_factory;
protected PoolController m_controller;
protected int m_maximum;
protected int m_initial;
public AbstractPool( final ObjectFactory factory,
final PoolController controller,
final int initial,
final int maximum )
{
m_count = 0;
m_factory = factory;
m_controller = controller;
m_maximum = maximum;
m_initial = initial;
}
public void init()
throws Exception
{
grow( m_maximum );
fill( m_initial );
}
/**
* Retrieve an object from pool.
*
* @return an object from Pool
*/
public Poolable get() throws Exception
{
if( null == m_pool && null != m_controller )
{
final int increase = m_controller.grow();
if( increase > 0 ) grow( increase );
}
if( 0 == m_count )
{
return m_factory.newInstance();
}
m_count--;
final Poolable poolable = m_pool[ m_count ];
m_pool[ m_count ] = null;
return poolable;
}
/**
* Place an object in pool.
*
* @param poolable the object to be placed in pool
*/
public void put( final Poolable poolable )
{
if( poolable instanceof Recyclable )
{
((Recyclable)poolable).recycle();
}
if( m_pool.length == (m_count + 1) && null != m_controller )
{
final int decrease = m_controller.shrink();
if( decrease > 0 ) shrink( decrease );
}
if ( m_pool.length > m_count + 1 )
{
m_pool[ m_count++ ] = poolable;
}
}
/**
* Return the total number of slots in Pool
*
* @return the total number of slots
*/
public final int getCapacity()
{
return m_pool.length;
}
/**
* Get the number of used slots in Pool
*
* @return the number of used slots
*/
public final int getSize()
{
return m_count;
}
/**
* This fills the pool to the size specified in parameter.
*/
public final void fill( final int fillSize ) throws Exception
{
final int size = Math.min( m_pool.length, fillSize );
for( int i = m_count; i < size; i++ )
{
m_pool[i] = m_factory.newInstance();
}
m_count = size;
}
/**
* This fills the pool by the size specified in parameter.
*/
public final void grow( final int increase )
{
if( null == m_pool )
{
m_pool = new Poolable[ increase ];
return;
}
final Poolable[] poolables = new Poolable[ increase + m_pool.length ];
System.arraycopy( m_pool, 0, poolables, 0, m_pool.length );
m_pool = poolables;
}
/**
* This shrinks the pool by parameter size.
*/
public final void shrink( final int decrease )
{
final Poolable[] poolables = new Poolable[ m_pool.length - decrease ];
System.arraycopy( m_pool, 0, poolables, 0, poolables.length );
m_pool = poolables;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pool/DefaultObjectFactory.java
Index: DefaultObjectFactory.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 file.
*/
package org.apache.avalon.util.pool;
import java.lang.reflect.Constructor;
import org.apache.avalon.Poolable;
import org.apache.avalon.Recyclable;
/**
* This is the default for factory that is used to create objects for Pool.
*
* It creates objects via reflection and constructor.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultObjectFactory
implements ObjectFactory
{
protected Constructor m_constructor;
protected Object[] m_arguements;
public DefaultObjectFactory( final Constructor constructor, final
Object[] arguements )
{
m_arguements = arguements;
m_constructor = constructor;
}
public DefaultObjectFactory( final Class clazz,
final Class[] arguementClasses,
final Object[] arguements )
throws NoSuchMethodException
{
this( clazz.getConstructor( arguementClasses ), arguements );
}
public DefaultObjectFactory( final Class clazz )
throws NoSuchMethodException
{
this( clazz, null, null );
}
public Class getCreatedClass()
{
return m_constructor.getDeclaringClass();
}
public Poolable newInstance()
{
try
{
return (Poolable)m_constructor.newInstance( m_arguements );
}
catch( final Exception e )
{
throw new Error( "Failed to instantiate the class " +
m_constructor.getDeclaringClass().getName() + "
due to " + e );
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pool/DefaultPool.java
Index: DefaultPool.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 file.
*/
package org.apache.avalon.util.pool;
import org.apache.avalon.Poolable;
import org.apache.avalon.Recyclable;
/**
* This is an <code>Pool</code> that caches Poolable objects for reuse.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultPool
extends AbstractPool
{
public final static int DEFAULT_POOL_SIZE = 8;
public DefaultPool( final ObjectFactory factory,
final PoolController controller )
throws Exception
{
super( factory, controller, DEFAULT_POOL_SIZE, DEFAULT_POOL_SIZE );
}
public DefaultPool( final ObjectFactory factory )
throws Exception
{
this( factory, null );
}
public DefaultPool( final Class clazz, final int initial, final int
maximum )
throws NoSuchMethodException, Exception
{
super( new DefaultObjectFactory( clazz ), null, initial, maximum );
}
public DefaultPool( final Class clazz, final int initial )
throws NoSuchMethodException, Exception
{
this( clazz, initial, initial );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pool/ObjectFactory.java
Index: ObjectFactory.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 file.
*/
package org.apache.avalon.util.pool;
import org.apache.avalon.Component;
import org.apache.avalon.Poolable;
/**
* This is the interface for factory that is used to create objects for Pool.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface ObjectFactory
extends Component
{
Poolable newInstance() throws Exception;
Class getCreatedClass();
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pool/Pool.java
Index: Pool.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 file.
*/
package org.apache.avalon.util.pool;
import org.apache.avalon.Component;
import org.apache.avalon.Poolable;
/**
* This is an <code>Pool</code> that caches Poolable objects for reuse.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface Pool
extends Component
{
Poolable get() throws Exception;
void put( Poolable poolable );
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pool/PoolController.java
Index: PoolController.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 file.
*/
package org.apache.avalon.util.pool;
/**
* This is the interface you implement if you want to control how Pools
capacity
* changes overtime.
*
* It gets called everytime that a Pool tries to go below or above it's
minimum or maximum.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
*/
public interface PoolController
{
/**
* Called when a Pool reaches it's minimum.
*
* Return the number of elements to increase minimum and maximum by.
*
* @return the element increase
*/
int grow();
/**
* Called when a pool reaches it's maximum.
*
* Returns the number of elements to decrease mi and max by.
*
* @return the element decrease
*/
int shrink();
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pool/ThreadSafePool.java
Index: ThreadSafePool.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 file.
*/
package org.apache.avalon.util.pool;
import org.apache.avalon.Poolable;
import org.apache.avalon.Recyclable;
import org.apache.avalon.ThreadSafe;
/**
* This is a implementation of <code>Pool</code> that is thread safe.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class ThreadSafePool
extends AbstractPool
implements ThreadSafe
{
public final static int DEFAULT_POOL_SIZE = 8;
protected boolean m_blocking = false;
public ThreadSafePool( final ObjectFactory factory, final PoolController
controller )
throws Exception
{
super( factory, controller, DEFAULT_POOL_SIZE, DEFAULT_POOL_SIZE );
}
public ThreadSafePool( final ObjectFactory factory )
throws Exception
{
this( factory, null );
}
public ThreadSafePool( final ObjectFactory factory,
final int initial,
final int maximum )
throws Exception
{
super( factory, null, initial, maximum );
}
public ThreadSafePool( final ObjectFactory factory, final int initial )
throws Exception
{
this( factory, initial, initial );
}
public ThreadSafePool( final Class clazz, final int initial, final int
maximum )
throws NoSuchMethodException, Exception
{
this( new DefaultObjectFactory( clazz ), initial, maximum );
}
public ThreadSafePool( final Class clazz, final int initial )
throws NoSuchMethodException, Exception
{
this( clazz, initial, initial );
}
public final boolean isBlocking()
{
return m_blocking;
}
/**
* Set whether this pool is blocking.
*
* If this pool is blocking and empties the Pool then the thread will
block until
* an object is placed back in the pool. This has to be used with care as
an errant
* thread who never does a put will force blocked clients to wait forever.
*
* @param blocking a boolean indicating if it is blocking or not
*/
public final void setBlocking( final boolean blocking )
{
m_blocking = blocking;
}
/**
* Retrieve an object from pool.
*
* @return an object from Pool
*/
public final Poolable get() throws Exception
{
//Require this or else the wait later will cause
final Poolable[] pool = m_pool;
synchronized( pool )
{
if( 0 == m_count )
{
if( !m_blocking )
{
return m_factory.newInstance();
}
else
{
while( 0 == m_count )
{
try { pool.wait(); }
catch( final InterruptedException ie ) { }
}
}
}
m_count--;
final Poolable poolable = m_pool[ m_count ];
m_pool[ m_count ] = null;
return poolable;
}
}
/**
* Place an object in pool.
*
* @param poolable the object to be placed in pool
*/
public final void put( final Poolable poolable )
{
final Poolable[] pool = m_pool;
synchronized( pool )
{
super.put( poolable );
//if someone was waiting on the old pool then we have to notify
them
pool.notifyAll();
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/pool/test/PoolProfile.java
Index: PoolProfile.java
===================================================================
/*
* Copyright 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 file.
*/
package org.apache.avalon.util.pool.test;
import org.apache.avalon.Poolable;
import org.apache.avalon.util.pool.DefaultPool;
import org.apache.avalon.util.pool.Pool;
import org.apache.avalon.util.pool.ThreadSafePool;
import org.apache.testlet.*;
/**
* This is used to profile the Pool implementation.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class PoolProfile
extends AbstractTestlet
{
public static class A
implements Poolable
{
int a;
int b;
int c;
float x;
float y;
float z;
}
public static class B
implements Poolable
{
int a;
int b;
int c;
float x;
float y;
float z;
Object o1;
Object o2;
Object o3;
public void recycle()
{
o1 = o2 = o3 = null;
}
}
public static class C
implements Poolable
{
int a;
int b;
int c;
float x;
float y;
float z;
Object o1;
Object o2;
Object o3;
Object o4;
Object o5;
Object o6;
public void build()
{
o1 = new Object();
o2 = new Object();
o3 = new Object();
o4 = new Object();
o5 = new Object();
o6 = new Object();
}
public void recycle()
{
o1 = o2 = o3 = o4 = o5 = o6 = null;
}
}
protected static final int TEST_SIZE = 1000000;
public void testSmallObjects()
throws Exception
{
System.out.println("SMALL Sized Objects");
final DefaultPool pool1 = new DefaultPool( A.class, 5, 10 );
final long pool1Start = System.currentTimeMillis();
final int pool1Factor = 1;
final int pool1Loops = TEST_SIZE / pool1Factor;
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = pool1.get();
pool1.put(a1);
}
final long pool1End = System.currentTimeMillis();
final long pool1Duration = pool1End - pool1Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 1: " +
Runtime.getRuntime().freeMemory() );
final DefaultPool pool2 = new DefaultPool( A.class, 5, 10 );
final long pool2Start = System.currentTimeMillis();
final int pool2Factor = 10;
final int pool2Loops = TEST_SIZE / pool2Factor;
for( int i = 0; i < pool2Loops; i++ )
{
final Poolable a1 = pool2.get();
final Poolable a2 = pool2.get();
final Poolable a3 = pool2.get();
final Poolable a4 = pool2.get();
final Poolable a5 = pool2.get();
final Poolable a6 = pool2.get();
final Poolable a7 = pool2.get();
final Poolable a8 = pool2.get();
final Poolable a9 = pool2.get();
final Poolable a0 = pool2.get();
pool2.put(a1);
pool2.put(a2);
pool2.put(a3);
pool2.put(a4);
pool2.put(a5);
pool2.put(a6);
pool2.put(a7);
pool2.put(a8);
pool2.put(a9);
pool2.put(a0);
}
final long pool2End = System.currentTimeMillis();
final long pool2Duration = pool2End - pool2Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 2: " +
Runtime.getRuntime().freeMemory() );
final DefaultPool pool3 = new DefaultPool( A.class, 5, 10 );
final long pool3Start = System.currentTimeMillis();
final int pool3Factor = 15;
final int pool3Loops = TEST_SIZE / pool3Factor;
for( int i = 0; i < pool3Loops; i++ )
{
final Poolable a1 = pool3.get();
final Poolable a2 = pool3.get();
final Poolable a3 = pool3.get();
final Poolable a4 = pool3.get();
final Poolable a5 = pool3.get();
final Poolable a6 = pool3.get();
final Poolable a7 = pool3.get();
final Poolable a8 = pool3.get();
final Poolable a9 = pool3.get();
final Poolable a10 = pool3.get();
final Poolable a11 = pool3.get();
final Poolable a12 = pool3.get();
final Poolable a13 = pool3.get();
final Poolable a14 = pool3.get();
final Poolable a15 = pool3.get();
pool3.put(a1);
pool3.put(a2);
pool3.put(a3);
pool3.put(a4);
pool3.put(a5);
pool3.put(a6);
pool3.put(a7);
pool3.put(a8);
pool3.put(a9);
pool3.put(a10);
pool3.put(a11);
pool3.put(a12);
pool3.put(a13);
pool3.put(a14);
pool3.put(a15);
}
final long pool3End = System.currentTimeMillis();
final long pool3Duration = pool3End - pool3Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 3: " +
Runtime.getRuntime().freeMemory() );
final DefaultPool pool4 = new DefaultPool( A.class, 5, 10 );
final long pool4Start = System.currentTimeMillis();
final int pool4Factor = 20;
final int pool4Loops = TEST_SIZE / pool4Factor;
for( int i = 0; i < pool4Loops; i++ )
{
final Poolable a1 = pool4.get();
final Poolable a2 = pool4.get();
final Poolable a3 = pool4.get();
final Poolable a4 = pool4.get();
final Poolable a5 = pool4.get();
final Poolable a6 = pool4.get();
final Poolable a7 = pool4.get();
final Poolable a8 = pool4.get();
final Poolable a9 = pool4.get();
final Poolable a10 = pool4.get();
final Poolable a11 = pool4.get();
final Poolable a12 = pool4.get();
final Poolable a13 = pool4.get();
final Poolable a14 = pool4.get();
final Poolable a15 = pool4.get();
final Poolable a16 = pool4.get();
final Poolable a17 = pool4.get();
final Poolable a18 = pool4.get();
final Poolable a19 = pool4.get();
final Poolable a20 = pool4.get();
pool4.put(a1);
pool4.put(a2);
pool4.put(a3);
pool4.put(a4);
pool4.put(a5);
pool4.put(a6);
pool4.put(a7);
pool4.put(a8);
pool4.put(a9);
pool4.put(a10);
pool4.put(a11);
pool4.put(a12);
pool4.put(a13);
pool4.put(a14);
pool4.put(a15);
pool4.put(a16);
pool4.put(a17);
pool4.put(a18);
pool4.put(a19);
pool4.put(a20);
}
final long pool4End = System.currentTimeMillis();
final long pool4Duration = pool4End - pool4Start;
System.out.println("FreeMem post 4: " +
Runtime.getRuntime().freeMemory() );
final long createStart = System.currentTimeMillis();
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = new C();
}
final long createEnd = System.currentTimeMillis();
final long createDuration = createEnd - createStart;
//System.out.println("Create Duration: " + createDuration + "ms ");
System.out.println("FreeMem post create: " +
Runtime.getRuntime().freeMemory() );
final double pool1Efficiancy =
(double)createDuration/(double)pool1Duration * 100.0;
final double pool2Efficiancy =
(double)createDuration/(double)pool2Duration * 100.0;
final double pool3Efficiancy =
(double)createDuration/(double)pool3Duration * 100.0;
final double pool4Efficiancy =
(double)createDuration/(double)pool4Duration * 100.0;
//System.out.println("Pool Duration for 100% hits: " + pool1Duration
+ "ms ");
System.out.println("Pool Efficiancy for 100% hits: " +
pool1Efficiancy + "ms ");
//System.out.println("Pool Duration for 100% hits and saturated: " +
pool2Duration + "ms ");
System.out.println("Pool Efficiancy for 100% hits and saturated: " +
pool2Efficiancy + "ms ");
//System.out.println("Pool Duration for 60% hits: " + pool3Duration +
"ms ");
System.out.println("Pool Efficiancy for 60% hits: " + pool3Efficiancy
+ "ms ");
//System.out.println("Pool Duration for 50% hits: " + pool4Duration +
"ms ");
System.out.println("Pool Efficiancy for 50% hits: " + pool4Efficiancy
+ "ms ");
}
public void testMediumObjects()
throws Exception
{
System.out.println("MEDIUM Sized Objects");
System.gc();
System.gc();
Thread.currentThread().sleep(2);
final DefaultPool pool1 = new DefaultPool( B.class, 5, 10 );
final long pool1Start = System.currentTimeMillis();
final int pool1Factor = 1;
final int pool1Loops = TEST_SIZE / pool1Factor;
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = pool1.get();
pool1.put(a1);
}
final long pool1End = System.currentTimeMillis();
final long pool1Duration = pool1End - pool1Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 1: " +
Runtime.getRuntime().freeMemory() );
final DefaultPool pool2 = new DefaultPool( B.class, 5, 10 );
final long pool2Start = System.currentTimeMillis();
final int pool2Factor = 10;
final int pool2Loops = TEST_SIZE / pool2Factor;
for( int i = 0; i < pool2Loops; i++ )
{
final Poolable a1 = pool2.get();
final Poolable a2 = pool2.get();
final Poolable a3 = pool2.get();
final Poolable a4 = pool2.get();
final Poolable a5 = pool2.get();
final Poolable a6 = pool2.get();
final Poolable a7 = pool2.get();
final Poolable a8 = pool2.get();
final Poolable a9 = pool2.get();
final Poolable a10 = pool2.get();
pool2.put(a1);
pool2.put(a2);
pool2.put(a3);
pool2.put(a4);
pool2.put(a5);
pool2.put(a6);
pool2.put(a7);
pool2.put(a8);
pool2.put(a9);
pool2.put(a10);
}
final long pool2End = System.currentTimeMillis();
final long pool2Duration = pool2End - pool2Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 2: " +
Runtime.getRuntime().freeMemory() );
final DefaultPool pool3 = new DefaultPool( B.class, 5, 10 );
final long pool3Start = System.currentTimeMillis();
final int pool3Factor = 15;
final int pool3Loops = TEST_SIZE / pool3Factor;
for( int i = 0; i < pool3Loops; i++ )
{
final Poolable a1 = pool3.get();
final Poolable a2 = pool3.get();
final Poolable a3 = pool3.get();
final Poolable a4 = pool3.get();
final Poolable a5 = pool3.get();
final Poolable a6 = pool3.get();
final Poolable a7 = pool3.get();
final Poolable a8 = pool3.get();
final Poolable a9 = pool3.get();
final Poolable a10 = pool3.get();
final Poolable a11 = pool3.get();
final Poolable a12 = pool3.get();
final Poolable a13 = pool3.get();
final Poolable a14 = pool3.get();
final Poolable a15 = pool3.get();
pool3.put(a1);
pool3.put(a2);
pool3.put(a3);
pool3.put(a4);
pool3.put(a5);
pool3.put(a6);
pool3.put(a7);
pool3.put(a8);
pool3.put(a9);
pool3.put(a10);
pool3.put(a11);
pool3.put(a12);
pool3.put(a13);
pool3.put(a14);
pool3.put(a15);
}
final long pool3End = System.currentTimeMillis();
final long pool3Duration = pool3End - pool3Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 3: " +
Runtime.getRuntime().freeMemory() );
final DefaultPool pool4 = new DefaultPool( B.class, 5, 10 );
final long pool4Start = System.currentTimeMillis();
final int pool4Factor = 20;
final int pool4Loops = TEST_SIZE / pool4Factor;
for( int i = 0; i < pool4Loops; i++ )
{
final Poolable a1 = pool4.get();
final Poolable a2 = pool4.get();
final Poolable a3 = pool4.get();
final Poolable a4 = pool4.get();
final Poolable a5 = pool4.get();
final Poolable a6 = pool4.get();
final Poolable a7 = pool4.get();
final Poolable a8 = pool4.get();
final Poolable a9 = pool4.get();
final Poolable a10 = pool4.get();
final Poolable a11 = pool4.get();
final Poolable a12 = pool4.get();
final Poolable a13 = pool4.get();
final Poolable a14 = pool4.get();
final Poolable a15 = pool4.get();
final Poolable a16 = pool4.get();
final Poolable a17 = pool4.get();
final Poolable a18 = pool4.get();
final Poolable a19 = pool4.get();
final Poolable a20 = pool4.get();
pool4.put(a1);
pool4.put(a2);
pool4.put(a3);
pool4.put(a4);
pool4.put(a5);
pool4.put(a6);
pool4.put(a7);
pool4.put(a8);
pool4.put(a9);
pool4.put(a10);
pool4.put(a11);
pool4.put(a12);
pool4.put(a13);
pool4.put(a14);
pool4.put(a15);
pool4.put(a16);
pool4.put(a17);
pool4.put(a18);
pool4.put(a19);
pool4.put(a20);
}
final long pool4End = System.currentTimeMillis();
final long pool4Duration = pool4End - pool4Start;
final long createStart = System.currentTimeMillis();
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = new C();
}
final long createEnd = System.currentTimeMillis();
final long createDuration = createEnd - createStart;
//System.out.println("Create Duration: " + createDuration + "ms ");
System.out.println("FreeMem post create: " +
Runtime.getRuntime().freeMemory() );
final double pool1Efficiancy =
(double)createDuration/(double)pool1Duration * 100.0;
final double pool2Efficiancy =
(double)createDuration/(double)pool2Duration * 100.0;
final double pool3Efficiancy =
(double)createDuration/(double)pool3Duration * 100.0;
final double pool4Efficiancy =
(double)createDuration/(double)pool4Duration * 100.0;
//System.out.println("Pool Duration for 100% hits: " + pool1Duration
+ "ms ");
System.out.println("Pool Efficiancy for 100% hits: " +
pool1Efficiancy + "ms ");
//System.out.println("Pool Duration for 100% hits and saturated: " +
pool2Duration + "ms ");
System.out.println("Pool Efficiancy for 100% hits and saturated: " +
pool2Efficiancy + "ms ");
//System.out.println("Pool Duration for 60% hits: " + pool3Duration +
"ms ");
System.out.println("Pool Efficiancy for 60% hits: " + pool3Efficiancy
+ "ms ");
//System.out.println("Pool Duration for 50% hits: " + pool4Duration +
"ms ");
System.out.println("Pool Efficiancy for 50% hits: " + pool4Efficiancy
+ "ms ");
}
public void testLargeObjects()
throws Exception
{
System.out.println("LARGE Sized Objects");
System.gc();
System.gc();
Thread.currentThread().sleep(2);
final DefaultPool pool1 = new DefaultPool( C.class, 5, 10 );
final long pool1Start = System.currentTimeMillis();
final int pool1Factor = 1;
final int pool1Loops = TEST_SIZE / pool1Factor;
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = pool1.get();
pool1.put(a1);
}
final long pool1End = System.currentTimeMillis();
final long pool1Duration = pool1End - pool1Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 1: " +
Runtime.getRuntime().freeMemory() );
final DefaultPool pool2 = new DefaultPool( C.class, 5, 10 );
final long pool2Start = System.currentTimeMillis();
final int pool2Factor = 10;
final int pool2Loops = TEST_SIZE / pool2Factor;
for( int i = 0; i < pool2Loops; i++ )
{
final Poolable a1 = pool2.get();
final Poolable a2 = pool2.get();
final Poolable a3 = pool2.get();
final Poolable a4 = pool2.get();
final Poolable a5 = pool2.get();
final Poolable a6 = pool2.get();
final Poolable a7 = pool2.get();
final Poolable a8 = pool2.get();
final Poolable a9 = pool2.get();
final Poolable a10 = pool2.get();
pool2.put(a1);
pool2.put(a2);
pool2.put(a3);
pool2.put(a4);
pool2.put(a5);
pool2.put(a6);
pool2.put(a7);
pool2.put(a8);
pool2.put(a9);
pool2.put(a10);
}
final long pool2End = System.currentTimeMillis();
final long pool2Duration = pool2End - pool2Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 2: " +
Runtime.getRuntime().freeMemory() );
final DefaultPool pool3 = new DefaultPool( C.class, 5, 10 );
final long pool3Start = System.currentTimeMillis();
final int pool3Factor = 15;
final int pool3Loops = TEST_SIZE / pool3Factor;
for( int i = 0; i < pool3Loops; i++ )
{
final Poolable a1 = pool3.get();
final Poolable a2 = pool3.get();
final Poolable a3 = pool3.get();
final Poolable a4 = pool3.get();
final Poolable a5 = pool3.get();
final Poolable a6 = pool3.get();
final Poolable a7 = pool3.get();
final Poolable a8 = pool3.get();
final Poolable a9 = pool3.get();
final Poolable a10 = pool3.get();
final Poolable a11 = pool3.get();
final Poolable a12 = pool3.get();
final Poolable a13 = pool3.get();
final Poolable a14 = pool3.get();
final Poolable a15 = pool3.get();
pool3.put(a1);
pool3.put(a2);
pool3.put(a3);
pool3.put(a4);
pool3.put(a5);
pool3.put(a6);
pool3.put(a7);
pool3.put(a8);
pool3.put(a9);
pool3.put(a10);
pool3.put(a11);
pool3.put(a12);
pool3.put(a13);
pool3.put(a14);
pool3.put(a15);
}
final long pool3End = System.currentTimeMillis();
final long pool3Duration = pool3End - pool3Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 3: " +
Runtime.getRuntime().freeMemory() );
final DefaultPool pool4 = new DefaultPool( C.class, 5, 10 );
final long pool4Start = System.currentTimeMillis();
final int pool4Factor = 20;
final int pool4Loops = TEST_SIZE / pool4Factor;
for( int i = 0; i < pool4Loops; i++ )
{
final Poolable a1 = pool4.get();
final Poolable a2 = pool4.get();
final Poolable a3 = pool4.get();
final Poolable a4 = pool4.get();
final Poolable a5 = pool4.get();
final Poolable a6 = pool4.get();
final Poolable a7 = pool4.get();
final Poolable a8 = pool4.get();
final Poolable a9 = pool4.get();
final Poolable a10 = pool4.get();
final Poolable a11 = pool4.get();
final Poolable a12 = pool4.get();
final Poolable a13 = pool4.get();
final Poolable a14 = pool4.get();
final Poolable a15 = pool4.get();
final Poolable a16 = pool4.get();
final Poolable a17 = pool4.get();
final Poolable a18 = pool4.get();
final Poolable a19 = pool4.get();
final Poolable a20 = pool4.get();
pool4.put(a1);
pool4.put(a2);
pool4.put(a3);
pool4.put(a4);
pool4.put(a5);
pool4.put(a6);
pool4.put(a7);
pool4.put(a8);
pool4.put(a9);
pool4.put(a10);
pool4.put(a11);
pool4.put(a12);
pool4.put(a13);
pool4.put(a14);
pool4.put(a15);
pool4.put(a16);
pool4.put(a17);
pool4.put(a18);
pool4.put(a19);
pool4.put(a20);
}
final long pool4End = System.currentTimeMillis();
final long pool4Duration = pool4End - pool4Start;
System.out.println("FreeMem post 4: " +
Runtime.getRuntime().freeMemory() );
final long createStart = System.currentTimeMillis();
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = new C();
}
final long createEnd = System.currentTimeMillis();
final long createDuration = createEnd - createStart;
System.out.println("FreeMem post create: " +
Runtime.getRuntime().freeMemory() );
final double pool1Efficiancy =
(double)createDuration/(double)pool1Duration * 100.0;
final double pool2Efficiancy =
(double)createDuration/(double)pool2Duration * 100.0;
final double pool3Efficiancy =
(double)createDuration/(double)pool3Duration * 100.0;
final double pool4Efficiancy =
(double)createDuration/(double)pool4Duration * 100.0;
System.out.println("Pool Efficiancy for 100% hits: " +
pool1Efficiancy + "ms ");
System.out.println("Pool Efficiancy for 100% hits and saturated: " +
pool2Efficiancy + "ms ");
System.out.println("Pool Efficiancy for 60% hits: " + pool3Efficiancy
+ "ms ");
System.out.println("Pool Efficiancy for 50% hits: " + pool4Efficiancy
+ "ms ");
}
public void testThreadedSmallObjects()
throws Exception
{
System.out.println("SMALL Sized Objects with thread safe pools");
final ThreadSafePool pool1 = new ThreadSafePool( A.class, 5, 10 );
final long pool1Start = System.currentTimeMillis();
final int pool1Factor = 1;
final int pool1Loops = TEST_SIZE / pool1Factor;
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = pool1.get();
pool1.put(a1);
}
final long pool1End = System.currentTimeMillis();
final long pool1Duration = pool1End - pool1Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 1: " +
Runtime.getRuntime().freeMemory() );
final ThreadSafePool pool2 = new ThreadSafePool( A.class, 5, 10 );
final long pool2Start = System.currentTimeMillis();
final int pool2Factor = 10;
final int pool2Loops = TEST_SIZE / pool2Factor;
for( int i = 0; i < pool2Loops; i++ )
{
final Poolable a1 = pool2.get();
final Poolable a2 = pool2.get();
final Poolable a3 = pool2.get();
final Poolable a4 = pool2.get();
final Poolable a5 = pool2.get();
final Poolable a6 = pool2.get();
final Poolable a7 = pool2.get();
final Poolable a8 = pool2.get();
final Poolable a9 = pool2.get();
final Poolable a0 = pool2.get();
pool2.put(a1);
pool2.put(a2);
pool2.put(a3);
pool2.put(a4);
pool2.put(a5);
pool2.put(a6);
pool2.put(a7);
pool2.put(a8);
pool2.put(a9);
pool2.put(a0);
}
final long pool2End = System.currentTimeMillis();
final long pool2Duration = pool2End - pool2Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 2: " +
Runtime.getRuntime().freeMemory() );
final ThreadSafePool pool3 = new ThreadSafePool( A.class, 5, 10 );
final long pool3Start = System.currentTimeMillis();
final int pool3Factor = 15;
final int pool3Loops = TEST_SIZE / pool3Factor;
for( int i = 0; i < pool3Loops; i++ )
{
final Poolable a1 = pool3.get();
final Poolable a2 = pool3.get();
final Poolable a3 = pool3.get();
final Poolable a4 = pool3.get();
final Poolable a5 = pool3.get();
final Poolable a6 = pool3.get();
final Poolable a7 = pool3.get();
final Poolable a8 = pool3.get();
final Poolable a9 = pool3.get();
final Poolable a10 = pool3.get();
final Poolable a11 = pool3.get();
final Poolable a12 = pool3.get();
final Poolable a13 = pool3.get();
final Poolable a14 = pool3.get();
final Poolable a15 = pool3.get();
pool3.put(a1);
pool3.put(a2);
pool3.put(a3);
pool3.put(a4);
pool3.put(a5);
pool3.put(a6);
pool3.put(a7);
pool3.put(a8);
pool3.put(a9);
pool3.put(a10);
pool3.put(a11);
pool3.put(a12);
pool3.put(a13);
pool3.put(a14);
pool3.put(a15);
}
final long pool3End = System.currentTimeMillis();
final long pool3Duration = pool3End - pool3Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 3: " +
Runtime.getRuntime().freeMemory() );
final ThreadSafePool pool4 = new ThreadSafePool( A.class, 5, 10 );
final long pool4Start = System.currentTimeMillis();
final int pool4Factor = 20;
final int pool4Loops = TEST_SIZE / pool4Factor;
for( int i = 0; i < pool4Loops; i++ )
{
final Poolable a1 = pool4.get();
final Poolable a2 = pool4.get();
final Poolable a3 = pool4.get();
final Poolable a4 = pool4.get();
final Poolable a5 = pool4.get();
final Poolable a6 = pool4.get();
final Poolable a7 = pool4.get();
final Poolable a8 = pool4.get();
final Poolable a9 = pool4.get();
final Poolable a10 = pool4.get();
final Poolable a11 = pool4.get();
final Poolable a12 = pool4.get();
final Poolable a13 = pool4.get();
final Poolable a14 = pool4.get();
final Poolable a15 = pool4.get();
final Poolable a16 = pool4.get();
final Poolable a17 = pool4.get();
final Poolable a18 = pool4.get();
final Poolable a19 = pool4.get();
final Poolable a20 = pool4.get();
pool4.put(a1);
pool4.put(a2);
pool4.put(a3);
pool4.put(a4);
pool4.put(a5);
pool4.put(a6);
pool4.put(a7);
pool4.put(a8);
pool4.put(a9);
pool4.put(a10);
pool4.put(a11);
pool4.put(a12);
pool4.put(a13);
pool4.put(a14);
pool4.put(a15);
pool4.put(a16);
pool4.put(a17);
pool4.put(a18);
pool4.put(a19);
pool4.put(a20);
}
final long pool4End = System.currentTimeMillis();
final long pool4Duration = pool4End - pool4Start;
System.out.println("FreeMem post 4: " +
Runtime.getRuntime().freeMemory() );
final long createStart = System.currentTimeMillis();
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = new C();
}
final long createEnd = System.currentTimeMillis();
final long createDuration = createEnd - createStart;
//System.out.println("Create Duration: " + createDuration + "ms ");
System.out.println("FreeMem post create: " +
Runtime.getRuntime().freeMemory() );
final double pool1Efficiancy =
(double)createDuration/(double)pool1Duration * 100.0;
final double pool2Efficiancy =
(double)createDuration/(double)pool2Duration * 100.0;
final double pool3Efficiancy =
(double)createDuration/(double)pool3Duration * 100.0;
final double pool4Efficiancy =
(double)createDuration/(double)pool4Duration * 100.0;
//System.out.println("Pool Duration for 100% hits: " + pool1Duration
+ "ms ");
System.out.println("Pool Efficiancy for 100% hits: " +
pool1Efficiancy + "ms ");
//System.out.println("Pool Duration for 100% hits and saturated: " +
pool2Duration + "ms ");
System.out.println("Pool Efficiancy for 100% hits and saturated: " +
pool2Efficiancy + "ms ");
//System.out.println("Pool Duration for 60% hits: " + pool3Duration +
"ms ");
System.out.println("Pool Efficiancy for 60% hits: " + pool3Efficiancy
+ "ms ");
//System.out.println("Pool Duration for 50% hits: " + pool4Duration +
"ms ");
System.out.println("Pool Efficiancy for 50% hits: " + pool4Efficiancy
+ "ms ");
}
public void testThreadedMediumObjects()
throws Exception
{
System.out.println("MEDIUM Sized Objects with thread safe pools");
System.gc();
System.gc();
Thread.currentThread().sleep(2);
final ThreadSafePool pool1 = new ThreadSafePool( B.class, 5, 10 );
final long pool1Start = System.currentTimeMillis();
final int pool1Factor = 1;
final int pool1Loops = TEST_SIZE / pool1Factor;
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = pool1.get();
pool1.put(a1);
}
final long pool1End = System.currentTimeMillis();
final long pool1Duration = pool1End - pool1Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 1: " +
Runtime.getRuntime().freeMemory() );
final ThreadSafePool pool2 = new ThreadSafePool( B.class, 5, 10 );
final long pool2Start = System.currentTimeMillis();
final int pool2Factor = 10;
final int pool2Loops = TEST_SIZE / pool2Factor;
for( int i = 0; i < pool2Loops; i++ )
{
final Poolable a1 = pool2.get();
final Poolable a2 = pool2.get();
final Poolable a3 = pool2.get();
final Poolable a4 = pool2.get();
final Poolable a5 = pool2.get();
final Poolable a6 = pool2.get();
final Poolable a7 = pool2.get();
final Poolable a8 = pool2.get();
final Poolable a9 = pool2.get();
final Poolable a10 = pool2.get();
/*
a1.build();
a2.build();
a3.build();
a4.build();
a5.build();
a6.build();
a7.build();
a8.build();
a9.build();
a10.build();
*/
pool2.put(a1);
pool2.put(a2);
pool2.put(a3);
pool2.put(a4);
pool2.put(a5);
pool2.put(a6);
pool2.put(a7);
pool2.put(a8);
pool2.put(a9);
pool2.put(a10);
}
final long pool2End = System.currentTimeMillis();
final long pool2Duration = pool2End - pool2Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 2: " +
Runtime.getRuntime().freeMemory() );
final ThreadSafePool pool3 = new ThreadSafePool( B.class, 5, 10 );
final long pool3Start = System.currentTimeMillis();
final int pool3Factor = 15;
final int pool3Loops = TEST_SIZE / pool3Factor;
for( int i = 0; i < pool3Loops; i++ )
{
final Poolable a1 = pool3.get();
final Poolable a2 = pool3.get();
final Poolable a3 = pool3.get();
final Poolable a4 = pool3.get();
final Poolable a5 = pool3.get();
final Poolable a6 = pool3.get();
final Poolable a7 = pool3.get();
final Poolable a8 = pool3.get();
final Poolable a9 = pool3.get();
final Poolable a10 = pool3.get();
final Poolable a11 = pool3.get();
final Poolable a12 = pool3.get();
final Poolable a13 = pool3.get();
final Poolable a14 = pool3.get();
final Poolable a15 = pool3.get();
/*
a1.build();
a2.build();
a3.build();
a4.build();
a5.build();
a6.build();
a7.build();
a8.build();
a9.build();
a10.build();
a11.build();
a12.build();
a13.build();
a14.build();
a15.build();
*/
pool3.put(a1);
pool3.put(a2);
pool3.put(a3);
pool3.put(a4);
pool3.put(a5);
pool3.put(a6);
pool3.put(a7);
pool3.put(a8);
pool3.put(a9);
pool3.put(a10);
pool3.put(a11);
pool3.put(a12);
pool3.put(a13);
pool3.put(a14);
pool3.put(a15);
}
final long pool3End = System.currentTimeMillis();
final long pool3Duration = pool3End - pool3Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 3: " +
Runtime.getRuntime().freeMemory() );
final ThreadSafePool pool4 = new ThreadSafePool( B.class, 5, 10 );
final long pool4Start = System.currentTimeMillis();
final int pool4Factor = 20;
final int pool4Loops = TEST_SIZE / pool4Factor;
for( int i = 0; i < pool4Loops; i++ )
{
final Poolable a1 = pool4.get();
final Poolable a2 = pool4.get();
final Poolable a3 = pool4.get();
final Poolable a4 = pool4.get();
final Poolable a5 = pool4.get();
final Poolable a6 = pool4.get();
final Poolable a7 = pool4.get();
final Poolable a8 = pool4.get();
final Poolable a9 = pool4.get();
final Poolable a10 = pool4.get();
final Poolable a11 = pool4.get();
final Poolable a12 = pool4.get();
final Poolable a13 = pool4.get();
final Poolable a14 = pool4.get();
final Poolable a15 = pool4.get();
final Poolable a16 = pool4.get();
final Poolable a17 = pool4.get();
final Poolable a18 = pool4.get();
final Poolable a19 = pool4.get();
final Poolable a20 = pool4.get();
/*
a1.build();
a2.build();
a3.build();
a4.build();
a5.build();
a6.build();
a7.build();
a8.build();
a9.build();
a10.build();
a11.build();
a12.build();
a13.build();
a14.build();
a15.build();
a16.build();
a17.build();
a18.build();
a19.build();
a20.build();
*/
pool4.put(a1);
pool4.put(a2);
pool4.put(a3);
pool4.put(a4);
pool4.put(a5);
pool4.put(a6);
pool4.put(a7);
pool4.put(a8);
pool4.put(a9);
pool4.put(a10);
pool4.put(a11);
pool4.put(a12);
pool4.put(a13);
pool4.put(a14);
pool4.put(a15);
pool4.put(a16);
pool4.put(a17);
pool4.put(a18);
pool4.put(a19);
pool4.put(a20);
}
final long pool4End = System.currentTimeMillis();
final long pool4Duration = pool4End - pool4Start;
final long createStart = System.currentTimeMillis();
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = new C();
}
final long createEnd = System.currentTimeMillis();
final long createDuration = createEnd - createStart;
//System.out.println("Create Duration: " + createDuration + "ms ");
System.out.println("FreeMem post create: " +
Runtime.getRuntime().freeMemory() );
final double pool1Efficiancy =
(double)createDuration/(double)pool1Duration * 100.0;
final double pool2Efficiancy =
(double)createDuration/(double)pool2Duration * 100.0;
final double pool3Efficiancy =
(double)createDuration/(double)pool3Duration * 100.0;
final double pool4Efficiancy =
(double)createDuration/(double)pool4Duration * 100.0;
//System.out.println("Pool Duration for 100% hits: " + pool1Duration
+ "ms ");
System.out.println("Pool Efficiancy for 100% hits: " +
pool1Efficiancy + "ms ");
//System.out.println("Pool Duration for 100% hits and saturated: " +
pool2Duration + "ms ");
System.out.println("Pool Efficiancy for 100% hits and saturated: " +
pool2Efficiancy + "ms ");
//System.out.println("Pool Duration for 60% hits: " + pool3Duration +
"ms ");
System.out.println("Pool Efficiancy for 60% hits: " + pool3Efficiancy
+ "ms ");
//System.out.println("Pool Duration for 50% hits: " + pool4Duration +
"ms ");
System.out.println("Pool Efficiancy for 50% hits: " + pool4Efficiancy
+ "ms ");
}
public void testThreadedLargeObjects()
throws Exception
{
System.out.println("LARGE Sized Objects with thread safe pools");
System.gc();
System.gc();
Thread.currentThread().sleep(2);
final ThreadSafePool pool1 = new ThreadSafePool( C.class, 5, 10 );
final long pool1Start = System.currentTimeMillis();
final int pool1Factor = 1;
final int pool1Loops = TEST_SIZE / pool1Factor;
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = pool1.get();
//a1.build();
pool1.put(a1);
}
final long pool1End = System.currentTimeMillis();
final long pool1Duration = pool1End - pool1Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 1: " +
Runtime.getRuntime().freeMemory() );
final ThreadSafePool pool2 = new ThreadSafePool( C.class, 5, 10 );
final long pool2Start = System.currentTimeMillis();
final int pool2Factor = 10;
final int pool2Loops = TEST_SIZE / pool2Factor;
for( int i = 0; i < pool2Loops; i++ )
{
final Poolable a1 = pool2.get();
final Poolable a2 = pool2.get();
final Poolable a3 = pool2.get();
final Poolable a4 = pool2.get();
final Poolable a5 = pool2.get();
final Poolable a6 = pool2.get();
final Poolable a7 = pool2.get();
final Poolable a8 = pool2.get();
final Poolable a9 = pool2.get();
final Poolable a10 = pool2.get();
/*
a1.build();
a2.build();
a3.build();
a4.build();
a5.build();
a6.build();
a7.build();
a8.build();
a9.build();
a10.build();
*/
pool2.put(a1);
pool2.put(a2);
pool2.put(a3);
pool2.put(a4);
pool2.put(a5);
pool2.put(a6);
pool2.put(a7);
pool2.put(a8);
pool2.put(a9);
pool2.put(a10);
}
final long pool2End = System.currentTimeMillis();
final long pool2Duration = pool2End - pool2Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 2: " +
Runtime.getRuntime().freeMemory() );
final ThreadSafePool pool3 = new ThreadSafePool( C.class, 5, 10 );
final long pool3Start = System.currentTimeMillis();
final int pool3Factor = 15;
final int pool3Loops = TEST_SIZE / pool3Factor;
for( int i = 0; i < pool3Loops; i++ )
{
final Poolable a1 = pool3.get();
final Poolable a2 = pool3.get();
final Poolable a3 = pool3.get();
final Poolable a4 = pool3.get();
final Poolable a5 = pool3.get();
final Poolable a6 = pool3.get();
final Poolable a7 = pool3.get();
final Poolable a8 = pool3.get();
final Poolable a9 = pool3.get();
final Poolable a10 = pool3.get();
final Poolable a11 = pool3.get();
final Poolable a12 = pool3.get();
final Poolable a13 = pool3.get();
final Poolable a14 = pool3.get();
final Poolable a15 = pool3.get();
/*
a1.build();
a2.build();
a3.build();
a4.build();
a5.build();
a6.build();
a7.build();
a8.build();
a9.build();
a10.build();
a11.build();
a12.build();
a13.build();
a14.build();
a15.build();
*/
pool3.put(a1);
pool3.put(a2);
pool3.put(a3);
pool3.put(a4);
pool3.put(a5);
pool3.put(a6);
pool3.put(a7);
pool3.put(a8);
pool3.put(a9);
pool3.put(a10);
pool3.put(a11);
pool3.put(a12);
pool3.put(a13);
pool3.put(a14);
pool3.put(a15);
}
final long pool3End = System.currentTimeMillis();
final long pool3Duration = pool3End - pool3Start;
System.gc();
System.gc();
Thread.currentThread().sleep(2);
System.out.println("FreeMem post 3: " +
Runtime.getRuntime().freeMemory() );
final ThreadSafePool pool4 = new ThreadSafePool( C.class, 5, 10 );
final long pool4Start = System.currentTimeMillis();
final int pool4Factor = 20;
final int pool4Loops = TEST_SIZE / pool4Factor;
for( int i = 0; i < pool4Loops; i++ )
{
final Poolable a1 = pool4.get();
final Poolable a2 = pool4.get();
final Poolable a3 = pool4.get();
final Poolable a4 = pool4.get();
final Poolable a5 = pool4.get();
final Poolable a6 = pool4.get();
final Poolable a7 = pool4.get();
final Poolable a8 = pool4.get();
final Poolable a9 = pool4.get();
final Poolable a10 = pool4.get();
final Poolable a11 = pool4.get();
final Poolable a12 = pool4.get();
final Poolable a13 = pool4.get();
final Poolable a14 = pool4.get();
final Poolable a15 = pool4.get();
final Poolable a16 = pool4.get();
final Poolable a17 = pool4.get();
final Poolable a18 = pool4.get();
final Poolable a19 = pool4.get();
final Poolable a20 = pool4.get();
pool4.put(a1);
pool4.put(a2);
pool4.put(a3);
pool4.put(a4);
pool4.put(a5);
pool4.put(a6);
pool4.put(a7);
pool4.put(a8);
pool4.put(a9);
pool4.put(a10);
pool4.put(a11);
pool4.put(a12);
pool4.put(a13);
pool4.put(a14);
pool4.put(a15);
pool4.put(a16);
pool4.put(a17);
pool4.put(a18);
pool4.put(a19);
pool4.put(a20);
}
final long pool4End = System.currentTimeMillis();
final long pool4Duration = pool4End - pool4Start;
System.out.println("FreeMem post 4: " +
Runtime.getRuntime().freeMemory() );
final long createStart = System.currentTimeMillis();
for( int i = 0; i < TEST_SIZE; i++ )
{
final Poolable a1 = new C();
}
final long createEnd = System.currentTimeMillis();
final long createDuration = createEnd - createStart;
System.out.println("FreeMem post create: " +
Runtime.getRuntime().freeMemory() );
final double pool1Efficiancy =
(double)createDuration/(double)pool1Duration * 100.0;
final double pool2Efficiancy =
(double)createDuration/(double)pool2Duration * 100.0;
final double pool3Efficiancy =
(double)createDuration/(double)pool3Duration * 100.0;
final double pool4Efficiancy =
(double)createDuration/(double)pool4Duration * 100.0;
System.out.println("Pool Efficiancy for 100% hits: " +
pool1Efficiancy + "ms ");
System.out.println("Pool Efficiancy for 100% hits and saturated: " +
pool2Efficiancy + "ms ");
System.out.println("Pool Efficiancy for 60% hits: " + pool3Efficiancy
+ "ms ");
System.out.println("Pool Efficiancy for 50% hits: " + pool4Efficiancy
+ "ms ");
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/security/AbstractPolicy.java
Index: AbstractPolicy.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 file.
*/
package org.apache.avalon.util.security;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.PropertyPermission;
import org.apache.avalon.Component;
import org.apache.avalon.Loggable;
import org.apache.avalon.util.io.FileUtil;
import org.apache.log.Logger;
/**
* Abstract policy extended in avalon.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public abstract class AbstractPolicy
extends Policy
implements Component, Loggable
{
protected final static boolean DEBUG = true;
protected final ArrayList m_entries = new ArrayList();
protected Logger m_logger;
/**
* Internal Policy Entry holder class.
*/
protected final static class PolicyEntry
{
CodeSource m_codeSource;
Permissions m_permissions;
}
public void setLogger( final Logger logger )
{
m_logger = logger;
}
/**
* Overide so we can have a per-application security policy with
* no side-effects to other applications.
*
* @param codeSource the codeSource to get permissions for
* @return the PermissionCollection
*/
public PermissionCollection getPermissions( CodeSource codeSource )
{
codeSource = normalize( codeSource );
getLogger().debug( "getPermissions(" + codeSource.getLocation() +
");" );
final Permissions permissions = new Permissions();
final int size = m_entries.size();
for( int i = 0; i < size; i++ )
{
final PolicyEntry entry = (PolicyEntry)m_entries.get( i );
if( entry.m_codeSource.implies( codeSource ) )
{
if( DEBUG )
{
getLogger().debug( entry.m_codeSource.getLocation() + "
implies " +
codeSource.getLocation() );
}
copyPermissions( permissions, entry.m_permissions );
}
}
if( DEBUG )
{
getLogger().debug( codeSource.getLocation() + " permissions = " +
permissions );
}
return permissions;
}
/**
* Refresh policy. Ignored in this implementation.
*/
public void refresh()
{
}
/**
* Normalizing CodeSource involves removing relative addressing
* (like .. and .) for file urls.
*
* @param codeSource the codeSource to be normalized
* @return the normalized codeSource
*/
protected CodeSource normalize( final CodeSource codeSource )
{
final URL initialLocation = codeSource.getLocation();
// This is a bit of a hack. I don't know why CodeSource should
behave like this
// Fear not, this only seems to be a problem for home grown
classloaders.
// - Paul Hammant, Nov 2000
if( null == initialLocation ) return codeSource;
String location = null;
if( !initialLocation.getProtocol().equalsIgnoreCase( "file" ) )
{
location = initialLocation.getFile();
location = FileUtil.normalize( location );
}
else
{
final File file = new File( initialLocation.getFile() );
location = file.getAbsoluteFile().toString().replace(
File.separatorChar, '/' );
location = FileUtil.normalize( location );
}
URL finalLocation = null;
try
{
finalLocation = new URL( initialLocation.getProtocol(),
initialLocation.getHost(),
initialLocation.getPort(),
location );
}
catch( final MalformedURLException mue )
{
getLogger().warn( "Error building codeBase", mue );
}
return new CodeSource( finalLocation, codeSource.getCertificates() );
}
protected void copyPermissions( final Permissions destination, final
Permissions src )
{
final Enumeration enum = src.elements();
while( enum.hasMoreElements() )
{
destination.add( (Permission)enum.nextElement() );
}
}
/**
* Create a permission set for a codeBase.
* These are read-write permissions and can be written till until the
* time in which they are applied to code.
*
* @param location the location of codes to apply permission set to.
* @param signers a comma seperated string of thos who signed codebase
* @return the new permission set
* @exception MalformedURLException if location string is malformed
*/
protected Permissions createPermissionSetFor( final String location,
final Certificate[] signers
)
throws MalformedURLException
{
final PolicyEntry entry = new PolicyEntry();
entry.m_codeSource = new CodeSource( new URL( location ), signers );
entry.m_codeSource = normalize( entry.m_codeSource );
getLogger().debug( "createPermissionSetFor(" +
entry.m_codeSource.getLocation() + ");" );
entry.m_permissions = new Permissions();
m_entries.add( entry );
return entry.m_permissions;
}
protected final Logger getLogger()
{
return m_logger;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/security/DefaultPolicy.java
Index: DefaultPolicy.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 file.
*/
package org.apache.avalon.util.security;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.UnresolvedPermission;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.PropertyPermission;
import java.util.StringTokenizer;
import org.apache.avalon.Component;
import org.apache.avalon.configuration.Configurable;
import org.apache.avalon.configuration.Configuration;
import org.apache.avalon.configuration.ConfigurationException;
import org.apache.avalon.Context;
import org.apache.avalon.Contextualizable;
import org.apache.avalon.DefaultContext;
import org.apache.avalon.Initializable;
import org.apache.avalon.util.PropertyException;
import org.apache.avalon.util.PropertyUtil;
import org.apache.avalon.util.security.AbstractPolicy;
/**
* Policy that extracts information from policy files.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultPolicy
extends AbstractPolicy
implements Component, Contextualizable, Configurable, Initializable
{
protected DefaultContext m_context;
public void contextualize( final Context context )
{
m_context = new DefaultContext( System.getProperties(), context );
m_context.put( "/", File.separator );
}
public void configure( final Configuration configuration )
throws ConfigurationException
{
final Configuration[] keyStoreConfigurations =
configuration.getChildren( "keystore" );
final HashMap keyStores = configureKeyStores( keyStoreConfigurations
);
final Configuration[] grants = configuration.getChildren( "grant" );
configureGrants( grants, keyStores );
}
public void init()
throws Exception
{
//these properties straight out ot
${java.home}/lib/security/java.policy
final Permissions permissions = createPermissionSetFor( "file:/-",
null );
permissions.add( new PropertyPermission( "os.name", "read" ) );
permissions.add( new PropertyPermission( "os.arch", "read" ) );
permissions.add( new PropertyPermission( "os.version", "read" ) );
permissions.add( new PropertyPermission( "file.separator", "read" ) );
permissions.add( new PropertyPermission( "path.separator", "read" ) );
permissions.add( new PropertyPermission( "line.separator", "read" ) );
permissions.add( new PropertyPermission( "java.version", "read" ) );
permissions.add( new PropertyPermission( "java.vendor", "read" ) );
permissions.add( new PropertyPermission( "java.vendor.url", "read" )
);
permissions.add( new PropertyPermission( "java.class.version", "read"
) );
permissions.add( new PropertyPermission( "java.vm.version", "read" )
);
permissions.add( new PropertyPermission( "java.vm.vendor", "read" ) );
permissions.add( new PropertyPermission( "java.vm.name", "read" ) );
permissions.add( new PropertyPermission(
"java.specification.version", "read" ) );
permissions.add( new PropertyPermission( "java.specification.vendor",
"read" ) );
permissions.add( new PropertyPermission( "java.specification.name",
"read" ) );
permissions.add( new PropertyPermission(
"java.vm.specification.version", "read" ) );
permissions.add( new PropertyPermission(
"java.vm.specification.vendor", "read" ) );
permissions.add( new PropertyPermission(
"java.vm.specification.name", "read" ) );
}
protected HashMap configureKeyStores( final Configuration[]
configurations )
throws ConfigurationException
{
final HashMap keyStores = new HashMap();
for( int i = 0; i < configurations.length; i++ )
{
final Configuration configuration = configurations[ i ];
final String type = configuration.getAttribute( "type" );
final String location = configuration.getAttribute( "location" );
final String name = configuration.getAttribute( "name" );
try
{
final KeyStore keyStore = KeyStore.getInstance( type );
final URL url = new URL( location );
final InputStream ins = url.openStream();
keyStore.load( ins, null );
keyStores.put( name, keyStore );
}
catch( final Exception e )
{
throw new ConfigurationException( "Error configuring keystore
" + name, e );
}
}
return keyStores;
}
protected void configureGrants( final Configuration[] configurations,
final HashMap keyStores )
throws ConfigurationException
{
for( int i = 0; i < configurations.length; i++ )
{
configureGrant( configurations[ i ], keyStores );
}
}
protected void configureGrant( final Configuration configuration, final
HashMap keyStores )
throws ConfigurationException
{
//<grant signed-by="Fred" code-base="file:${sar.home}/blocks/*"
key-store="foo-keystore">
//<permission class="java.io.FilePermission" target="/tmp/*"
action="read,write" />
//</grant>
final String signedBy = configuration.getAttribute( "signed-by", null
);
final String keyStoreName = configuration.getAttribute( "key-store",
null );
String codeBase = configuration.getAttribute( "code-base", null );
if( null != codeBase )
{
codeBase = expand( codeBase );
}
final Certificate[] signers = getSigners( signedBy, keyStoreName,
keyStores );
Permissions permissions = null;
try { permissions = createPermissionSetFor( codeBase, signers ); }
catch( final MalformedURLException mue )
{
throw new ConfigurationException( "Malformed code-base " +
codeBase, mue );
}
configurePermissions( configuration.getChildren( "permission" ),
permissions,
keyStores );
}
protected void configurePermissions( final Configuration[]
configurations,
final Permissions permissions,
final HashMap keyStores )
throws ConfigurationException
{
for( int i = 0; i < configurations.length; i++ )
{
configurePermission( configurations[ i ], permissions, keyStores
);
}
}
protected void configurePermission( final Configuration configuration,
final Permissions permissions,
final HashMap keyStores )
throws ConfigurationException
{
final String type = configuration.getAttribute( "class" );
final String actions = configuration.getAttribute( "actions", null );
final String signedBy = configuration.getAttribute( "signed-by", null
);
final String keyStoreName = configuration.getAttribute( "key-store",
null );
String target = configuration.getAttribute( "target", null );
if( null != target )
{
target = expand( target );
}
final Certificate[] signers = getSigners( signedBy, keyStoreName,
keyStores );
final Permission permission = createPermission( type, target,
actions, signers );
permissions.add( permission );
}
protected String expand( final String value )
throws ConfigurationException
{
try
{
final Object resolvedValue = PropertyUtil.resolveProperty( value,
m_context, false );
return resolvedValue.toString();
}
catch( final PropertyException pe )
{
throw new ConfigurationException( "Error resolving property " +
value, pe );
}
}
protected Permission createPermission( final String type,
final String target,
final String actions,
final Certificate[] signers )
throws ConfigurationException
{
if( null != signers )
{
return createUnresolvedPermission( type, target, actions, signers
);
}
try
{
final Class c = Class.forName( type );
Class paramClasses[] = null;
Object params[] = null;
if( null == actions && null == target )
{
paramClasses = new Class[ 0 ];
params = new Object[ 0 ];
}
else if( null == actions )
{
paramClasses = new Class[1];
paramClasses[0] = String.class;
params = new Object[1];
params[0] = target;
}
else
{
paramClasses = new Class[2];
paramClasses[0] = String.class;
paramClasses[1] = String.class;
params = new Object[2];
params[0] = target;
params[1] = actions;
}
final Constructor constructor = c.getConstructor( paramClasses );
final Object o = constructor.newInstance( params );
return (Permission)o;
}
catch( final ClassNotFoundException cnfe )
{
return createUnresolvedPermission( type, target, actions, signers
);
}
catch( final Exception e )
{
throw new ConfigurationException( "Failed to create permission "
+ type +
" due to " + e, e );
}
}
protected Permission createUnresolvedPermission( final String type,
final String target,
final String actions,
final Certificate[]
signers )
{
return new UnresolvedPermission( type, target, actions, signers );
}
protected Certificate[] getSigners( final String signedBy,
String keyStoreName,
final HashMap keyStores )
throws ConfigurationException
{
if( null != signedBy && null == keyStoreName )
{
keyStoreName = "default";
}
Certificate[] signers = null;
if( null != signedBy )
{
signers = getCertificates( signedBy, keyStoreName, keyStores );
}
return signers;
}
protected Certificate[] getCertificates( final String signedBy,
final String keyStoreName,
final HashMap keyStores )
throws ConfigurationException
{
final KeyStore keyStore = (KeyStore)keyStores.get( keyStoreName );
if( null == keyStore )
{
throw new ConfigurationException( "Unable to aquire keyStore " +
keyStoreName );
}
final ArrayList certificateSet = new ArrayList();
final StringTokenizer tokenizer = new StringTokenizer( signedBy, ","
);
while( tokenizer.hasMoreTokens() )
{
final String alias = ((String)tokenizer.nextToken()).trim();
Certificate certificate = null;
try { certificate = keyStore.getCertificate( alias ); }
catch( final KeyStoreException kse )
{
throw new ConfigurationException( "Error aquiring certificate
" + alias,
kse );
}
if( null == certificate )
{
throw new ConfigurationException( "Unable to locate alias " +
alias +
" in keystore named " +
keyStoreName );
}
if( !certificateSet.contains( certificate ) )
{
if( DEBUG ) getLogger().debug( "Certificate " + certificate );
certificateSet.add( certificate );
}
}
return (Certificate[])certificateSet.toArray( new Certificate[ 0 ] );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/security/PolicyClassLoader.java
Index: PolicyClassLoader.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 file.
*/
package org.apache.avalon.util.security;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
/**
* Classloader that applies correct policy information.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class PolicyClassLoader
extends URLClassLoader
{
protected Policy m_policy;
public PolicyClassLoader( final URL[] urls,
final ClassLoader classLoader,
final Policy policy )
{
super( urls, classLoader );
m_policy = policy;
}
/**
* Overide so we can have a per-application security policy with
* no side-effects to other applications.
*
* @param codeSource the codeSource to get permissions for
* @return the PermissionCollection
*/
protected PermissionCollection getPermissions( final CodeSource
codeSource )
{
if( null == m_policy )
{
final Permissions permissions = new Permissions();
permissions.add( new java.security.AllPermission() );
return permissions;
}
else
{
return m_policy.getPermissions( codeSource );
}
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/test/BinaryHeapTestlet.java
Index: BinaryHeapTestlet.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 file.
*/
package org.apache.avalon.util.test;
import org.apache.avalon.util.BinaryHeap;
import org.apache.testlet.AbstractTestlet;
/**
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class BinaryHeapTestlet
extends AbstractTestlet
{
protected final static Integer VAL1 = new Integer( 1 );
protected final static Integer VAL2 = new Integer( 2 );
protected final static Integer VAL3 = new Integer( 3 );
protected final static Integer VAL4 = new Integer( 4 );
protected final static Integer VAL5 = new Integer( 5 );
protected final static Integer VAL6 = new Integer( 6 );
protected final static Integer VAL7 = new Integer( 7 );
public void testSimpleOrder()
{
final BinaryHeap heap = new BinaryHeap();
heap.clear();
heap.insert( VAL1 );
heap.insert( VAL2 );
heap.insert( VAL3 );
heap.insert( VAL4 );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
assert( VAL2 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL4 == heap.pop() );
}
public void testReverseOrder()
{
final BinaryHeap heap = new BinaryHeap();
heap.clear();
heap.insert( VAL4 );
heap.insert( VAL3 );
heap.insert( VAL2 );
heap.insert( VAL1 );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
assert( VAL2 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL4 == heap.pop() );
}
public void testMixedOrder()
{
final BinaryHeap heap = new BinaryHeap();
heap.clear();
heap.insert( VAL4 );
heap.insert( VAL2 );
heap.insert( VAL1 );
heap.insert( VAL3 );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
assert( VAL2 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL4 == heap.pop() );
}
public void testDuplicates()
{
final BinaryHeap heap = new BinaryHeap();
heap.clear();
heap.insert( VAL4 );
heap.insert( VAL2 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL3 );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL2 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL4 == heap.pop() );
}
public void testMixedInsertPopOrder()
{
final BinaryHeap heap = new BinaryHeap();
heap.clear();
heap.insert( VAL1 );
heap.insert( VAL4 );
heap.insert( VAL2 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL3 );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
heap.insert( VAL4 );
heap.insert( VAL2 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL3 );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL2 == heap.pop() );
assert( VAL2 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL4 == heap.pop() );
assert( VAL4 == heap.pop() );
}
public void testReverseSimpleOrder()
{
final BinaryHeap heap = new BinaryHeap( false );
heap.clear();
heap.insert( VAL1 );
heap.insert( VAL2 );
heap.insert( VAL3 );
heap.insert( VAL4 );
assert( VAL4 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL2 == heap.pop() );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
}
public void testReverseReverseOrder()
{
final BinaryHeap heap = new BinaryHeap( false );
heap.clear();
heap.insert( VAL4 );
heap.insert( VAL3 );
heap.insert( VAL2 );
heap.insert( VAL1 );
assert( VAL4 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL2 == heap.pop() );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
}
public void testReverseMixedOrder()
{
final BinaryHeap heap = new BinaryHeap( false );
heap.clear();
heap.insert( VAL4 );
heap.insert( VAL2 );
heap.insert( VAL1 );
heap.insert( VAL3 );
assert( VAL4 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL2 == heap.pop() );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
}
public void testReverseDuplicates()
{
final BinaryHeap heap = new BinaryHeap( false );
heap.clear();
heap.insert( VAL4 );
heap.insert( VAL3 );
heap.insert( VAL2 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL1 );
assert( VAL4 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL2 == heap.pop() );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
}
public void testReverseMixedInsertPopOrder()
{
final BinaryHeap heap = new BinaryHeap( false );
heap.clear();
heap.insert( VAL1 );
heap.insert( VAL4 );
heap.insert( VAL2 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL3 );
assert( VAL4 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL2 == heap.pop() );
heap.insert( VAL4 );
heap.insert( VAL2 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL1 );
heap.insert( VAL3 );
assert( VAL4 == heap.pop() );
assert( VAL3 == heap.pop() );
assert( VAL2 == heap.pop() );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.peek() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
assert( VAL1 == heap.pop() );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/test/DependencyGraphTestlet.java
Index: DependencyGraphTestlet.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 file.
*/
package org.apache.avalon.util.test;
import java.util.List;
import org.apache.avalon.util.CircularDependencyException;
import org.apache.avalon.util.DependencyGraph;
import org.apache.testlet.AbstractTestlet;
/**
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class DependencyGraphTestlet
extends AbstractTestlet
{
protected final String[][] DEPENDENCY_TREE =
{
{ "A" }, { "B", "C", "D" },
{ "B" }, { "E" },
{ "C" }, {},
{ "D" }, { "F" },
{ "E" }, { "F" },
{ "F" }, { },
{ "G" }, { "H" },
{ "H" }, { "G" },
{ "I" }, { "I" }
};
protected DependencyGraph m_graph;
public void initialize()
{
m_graph = new DependencyGraph();
for( int i = 0; i < DEPENDENCY_TREE.length; i += 2 )
{
m_graph.add( DEPENDENCY_TREE[ i ][0], DEPENDENCY_TREE[ i + 1 ] );
}
}
protected boolean contains( final DependencyGraph.Dependency[] list,
final String name )
{
for( int i = 0; i < list.length; i++ )
{
if( list[ i ].getName().equals( name ) )
{
return true;
}
}
return false;
}
public void testNoDependency()
throws Exception
{
final DependencyGraph.Dependency[] list = m_graph.getDependencyList(
"F" );
assertEquality( "Graph for F", list.length, 1 );
assertEquality( "Graph for F[1]", list[ 0 ].getName(), "F" );
assertEquality( "Graph for F[1]", list[ 0 ].getRequiredBy(), null );
}
public void test1LevelDependency()
throws Exception
{
final DependencyGraph.Dependency[] list = m_graph.getDependencyList(
"E" );
assertEquality( "Graph for E", list.length, 2 );
assert( "Graph for E[1]", contains( list, "E" ) );
assert( "Graph for E[2]", contains( list, "F" ) );
}
public void test2LevelDependency()
throws Exception
{
final DependencyGraph.Dependency[] list = m_graph.getDependencyList(
"B" );
assertEquality( "Graph for E", list.length, 3 );
assert( "Graph for E[1]", contains( list, "E" ) );
assert( "Graph for E[2]", contains( list, "F" ) );
assert( "Graph for E[3]", contains( list, "B" ) );
}
public void testNLevelDependency()
throws Exception
{
final DependencyGraph.Dependency[] list = m_graph.getDependencyList(
"A" );
assertEquality( "Graph for A", list.length, 6 );
assert( "Graph for A[1]", contains( list, "A" ) );
assert( "Graph for A[2]", contains( list, "B" ) );
assert( "Graph for A[3]", contains( list, "C" ) );
assert( "Graph for A[4]", contains( list, "D" ) );
assert( "Graph for A[5]", contains( list, "E" ) );
assert( "Graph for A[6]", contains( list, "F" ) );
}
public void testAllowableCircularDependency()
throws Exception
{
m_graph.setAllowCircularity( true );
final DependencyGraph.Dependency[] list = m_graph.getDependencyList(
"G" );
assertEquality( "Graph for G", list.length, 2 );
assert( "Graph for G[1]", contains( list, "G" ) );
assert( "Graph for H[2]", contains( list, "H" ) );
}
public void testUnallowableCircularDependency()
throws Exception
{
try
{
m_graph.setAllowCircularity( false );
m_graph.getDependencyList( "G" );
}
catch( final CircularDependencyException cde )
{
return;
}
fail( "Expected CircularDependencyException" );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/test/PropertyUtilTestlet.java
Index: PropertyUtilTestlet.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 file.
*/
package org.apache.avalon.util.test;
import org.apache.avalon.Context;
import org.apache.avalon.DefaultContext;
import org.apache.avalon.Resolvable;
import org.apache.avalon.util.PropertyException;
import org.apache.avalon.util.PropertyUtil;
import org.apache.testlet.AbstractTestlet;
/**
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class PropertyUtilTestlet
extends AbstractTestlet
{
protected static final class ResolveTest
implements Resolvable
{
protected int m_count;
protected int m_current;
public ResolveTest( final int count )
{
m_count = count;
}
public Object resolve( final Context context )
{
m_current++;
if( m_current >= m_count ) return new Integer( m_count );
else return this;
}
}
protected final static Object OBJ1 = new Object();
protected final static Object OBJ2 = new Object();
protected DefaultContext m_context;
public void initialize()
{
m_context = new DefaultContext();
m_context.put( "obj1", OBJ1 );
m_context.put( "obj2", OBJ2 );
m_context.put( "res1", new ResolveTest( 1 ) );
m_context.put( "res2", new ResolveTest( 2 ) );
m_context.put( "res3", new ResolveTest( 3 ) );
m_context.put( "res4", new ResolveTest( 4 ) );
}
public void testNoResolve()
throws PropertyException
{
final Object result =
PropertyUtil.resolveProperty( "blah", m_context, false );
assertEquality( result, "blah" );
}
public void testObjResolve()
throws PropertyException
{
final Object result =
PropertyUtil.resolveProperty( "${obj1}", m_context, false );
assertEquality( result, OBJ1 );
}
public void testObjResolveToText()
throws PropertyException
{
final Object result =
PropertyUtil.resolveProperty( "${obj1} ", m_context, false );
assertEquality( result, OBJ1 + " " );
}
public void testDualObjResolve()
throws PropertyException
{
final Object result =
PropertyUtil.resolveProperty( " ${obj1} ${obj2} ", m_context,
false );
assertEquality( result, " " + OBJ1 + " " + OBJ2 + " " );
}
public void testRecurseObjResolve()
throws PropertyException
{
final Object result =
PropertyUtil.resolveProperty( "${res1}", m_context, false );
assertEquality( result, new Integer( 1 ) );
}
public void testRecurseObjResolve2()
throws PropertyException
{
final Object result =
PropertyUtil.resolveProperty( "${res2}", m_context, false );
assertEquality( result, new Integer( 2 ) );
}
public void testNullObjResolve()
throws PropertyException
{
final Object result =
PropertyUtil.resolveProperty( "${blahaaa}", m_context, true );
assertEquality( result, "" );
}
public void testNullObjResolveForException()
throws PropertyException
{
try
{
final Object result =
PropertyUtil.resolveProperty( "${blahaaa}", m_context, false
);
}
catch( final PropertyException pe )
{
return;
}
fail( "NUll resolve occured without exception" );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/test/ProxyGeneratorTestlet.java
Index: ProxyGeneratorTestlet.java
===================================================================
/*
* Copyright 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 file.
*/
package org.apache.avalon.util.test;
import org.apache.avalon.util.ProxyGenerator;
import org.apache.testlet.AbstractTestlet;
import org.apache.testlet.TestFailedException;
/**
* This is used to test Proxy generation for correctness.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class ProxyGeneratorTestlet
extends AbstractTestlet
{
public interface Interface1
{
void method1();
}
public interface Interface2 extends Interface1
{
void method2();
}
public interface Interface3
{
void method3( int x );
}
public interface Interface4
{
void method4( String x );
}
public interface Interface5
{
void method3( String x );
}
public interface Interface6
{
void method2();
}
public interface Interface7
{
void method3( double x );
}
public interface Interface8
{
void method3( double x, double y );
}
public interface Interface9
{
int method4( double x, double y );
}
public interface Interface10
{
double method10( double x, double y );
}
public static class ClassA
implements Interface1, Interface3, Interface4, Interface5,
Interface9, Interface10
{
public void method1() {}
public void method3( int x ) {}
public void method3( String x ) {}
public void method4( String x ) {}
public int method4( double x, double y ) { return 0; }
public double method10( double x, double y ) { return 0.0; }
}
public static class ClassB implements Interface2, Interface6, Interface7,
Interface8
{
public void method1() {}
public void method2() {}
public void method3( double x ) {}
public void method3( double x, double y ) {}
}
public void testNoParamMethod()
throws Exception
{
final Class[] interfaces = new Class[] { Interface1.class };
final Object object = new ClassA();
final Object result = doTest( object, interfaces );
((Interface1)result).method1();
}
public void testExtendedInterfaceHidden()
throws Exception
{
final Class[] interfaces = new Class[] { Interface1.class };
final Object object = new ClassB();
final Object result = doTest( object, interfaces );
((Interface1)result).method1();
assert( !(result instanceof Interface2) );
}
public void testExtendedInterface()
throws Exception
{
final Class[] interfaces = new Class[] { Interface1.class,
Interface2.class };
final Object object = new ClassB();
final Object result = doTest( object, interfaces );
((Interface1)result).method1();
((Interface2)result).method1();
((Interface2)result).method2();
}
public void testIntParamInterface()
throws Exception
{
final Class[] interfaces = new Class[] { Interface3.class };
final Object object = new ClassA();
final Object result = doTest( object, interfaces );
((Interface3)result).method3(2);
}
public void testStringParamInterface()
throws Exception
{
final Class[] interfaces = new Class[] { Interface4.class };
final Object object = new ClassA();
final Object result = doTest( object, interfaces );
((Interface4)result).method4("Hello");
}
public void testOverloadedStringParamInterface()
throws Exception
{
final Class[] interfaces = new Class[] { Interface5.class };
final Object object = new ClassA();
final Object result = doTest( object, interfaces );
((Interface5)result).method3("Hello");
}
public void testDuplicateMethodInterface()
throws Exception
{
final Class[] interfaces = new Class[] { Interface2.class,
Interface6.class };
final Object object = new ClassB();
final Object result = doTest( object, interfaces );
((Interface6)result).method2();
((Interface2)result).method2();
}
public void testDoubleParamInterface()
throws Exception
{
final Class[] interfaces = new Class[] { Interface7.class };
final Object object = new ClassB();
final Object result = doTest( object, interfaces );
((Interface7)result).method3(2.0);
}
public void test2DoubleParamInterface()
throws Exception
{
final Class[] interfaces = new Class[] { Interface8.class };
final Object object = new ClassB();
final Object result = doTest( object, interfaces );
((Interface8)result).method3(2.0,2.0);
}
public void testIntReturnInterface()
throws Exception
{
final Class[] interfaces = new Class[] { Interface9.class };
final Object object = new ClassA();
final Object result = doTest( object, interfaces );
final int x = ((Interface9)result).method4(2.0,2.0);
}
public void testDoubleReturnInterface()
throws Exception
{
final Class[] interfaces = new Class[] { Interface10.class };
final Object object = new ClassA();
final Object result = doTest( object, interfaces );
final double x = ((Interface10)result).method10(2.0,2.0);
}
protected Object doTest( final Object object, final Class[] interfaces )
throws Exception
{
final Object result =
ProxyGenerator.generateProxy( object, interfaces );
if( null == result )
{
throw new TestFailedException( "Proxy object failed to be
created." );
}
for( int i = 0; i < interfaces.length; i++ )
{
if( !interfaces[ i ].isInstance( result ) )
{
throw new TestFailedException( "Interface " + interfaces[ i ]
+
" not implemented by proxy." );
}
}
return result;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/test/StringUtilTestlet.java
Index: StringUtilTestlet.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 file.
*/
package org.apache.avalon.util.test;
import org.apache.avalon.util.StringUtil;
import org.apache.testlet.AbstractTestlet;
/**
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class StringUtilTestlet
extends AbstractTestlet
{
public void testNoReplace()
{
final String result =
StringUtil.replaceSubString("blah", "not-there", "ignored" );
assertEquality( result, "blah" );
}
public void testMidReplace()
{
final String result =
StringUtil.replaceSubString("blah", "la", "le" );
assertEquality( result, "bleh" );
}
public void testStartReplace()
{
final String result =
StringUtil.replaceSubString("blah", "bla", "ble" );
assertEquality( result, "bleh" );
}
public void testEndReplace()
{
final String result =
StringUtil.replaceSubString("blah", "lah", "leh" );
assertEquality( result, "bleh" );
}
public void testDoubleReplace()
{
final String result =
StringUtil.replaceSubString("blahblah", "la", "le" );
assertEquality( result, "blehbleh" );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/thread/DefaultThreadManager.java
Index: DefaultThreadManager.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 file.
*/
package org.apache.avalon.util.thread;
import java.util.Hashtable;
import java.util.Iterator;
import org.apache.avalon.AbstractLoggable;
import org.apache.avalon.configuration.Configurable;
import org.apache.avalon.configuration.Configuration;
import org.apache.avalon.configuration.ConfigurationException;
/**
*
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class DefaultThreadManager
extends AbstractLoggable
implements ThreadManager, Configurable
{
protected final Hashtable m_pools = new Hashtable();
public void configure( final Configuration configuration )
throws ConfigurationException
{
final Configuration[] groups = configuration.getChildren(
"thread-group" );
for( int i = 0; i < groups.length; i++ )
{
final Configuration group = groups[ i ];
final String name = group.getChild( "name" ).getValue();
final int priority = group.getChild( "priority" ).getValueAsInt(
5 );
final boolean isDaemon = group.getChild( "is-daemon"
).getValueAsBoolean( false );
final int minThreads = group.getChild( "min-threads"
).getValueAsInt( 5 );
final int maxThreads = group.getChild( "max-threads"
).getValueAsInt( 10 );
final int minSpareThreads = group.getChild( "min-spare-threads" ).
getValueAsInt( maxThreads - minThreads );
try
{
final ThreadPool threadPool = new ThreadPool( name,
maxThreads );
threadPool.setDaemon( isDaemon );
setupLogger( threadPool );
m_pools.put( name, threadPool );
}
catch( final Exception e )
{
throw new ConfigurationException( "Error creating thread pool
" + name,
e );
}
}
}
public ThreadPool getDefaultThreadPool()
{
return getThreadPool( "default" );
}
public ThreadPool getThreadPool( final String name )
{
final ThreadPool threadPool = (ThreadPool)m_pools.get( name );
if( null == threadPool )
{
//Should this be a ComponentNotFoundException ????
throw new IllegalArgumentException( "No such thread group " +
name );
}
return threadPool;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/thread/ThreadContext.java
Index: ThreadContext.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 file.
*/
package org.apache.avalon.util.thread;
import org.apache.avalon.Poolable;
import org.apache.avalon.util.pool.ObjectFactory;
import org.apache.avalon.util.pool.ThreadSafePool;
/**
* To deal with *current* ThreadContext.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public final class ThreadContext
{
protected final static InheritableThreadLocal c_context = new
InheritableThreadLocal();
public static ThreadPool getCurrentThreadPool()
{
return (ThreadPool)c_context.get();
}
public static void setCurrentThreadPool( final ThreadPool threadPool )
{
//TODO: protect by a permission guard
c_context.set( threadPool );
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/thread/ThreadManager.java
Index: ThreadManager.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 file.
*/
package org.apache.avalon.util.thread;
import org.apache.avalon.Component;
/**
* Interface for component that hands out thread pools.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Federico Barbieri</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public interface ThreadManager
extends Component
{
ThreadPool getThreadPool( String name );
ThreadPool getDefaultThreadPool();
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/thread/ThreadPool.java
Index: ThreadPool.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 file.
*/
package org.apache.avalon.util.thread;
import org.apache.avalon.Loggable;
import org.apache.avalon.Poolable;
import org.apache.avalon.util.pool.ObjectFactory;
import org.apache.avalon.util.pool.ThreadSafePool;
import org.apache.log.Logger;
/**
* This class is the public frontend for the thread pool code.
*
* TODO: Should this be configured with min threads, max threads and min
spare threads ?
*
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
public class ThreadPool
extends ThreadGroup
implements ObjectFactory, Loggable
{
protected final ThreadSafePool m_pool;
protected int m_level;
protected Logger m_logger;
public ThreadPool( final int capacity )
throws Exception
{
this( "Worker Pool", capacity );
}
public ThreadPool( final String name, final int capacity )
throws Exception
{
super( name );
m_pool = new ThreadSafePool( this, 0 );
m_pool.init();
m_pool.grow( capacity );
}
public void setLogger( final Logger logger )
{
m_logger = logger;
}
public Poolable newInstance()
{
final WorkerThread worker =
new WorkerThread( this, m_pool, getName() + " Worker #" +
m_level++ );
worker.setLogger( m_logger );
worker.start();
return worker;
}
public Class getCreatedClass()
{
return WorkerThread.class;
}
public void execute( final Runnable work )
throws Exception
{
execute( work, Thread.NORM_PRIORITY );
}
public void execute( final Runnable work, final int priority )
throws Exception
{
final WorkerThread worker = getWorker( priority );
worker.execute( work );
}
public void executeAndWait( final Runnable work )
throws Exception
{
executeAndWait( work, Thread.NORM_PRIORITY );
}
public void executeAndWait( final Runnable work, final int priority )
throws Exception
{
final WorkerThread worker = getWorker( priority );
worker.executeAndWait( work );
}
protected WorkerThread getWorker( final int priority )
throws Exception
{
final WorkerThread worker = (WorkerThread)m_pool.get();
worker.setContextClassLoader(
Thread.currentThread().getContextClassLoader() );
worker.setPriority( priority );
return worker;
}
}
1.1
jakarta-avalon/src/java/org/apache/avalon/util/thread/WorkerThread.java
Index: WorkerThread.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 file.
*/
package org.apache.avalon.util.thread;
import org.apache.avalon.Loggable;
import org.apache.avalon.Poolable;
import org.apache.avalon.util.pool.ThreadSafePool;
import org.apache.log.Logger;
/**
* This class extends the Thread class to add recyclable functionalities.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
*/
class WorkerThread
extends Thread
implements Poolable, Loggable
{
protected final static boolean DEBUG = false;
protected Logger m_logger;
protected ThreadPool m_threadPool;
protected ThreadSafePool m_pool;
protected Runnable m_work;
protected boolean m_alive;
/**
* Allocates a new <code>Worker</code> object.
*/
protected WorkerThread( final ThreadPool threadPool,
final ThreadSafePool pool,
final String name )
{
super( threadPool, name );
m_threadPool = threadPool;
m_pool = pool;
m_work = null;
m_alive = true;
setDaemon( false );
}
public void setLogger( final Logger logger )
{
m_logger = logger;
}
/**
* The main execution loop.
*/
public final synchronized void run()
{
ThreadContext.setCurrentThreadPool( m_threadPool );
if( DEBUG ) m_logger.info( getName() + ": starting." );
// Notify the pool this worker started running.
//notifyAll();
while( m_alive )
{
waitUntilCondition( true );
if( DEBUG ) m_logger.debug( getName() + ": running." );
try
{
m_work.run();
}
catch( final ThreadDeath td )
{
if ( DEBUG ) m_logger.debug( getName() + ": thread has died."
);
// This is to let the thread death propagate to the runtime
// enviroment to let it know it must kill this worker
throw td;
}
catch( final Throwable t )
{
// Error thrown while working.
if( DEBUG ) m_logger.debug( getName() + ": error caught: " +
t );
// XXX: what should we do when this happens?
}
if( DEBUG ) m_logger.debug( getName() + ": done." );
m_work = null;
//should this be just notify or notifyAll ???
//It seems to resource intensive option to use notify()
//notifyAll();
notify();
// recycle ourselves
if( null != m_pool )
{
m_pool.put( this );
}
else
{
m_alive = false;
}
}
}
/**
* Set the <code>Work</code> code this <code>Worker</code> must
* execute and <i>notifies</i> its thread to do it.
*/
protected synchronized void executeAndWait( final Runnable work )
{
execute( work );
waitUntilCondition( false );
}
protected synchronized void waitUntilCondition( final boolean hasWork )
{
while( hasWork == (null == m_work) )
{
try
{
if( DEBUG ) m_logger.debug( getName() + ": waiting." );
wait();
if( DEBUG ) m_logger.debug( getName() + ": notified." );
}
catch( final InterruptedException ie ) {}
}
}
protected synchronized void execute( final Runnable work )
{
if( DEBUG ) m_logger.debug( getName() + ": notifying this worker." );
m_work = work;
notify();
}
/**
* Set the <code>alive</code> variable to false causing the worker to die.
* If the worker is stalled and a timeout generated this call, this method
* does not change the state of the worker (that must be destroyed in
other
* ways).
*/
public void dispose()
{
if( DEBUG ) m_logger.debug( getName() + ": destroying." );
m_alive = false;
}
}
1.1 jakarta-avalon/src/make/build-docs.xml
Index: build-docs.xml
===================================================================
<?xml version="1.0"?>
<!--
=======================================================================
Avalon Docs Build File
=======================================================================
-->
<project name="Avalon Docs Builder" default="docs" basedir="..\..">
<property name="javadocs.packages" value="org.apache.*"/>
<property name="xdocs.dir" value="${src.dir}/xdocs"/>
<property name="skins.dir" value="${src.dir}/skins"/>
<property name="stylesheets.dir" value="${skins.dir}"/>
<property name="site.dir" value="www"/>
<property name="avalon.skin" value="${skins.dir}/avalon/"/>
<property name="build.xdocs" value="${build.dir}/xdocs"/>
<!--
===================================================================
Prepares the documentation directory
===================================================================
-->
<target name="prepare-docs">
<filter token="year" value="${year}"/>
<mkdir dir="${build.xdocs}"/>
<mkdir dir="${build.docs}"/>
<copy todir="${build.xdocs}" filtering="on">
<fileset dir="${xdocs.dir}">
<exclude name="**/images/**"/>
</fileset>
</copy>
<copy todir="${build.xdocs}" filtering="off">
<fileset dir="${xdocs.dir}">
<include name="**/images/**"/>
</fileset>
</copy>
</target>
<!--
===================================================================
Create developer documentation
===================================================================
-->
<target name="xdocs" depends="prepare-docs">
<mkdir dir="${build.docs}"/>
<stylebook targetdirectory="${build.docs}"
book="${build.xdocs}/book.xml"
skindirectory="${avalon.skin}">
<classpath path="${java.class.path}" />
</stylebook>
</target>
<!--
===================================================================
Create the API documentation
===================================================================
-->
<target name="javadocs">
<deltree dir="${build.javadocs}"/>
<mkdir dir="${build.javadocs}"/>
<javadoc packagenames="${javadocs.packages}"
sourcepath="${java.dir}"
destdir="${build.javadocs}"
author="true"
version="true"
use="true"
windowtitle="${Name} API"
doctitle="${Name}"
bottom="Copyright © ${year} Apache XML Project. All Rights
Reserved."
/>
<mkdir dir="${javadocs.dir}"/>
<copy todir="${javadocs.dir}">
<fileset dir="${build.javadocs}" />
</copy>
<copy file="${stylesheets.dir}/javadoc.css" todir="${build.javadocs}/"/>
</target>
<target name="docs" depends="xdocs,javadocs"/>
</project>
1.1 jakarta-avalon/src/skins/javadoc.css
Index: javadoc.css
===================================================================
/* Apache Javadoc style sheet */
/* Page background color */
body { background-color: #FFFFFF }
/* Table colors */
.TableHeadingColor { background: #D0D0D0 }
.TableSubHeadingColor { background: #E0E0E0 }
.TableRowColor { background: #F9F9F9 }
/* Navigation bar fonts and colors */
.NavBarCell1 { background-color:#D0D0D0;}
.NavBarCell1Rev { background-color:#A0A0A0;}
.NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;}
.NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;}
.NavBarCell2 { font-family: Arial, Helvetica, sans-serif;
background-color:#E0E0E0;}
.NavBarCell3 { font-family: Arial, Helvetica, sans-serif;
background-color:#F0F0F0;}
/* Font used in left-hand frame lists */
.FrameTitleFont { font-size: normal; font-family: Helvetica, Arial,
sans-serif }
.FrameHeadingFont { font-size: normal; font-family: Helvetica, Arial,
sans-serif }
.FrameItemFont { font-size: 10pt; font-family: Helvetica, Arial,
sans-serif }
/* Link colors styling */
A:link { color: #0000A0 } /* unvisited link */
A:visited { color: #A00000 } /* visited links */
A:active { color: #00A000 } /* active links */
1.1 jakarta-avalon/src/skins/avalon/loader.xml
Index: loader.xml
===================================================================
<?xml version="1.0"?>
<!-- CVS $Revision: 1.1 $ $Date: 2001/02/23 10:47:46 $ -->
<loader>
<processor name="xslt">
<parameter name="stylesheet"
value="sbk:/style/stylesheets/book2project.xsl"/>
</processor>
</loader>
1.1 jakarta-avalon/src/skins/avalon/resources/header.gif
<<Binary file>>
1.1
jakarta-avalon/src/skins/avalon/resources/jakarta-logo.gif
<<Binary file>>
1.1 jakarta-avalon/src/skins/avalon/resources/line.gif
<<Binary file>>
1.1
jakarta-avalon/src/skins/avalon/stylesheets/book2project.xsl
Index: book2project.xsl
===================================================================
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- match the root book element -->
<xsl:template match="book">
<project>
<parameter name="copyright" value="[EMAIL PROTECTED]"/>
<!-- copy all resources to the targets -->
<process source="sbk:/style/resources/" producer="directory">
<processor name="xslt">
<parameter name="stylesheet"
value="sbk:/style/stylesheets/directory2project.xsl"/>
<parameter name="base" value="resources/"/>
</processor>
</process>
<xsl:apply-templates/>
</project>
</xsl:template>
<xsl:template match="page|hidden">
<process source="[EMAIL PROTECTED]" producer="parser">
<processor name="xslt">
<parameter name="stylesheet"
value="sbk:/style/stylesheets/scan4resources.xsl"/>
</processor>
</process>
<create source="[EMAIL PROTECTED]" target="[EMAIL PROTECTED]"
producer="parser" printer="html">
<processor name="xslt">
<parameter name="stylesheet"
value="sbk:/style/stylesheets/document2html.xsl"/>
</processor>
</create>
</xsl:template>
<xsl:template match="changes">
<process source="[EMAIL PROTECTED]" producer="parser">
<processor name="xslt">
<parameter name="stylesheet"
value="sbk:/style/stylesheets/{name(.)}2document.xsl"/>
</processor>
<processor name="xslt">
<parameter name="stylesheet"
value="sbk:/style/stylesheets/scan4resources.xsl"/>
</processor>
</process>
<create source="[EMAIL PROTECTED]" target="[EMAIL PROTECTED]"
producer="parser" printer="html">
<processor name="xslt">
<parameter name="stylesheet"
value="sbk:/style/stylesheets/{name(.)}2document.xsl"/>
</processor>
<processor name="xslt">
<parameter name="stylesheet"
value="sbk:/style/stylesheets/document2html.xsl"/>
</processor>
</create>
</xsl:template>
<xsl:template match="external">
</xsl:template>
</xsl:stylesheet>
1.1
jakarta-avalon/src/skins/avalon/stylesheets/changes2document.xsl
Index: changes2document.xsl
===================================================================
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:param name="name"/>
<xsl:template match="changes">
<document>
<header>
<title><xsl:value-of select="@title"/></title>
</header>
<body>
<xsl:apply-templates/>
</body>
</document>
</xsl:template>
<xsl:template match="release">
<s1>
<xsl:attribute name="title">
<xsl:value-of select="@name"/><xsl:text> </xsl:text>
<xsl:value-of select="@version"/><xsl:text> </xsl:text>
<xsl:if test="@date">
<xsl:value-of select="@date"/>
</xsl:if>
</xsl:attribute>
<sl>
<xsl:apply-templates/>
</sl>
</s1>
</xsl:template>
<xsl:template match="action">
<li>
<icon src="images/[EMAIL PROTECTED]" alt="[EMAIL PROTECTED]"/>
<xsl:apply-templates/>
<xsl:text>(</xsl:text><xsl:value-of select="@dev"/><xsl:text>)</xsl:text>
<xsl:if test="@due-to">
<xsl:text> Thanks to </xsl:text>
<link href="mailto:[EMAIL PROTECTED]"><xsl:value-of
select="@due-to"/></link>
<xsl:text>.</xsl:text>
</xsl:if>
<xsl:if test="@fixes-bug">
<xsl:text> Fixes </xsl:text>
<link href="http://xml.apache.org/bugs/[EMAIL PROTECTED]">
<xsl:text>bug </xsl:text><xsl:value-of select="@fixes-bug"/>
</link>
<xsl:text>.</xsl:text>
</xsl:if>
</li>
</xsl:template>
<xsl:template match="devs">
<!-- remove -->
</xsl:template>
</xsl:stylesheet>
1.1
jakarta-avalon/src/skins/avalon/stylesheets/directory2project.xsl
Index: directory2project.xsl
===================================================================
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="base"/>
<xsl:template match="directory">
<project>
<xsl:apply-templates/>
</project>
</xsl:template>
<xsl:template match="entry">
<xsl:if test="not(@directory)">
<resource source="[EMAIL PROTECTED]" target="[EMAIL PROTECTED]"/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
1.1
jakarta-avalon/src/skins/avalon/stylesheets/document2html.xsl
Index: document2html.xsl
===================================================================
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.0">
<xsl:param name="stylebook.project"/>
<xsl:param name="copyright"/>
<!-- ======================================================================
-->
<!-- document section -->
<!-- ======================================================================
-->
<xsl:template match="/">
<!-- checks if this is the included document to avoid neverending loop -->
<xsl:if test="not(book)">
<html>
<head>
<title><xsl:value-of select="document/header/title"/></title>
</head>
<body text="#000000" link="#023264" vlink="#023264" alink="#023264"
topmargin="4" leftmargin="4" marginwidth="4" marginheight="4"
bgcolor="#ffffff">
<!-- THE TOP BAR (HEADER) -->
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td valign="top" align="left">
<a href="http://jakarta.apache.org/index.html">
<img src="resources/jakarta-logo.gif" hspace="0" vspace="0"
border="0"/>
</a>
</td>
<td width="100%" valign="top" align="left" bgcolor="#ffffff">
<img src="resources/header.gif"
hspace="0"
vspace="0"
border="0"
alt="{header/title}"
align="right"/>
</td>
</tr>
<tr>
<td width="100%" height="2" colspan="2"
background="resources/line.gif">
<img src="resources/line.gif"
width="1"
height="2"
hspace="0"
vspace="0"
border="0"
alt="{header/title}" />
</td>
</tr>
</table>
<!-- THE MAIN PANEL (SIDEBAR AND CONTENT) -->
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<!-- THE SIDE BAR -->
<td width="1%" valign="top">
</td>
<td width="14%" valign="top" nowrap="1">
<br/>
<xsl:apply-templates select="document($stylebook.project)"/>
</td>
<!-- THE CONTENT PANEL -->
<td width="*" valign="top" align="left">
<table border="0" cellspacing="0" cellpadding="3">
<tr><td><br/><xsl:apply-templates/></td></tr>
<tr>
<td align="right">
<xsl:if test="document/header/authors">
<p>by
<xsl:for-each select="document/header/authors/person">
<a href="mailto:[EMAIL PROTECTED]"><xsl:value-of
select="@name"/></a>
<xsl:if test="not(position()=last())">, </xsl:if>
</xsl:for-each>
</p>
</xsl:if>
</td>
</tr>
</table>
</td>
</tr>
</table>
<br/>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td bgcolor="#023264"><xsl:text> </xsl:text></td></tr>
<tr>
<td align="center">
<font face="arial,helvetica,sanserif" size="-1" color="#023264">
<i>
Copyright © <xsl:value-of select="$copyright"/>.
All Rights Reserved.
</i>
</font>
</td>
</tr>
</table>
</body>
</html>
</xsl:if>
<xsl:if test="book">
<xsl:apply-templates/>
</xsl:if>
</xsl:template>
<!--
======================================================================
book section
======================================================================
-->
<xsl:template match="page|faqs|changes|todo|spec">
<font face="arial,helvetica,sanserif" size="-1">
<li><a href="[EMAIL PROTECTED]"><xsl:value-of select="@label"/></a></li>
</font>
</xsl:template>
<xsl:template match="external">
<li><a href="[EMAIL PROTECTED]" target="[EMAIL PROTECTED]"><xsl:value-of
select="@label"/></a></li>
<br/>
</xsl:template>
<xsl:template match="separator">
<p/>
</xsl:template>
<xsl:template match="section">
<p><xsl:value-of select="@label"/></p>
</xsl:template>
<!-- ======================================================================
-->
<!-- header section -->
<!-- ======================================================================
-->
<xsl:template match="header">
<center>
<table width="80%">
<tr>
<td bgcolor="#F3DD61">
<br/>
<center>
<b>
<font face="arial,helvetica,sanserif" color="#000000">
<xsl:value-of select="title"/>
<xsl:if test="subtitle">
: <xsl:value-of select="subtitle"/>
</xsl:if>
</font>
</b>
</center>
<br/>
</td>
</tr>
</table>
</center>
<br/>
<!-- ignore on general document -->
</xsl:template>
<!-- ======================================================================
-->
<!-- body section -->
<!-- ======================================================================
-->
<xsl:template match="s1">
<xsl:call-template name="section">
<xsl:with-param name="width">100%</xsl:with-param>
<xsl:with-param name="font-size">+1</xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template match="s2">
<xsl:call-template name="section">
<xsl:with-param name="width">95%</xsl:with-param>
<xsl:with-param name="font-size">+0</xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template match="s3">
<xsl:call-template name="section">
<xsl:with-param name="width">90%</xsl:with-param>
<xsl:with-param name="font-size">-1</xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template match="s4">
<xsl:call-template name="section">
<xsl:with-param name="width">85%</xsl:with-param>
<xsl:with-param name="font-size">-2</xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template name="section">
<xsl:param name="width" />
<xsl:param name="font-size" />
<div align="right">
<table border="0" cellspacing="0" cellpadding="0">
<xsl:attribute name="width"><xsl:value-of
select="$width"/></xsl:attribute>
<tr>
<td bgcolor="#023264">
<font face="arial,helvetica,sanserif" color="#ffffff">
<xsl:attribute name="size"><xsl:value-of
select="$font-size"/></xsl:attribute>
<b><xsl:value-of select="@title"/></b>
</font>
</td>
</tr>
<tr>
<td>
<font face="arial,helvetica,sanserif"
color="#000000"><br/><xsl:apply-templates/></font>
</td>
</tr>
</table>
</div>
<br/>
</xsl:template>
<!-- ======================================================================
-->
<!-- footer section -->
<!-- ======================================================================
-->
<xsl:template match="footer">
<!-- ignore on general documents -->
</xsl:template>
<!-- ======================================================================
-->
<!-- paragraph section -->
<!-- ======================================================================
-->
<xsl:template match="p">
<p align="justify"><xsl:apply-templates/></p>
</xsl:template>
<xsl:template match="source">
<div align="center">
<table border="1" cellspacing="2" cellpadding="2">
<tr>
<td><pre><xsl:apply-templates/></pre></td>
</tr>
</table>
</div>
</xsl:template>
<xsl:template match="fixme">
<!-- ignore on documentation -->
</xsl:template>
<!-- ======================================================================
-->
<!-- list section -->
<!-- ======================================================================
-->
<xsl:template match="ul|ol|dl">
<blockquote>
<xsl:copy><xsl:apply-templates/></xsl:copy>
</blockquote>
</xsl:template>
<xsl:template match="li">
<xsl:copy><xsl:apply-templates/></xsl:copy>
</xsl:template>
<xsl:template match="sl">
<ul><xsl:apply-templates/></ul>
</xsl:template>
<xsl:template match="dt">
<li>
<strong><xsl:value-of select="."/></strong>
<xsl:text> - </xsl:text>
<xsl:value-of select="following::dd"/>
</li>
</xsl:template>
<xsl:template match="dd">
<!-- ignore since already used -->
</xsl:template>
<!-- ======================================================================
-->
<!-- table section -->
<!-- ======================================================================
-->
<xsl:template match="table">
<table width="100%" border="0" cellspacing="2" cellpadding="2">
<caption><xsl:value-of select="caption"/></caption>
<xsl:apply-templates/>
</table>
</xsl:template>
<xsl:template match="tr">
<tr><xsl:apply-templates/></tr>
</xsl:template>
<xsl:template match="th">
<td bgcolor="#039acc"
colspan="[EMAIL PROTECTED]"
rowspan="[EMAIL PROTECTED]"
valign="center"
align="center">
<font color="#ffffff" size="-1" face="arial,helvetica,sanserif">
<b><xsl:apply-templates/></b> 
</font>
</td>
</xsl:template>
<xsl:template match="td">
<td bgcolor="#a0ddf0" colspan="[EMAIL PROTECTED]" rowspan="[EMAIL
PROTECTED]" valign="top" align="left">
<font color="#000000" size="-1" face="arial,helvetica,sanserif">
<xsl:apply-templates/> 
</font>
</td>
</xsl:template>
<xsl:template match="tn">
<td bgcolor="#ffffff" colspan="[EMAIL PROTECTED]" rowspan="[EMAIL
PROTECTED]">
 
</td>
</xsl:template>
<xsl:template match="caption">
<!-- ignore since already used -->
</xsl:template>
<!-- ======================================================================
-->
<!-- markup section -->
<!-- ======================================================================
-->
<xsl:template match="strong">
<b><xsl:apply-templates/></b>
</xsl:template>
<xsl:template match="em">
<i><xsl:apply-templates/></i>
</xsl:template>
<xsl:template match="filename">
<filename><i><xsl:apply-templates/></i></filename>
</xsl:template>
<xsl:template match="code">
<code><font face="courier,
monospaced"><xsl:apply-templates/></font></code>
</xsl:template>
<!-- ======================================================================
-->
<!-- images section -->
<!-- ======================================================================
-->
<xsl:template match="figure">
<p align="center"><img src="[EMAIL PROTECTED]" alt="[EMAIL PROTECTED]"
border="0" vspace="4" hspace="4"/></p>
</xsl:template>
<xsl:template match="img">
<img src="[EMAIL PROTECTED]" alt="[EMAIL PROTECTED]" border="0" vspace="4"
hspace="4" align="right"/>
</xsl:template>
<xsl:template match="icon">
<img src="[EMAIL PROTECTED]" alt="[EMAIL PROTECTED]" border="0"
align="absmiddle"/>
</xsl:template>
<!-- ======================================================================
-->
<!-- links section -->
<!-- ======================================================================
-->
<xsl:template match="link">
<a href="[EMAIL PROTECTED]"><xsl:apply-templates/></a>
</xsl:template>
<xsl:template match="jump">
<a href="[EMAIL PROTECTED]@anchor}"><xsl:apply-templates/></a>
</xsl:template>
<xsl:template match="fork">
<a href="[EMAIL PROTECTED]" target="_blank"><xsl:apply-templates/></a>
</xsl:template>
<xsl:template match="anchor">
<a name="[EMAIL PROTECTED]"><xsl:comment>anchor</xsl:comment></a>
</xsl:template>
<!-- ======================================================================
-->
<!-- specials section -->
<!-- ======================================================================
-->
<xsl:template match="br">
<br/>
</xsl:template>
</xsl:stylesheet>
1.1
jakarta-avalon/src/skins/avalon/stylesheets/document2project.xsl
Index: document2project.xsl
===================================================================
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<project>
<xsl:apply-templates/>
</project>
</xsl:template>
<xsl:template match="img|figure|icon">
<resource source="[EMAIL PROTECTED]" target="[EMAIL PROTECTED]"/>
</xsl:template>
<xsl:template match="node()">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
1.1
jakarta-avalon/src/skins/avalon/stylesheets/scan4resources.xsl
Index: scan4resources.xsl
===================================================================
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<project>
<xsl:apply-templates/>
</project>
</xsl:template>
<xsl:template match="img|figure|icon">
<resource source="[EMAIL PROTECTED]" target="[EMAIL PROTECTED]"/>
</xsl:template>
<xsl:template match="text()">
<!-- ignore -->
</xsl:template>
</xsl:stylesheet>
1.1 jakarta-avalon/src/xdocs/administrator-guide.xml
Index: administrator-guide.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Phoenix Administrator Documentation</title>
<subtitle>Introduction</subtitle>
<authors>
<person name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Introduction">
<p>
Avalon is a Server Framework that provides or will provide for
central administration, server pooling, and quicker time to market.
The framework defines a standard method of piecing together server
components and creating a server.
</p>
<s2 title="Target Audience">
<p>
This documentation describes the care and feeding of the Avalon
Phoenix kernel from the point of view of the administrator.
It will be expanded as the system becomes more complete.
</p>
</s2>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:47 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/assemblers-guide.xml
Index: assemblers-guide.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "dtd/document-v10.dtd">
<document>
<header>
<title>Server Assemblers Guide</title>
<subtitle>Introduction</subtitle>
<authors>
<person name="Avalon Documentation Team" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Who Should Read This Book?">
<p>
The Server Assemblers Guide is written for assemblers who want to
assemble a
Server Application for Phoenix. It is assumed that you are familiar
with
the basic concepts of the Phoenix framework.
</p>
<p>
This book concentrates on assembly, and as such requires no knowledge
of
java programming. It does however assume you are familiar with server
fundamentals, basic security measures, and performance tuning.
</p>
</s1>
<s1 title="Organization">
<p>
The information is organized into sections detailing a specifc aspect
of
assembling ServerApplications.
</p>
</s1>
<s1 title="Sections">
<ol>
<li>
<link href="what-is-a-server-application.html">
What is a Server Application?
</link>
</li>
<li>
<link href="creating-a-server-application.html">
How do I create a Server Application?
</link>
</li>
<li><link href="assembly-xml-specification.html">assembly.xml
specification</link></li>
<li><link href="server-xml-specification.html">server.xml
specification</link></li>
</ol>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:47 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/blank.xml
Index: blank.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "dtd/document-v10.dtd">
<document>
<header>
<title>Blank Documentation</title>
<subtitle>Blank Title</subtitle>
<authors>
<person name="Avalon Documentation Team" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Not Done Yet">
<p>
Unfortunately you have reached a page that has yet to be done. Feel
free
to send us in patches for it though ;)
</p>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:47 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/block-developers-guide.xml
Index: block-developers-guide.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "dtd/document-v10.dtd">
<document>
<header>
<title>Block Developers Guide</title>
<subtitle>Preface</subtitle>
<authors>
<person name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
</authors>
<abstract>
The Block Developer's Guide (BDG) is written to bring an overview
of how to create and deploy a Block. The Block is the component that
is hosted in the Phoenix micro-kernel.
</abstract>
</header>
<body>
<s1 title="Who Should Read This Book?">
<p>The BDG is written for developers who want to create
blocks for Phoenix. It is assumed that you are familiar with
Java, XML, Avalon
patterns and server side security issues. This book provides an
overview of
the underlying technology, Java classes and interfaces, component
model, and
behavior of server Blocks within Phoenix.</p>
<p>While this book concentrates on server fundamentals, it
should not
be construed as a “dummy's” book. Server side
programming
is complex because of the performance and security issues you
must
balance.</p>
<p>You should be well versed in the Java language and have some
practical experience developing server solutions. If you need
a stronger
background on server side programming, I suggest finding a
good book on the
subject (any suggestions?).</p>
</s1>
<s1 title="Organization">
<p>
Here is how the information is presented. The first X chapters are
foundational material, and describe the basic concepts you can use in
your
own blocks. The later chapters specify in detail the formal
requirements of
Block implementations.
</p>
</s1>
<s1 title="Sections">
<ol>
<li><link href="what-is-a-block.html">What is a block?</link></li>
<li><link href="creating-a-block.html">How do I create a
block?</link></li>
<li><link href="blockinfo-specification.html">BlockInfo
specification</link></li>
</ol>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:47 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/book.xml
Index: book.xml
===================================================================
<?xml version="1.0"?>
<book software="Avalon"
title="Avalon Documentation"
copyright="@year@ The Apache Software Foundation">
<section label="About"/>
<page id="index" label="Overview" source="index.xml"/>
<page id="history" label="History" source="history.xml"/>
<page id="features" label="Features" source="features.xml"/>
<page id="geting-started" label="Getting Started"
source="getting-started.xml"/>
<page id="install" label="Installation" source="install.xml"/>
<page id="license" label="License" source="license.xml"/>
<separator/>
<page id="mail" label="Mail Archive" source="mail.xml"/>
<external id="faq"
label="FAQ"
href="http://java.apache.org/jyve-faq/Turbine/screen/DisplayTopics/action/SetAll/project_id/1/faq_id/35"/>
<page id="contributors" label="Contributors" source="contributors.xml"/>
<changes id="changes" label="Changes" source="changes.xml"/>
<section label="Developers"/>
<page id="design" label="Patterns and Design" source="design.xml"/>
<page id="code-standards" label="Coding Standards"
source="code-standards.xml"/>
<page id="todo" label="Todo" source="todo.xml"/>
<external id="api-docs" label="API Docs" href="api/index.html"/>
<section label="Phoenix"/>
<page id="phoenix" label="What is Phoenix?" source="phoenix.xml"/>
<page id="administrators" label="Administrators Guide"
source="administrator-guide.xml"/>
<page id="deployers" label="Deployers Guide" source="deployers-guide.xml"/>
<page id="assemblers" label="Assemblers Guide"
source="assemblers-guide.xml"/>
<page id="developers" label="Block Developers Guide"
source="block-developers-guide.xml" />
<!-- history pages -->
<hidden id="call-to-vote" source="history/call-to-vote.xml" />
<hidden id="what-is-a-server" source="history/what-is-a-server.xml" />
<hidden id="need-for-avalon" source="history/need-for-avalon.xml" />
<!-- design pages -->
<hidden id="patterns" source="design/patterns.xml" />
<hidden id="components" source="design/components.xml" />
<hidden id="composer" source="design/composer.xml" />
<hidden id="life-cycle" source="design/life-cycle.xml" />
<hidden id="inversion-of-control" source="design/inversion-of-control.xml"
/>
<hidden id="reuse-standards" source="design/reuse-standards.xml" />
<hidden id="security" source="design/security.xml" />
<hidden id="separation-of-concerns"
source="design/separation-of-concerns.xml" />
<!-- phoenix pages -->
<hidden id="what-is-a-block" source="phoenix/what-is-a-block.xml" />
<hidden id="blockinfo-specification"
source="phoenix/blockinfo-specification.xml" />
<hidden id="creating-a-block" source="phoenix/creating-a-block.xml" />
<hidden id="what-is-a-server-application"
source="phoenix/what-is-a-server-application.xml" />
<hidden id="assembly-xml-specification"
source="phoenix/assembly-xml-specification.xml" />
<hidden id="server-xml-specification"
source="phoenix/server-xml-specification.xml" />
<hidden id="creating-a-server-application"
source="phoenix/creating-a-server-application.xml" />
</book>
1.1 jakarta-avalon/src/xdocs/changes.xml
Index: changes.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE changes SYSTEM "dtd/changes-v10.dtd">
<changes title="Avalon History of Changes">
<devs>
<person name="Federico Barbieri" email="[EMAIL PROTECTED]" id="FB"/>
<person name="Berin Loritsch" email="[EMAIL PROTECTED]" id="BL"/>
<person name="Peter Donald" email="[EMAIL PROTECTED]" id="PD"/>
</devs>
<release version="3.1a1" date="29th January 2001">
<action dev="BL" type="add">
Added in DataSource implementation for use with J2EE style apps.
</action>
<action dev="PD" type="add">
Added the notion of ServerApplication to replace the concept of .bar as a
server.
A ServerApplication is a isolated environment that manages it's own
threads,
security, logging, classloading etc. It has a specific layout as
documented
in Assembly guide. The kernel was refactored to contain ServerApplications
rather than Blocks and a lot of support was refactored to support safe
separation
of ServerApplications. The archives are in .sar format and are similar in
many
aspects to .war of servlet fame.
</action>
<action dev="PD" type="add">
Refactored thread management so specific thread pools can assigned to
specific
threads/thread groups in a manner similar to how ContextClassLoader is
associated
with threads. Thread management was also moved to a new package
(org.apache.avalon.util.threads).
</action>
<action dev="PD" type="update">
Modify the packagin of all kernel related files into org.apache.phoenix.
</action>
<action dev="PD" type="update">
Modify the packagin of all blocks/services/demos into package hierarchy
org.apache.cornerstone.
</action>
<action dev="PD" type="add">
Added two new services/blocks by refactoring code from tomcat and old
SocketServer.
There is now a SocketManager and a ConnectionManager. The TLS code is now
much improved
and there is the begining of client socket factory. This provides for
future client
socket code factories for SSL/TLS or SSH1/2 etc. Also adapted
SimpleServer to use
these methods.
</action>
<action dev="PD" type="update">
Changed config file from per .bar to per .sar and changed name from
BAR-INF/<
barname>.conf.xml to conf/assembly.xml. It still contains
configuration data as
well as assembly data but this will be removed in a future revision.
</action>
<action dev="PD" type="add">
Added an extra config file to .sar (conf/server.xml) that is responsible
for
configuring .sar wide variables. Some examples include security, logging
and thread loading.
</action>
<action dev="PD" type="update">
Refactored most of the code to use AbstractLoggable and the coresponding
getLogger()
method. Also removed the remaining static access to LogKit.
</action>
<action dev="PD" type="update">
Continued to refine the Camelot API.
</action>
<action dev="PD" type="add">
Removed blockdefs.properties in favour of adding attributes to manifest
entries of jars.
This should enable future GUI tools to easily assemble blocks.
</action>
<action dev="PD" type="add">
ReAdded the sub-classed context BlockContext to allow blocks full access
to important
environmental information.
</action>
<action dev="PD" type="update">
Many of the lifecycle methods now have a chance to fail by throwing an
exception.
</action>
<action dev="PD" type="remove">
Removed all notion of kernel configurability.
</action>
<action dev="PD" type="update">
Enabled securityManager by default and now ServerApplications have to
specify a security
policy.
</action>
<action dev="PD" type="update">
Removed classloader hack in ObjectStorageRepository as it is no longer
required with
new .sar format.
</action>
<action dev="PD" type="update">
Homogenized the remaining code to follow one style.
</action>
<action dev="PD" type="update">
Configuration temporarily will create new Configuration objects on
getChild() if they
don't exist until Berins work is finalized.
</action>
<action dev="PD" type="update">
Altered Compose so that it threw ComponentManagerException of which the
previous two
exceptions thrown are now subclasses.
</action>
<action dev="PD" type="update">
Made loading of jars relative to avalon-loader.jar rather than via
current working
directory so that some tools (ie VAJava) would not complain.
</action>
<action dev="PD" type="update">
Separated out tools directory/jars from main jars that avalon uses.
</action>
<action dev="BL" type="update">
A number of bug fixes and more descriptive exceptions for Configuration
and Parameters
objects.
</action>
</release>
<release version="3.0a3" date="11th October 2000">
<action dev="PD" type="update">
Made SocketManager accept arbitrary SocketServer.Listener objects.
</action>
<action dev="FB" type="update">
Updated all blocks to use new system level logging.
</action>
<action dev="FB" type="update">
Changed Threads so that it is now a system level service.
</action>
<action dev="PD" type="add">
Added new LogManager that manages arbitrary log categories.
</action>
<action dev="PD" type="add">
Added the BlockInfo requirement. Thus blocks need to have an XML file
that describe the
services it offers, the services it depends upon and other meta
information.
</action>
<action dev="PD" type="add">
Added support for Blocks to implement BlockContextualizable. If they do
this the kernel
will pass them Context information. Currently the context information is
limited to
a handle to kernel instance and the name they were configured under.
</action>
<action dev="PD" type="add">
Changed SimpleContext and SimpleComponentManager to DefaultComponent and
DefaultComponentManager to match better with other Avalon design
patterns.
</action>
<action dev="PD" type="add">
Added functionality that allowed you to listen to BlockEvents generated
by kernel.
Events indicate when a Block is being created, initialized, composed,
destroyed, ran and
stopped.
</action>
<action dev="PD" type="add">
Updated Logger interface so arbitrary integer levels are not allowed to
be passed. The user
is forced to use defined enumerants. This was done to increase safety.
</action>
<action dev="PD" type="add">
Updated kernel so that is now delegates to AvalonKernelConfigurator to
configure itself.
</action>
<action dev="PD" type="update">
Updated kernel so that it is now pluggable. Any kernel can be loaded via
the code in main.
Kernel configuration files are loaded from default configuration
directory in a file
with same name as class with a .conf.xml appended.
</action>
<action dev="PD" type="update">
Removed getDescription method from Block as it is to become part of
BlockInfo
</action>
<action dev="PD" type="update">
Change methods in Configure/Reconfigure to throw ConfigurationExceptions.
</action>
<action dev="PD" type="update">
Change methods in Configure/Reconfigure to match Java standards.
</action>
<action dev="FB" type="add">
Add to the Logger log level support.
</action>
<action dev="BL" type="add">
JNDI for the lookup of blocks and components. Still keep the
Composer interface for those lightweight blocks that don't
need the extra features of the Context. JNDI should be the
ComponentManager of choice.
</action>
<action dev="BL" type="update">
Synchronized Avalon with Cocoon 2 enhancements. Uses SAX 2 for
configuration, incorporated abstract and base classes for fundamental
types, and incorporated the NamedComponent interface.
</action>
<action dev="BL" type="update">
Upgraded Loader architecture and the AvalonClassLoader to provide
better detail, as well as new ways of configuring the loader at the
beginning. It does not require any extra libraries to load.
</action>
</release>
<release version="2.1" date="2000">
<action dev="FB" type="update">
Changed the Acceptor pattern to a more flexible event provider.
</action>
<action dev="FB" type="add">
Added a TimeServer to easily manage time events.
</action>
<action dev="FB" type="update">
Make Store implementation more pluggable.
</action>
</release>
<release version="2.0" date="2000">
<action dev="FB" type="update">
Updated Context pattern to Configurable-Composer pattern.
</action>
</release>
<release version="1.0-dev" date="Can't remember">
<action dev="FB" type="update">
First Avalon implementation.
</action>
</release>
</changes>
1.1 jakarta-avalon/src/xdocs/code-standards.xml
Index: code-standards.xml
===================================================================
<?xml version="1.0"?>
<document>
<header>
<title>Coding Standards</title>
<authors>
<person name="Avalon Documentation Team" email="[EMAIL PROTECTED]"/>
<person name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
<person name="Peter Donald" email="[EMAIL PROTECTED]"/>
<person name="Roberto Lo Giacco" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Coding Standards">
<p>
This document describes a list of coding conventions that are required
for code submissions to the project. By default, the coding conventions
for most Open Source Projects should follow the existing coding conventions
in the code that you are working on. For example, if the bracket is on
the same line as the if statement, then you should write all your code
to have that convention.
</p>
<p>
<strong>If you commit code that does not follow these conventions and you
are caught, you are responsible for also fixing your own code.</strong>
</p>
<ol>
<li>Brackets should begin and end on a new line. Examples:
<source><![CDATA[
if( foo )
{
// code here
}
try
{
// code here
}
catch( final Exception bar )
{
// code here
}
finally
{
// code here
}
while( true )
{
// code here
}
]]></source>
</li>
<li><p>The preference is to include extra spaces between parenthesis and
expression.
For example;</p>
<source><![CDATA[
if( foo )
]]></source>
</li>
<li>
<p>
4 spaces. <strong>NO</strong> tabs. Period. We understand that a lot of you
like
to use tabs, but the fact of the matter is that in a distributed development
enviroment, when the cvs commit messages get sent to a mailing list, they
are almost impossible to read if you use tabs.
</p>
<p>
In Emacs-speak, this translates to the following command:
(setq-default tab-width 4 indent-tabs-mode nil)
</p>
</li>
<li>
Unix linefeeds for all .java source code files. Other platform specific
files should have the platform specific linefeeds.
</li>
<li>
Javadoc <strong>SHOULD</strong> exist on all your methods. Also, if you are
working
on existing code and there currently isn't a javadoc for that
method/class/variable
or whatever, then you should contribute and add it. This will improve the
project as a whole.
</li>
<li>
The Jakarta Apache/Avalon License <strong>MUST</strong> be placed at the top
of each and every file.
</li>
<li>
If you contribute to a file (code or documentation), add yourself to the
top of the file. For java files the preferred Javadoc format is:
<source><![CDATA[
@author <a href="mailto:[EMAIL PROTECTED]">John Doe</a>
]]></source>
</li>
<li>
Indent comments on an 80 column basis and the code on a
100 column using a two more indention when you're constrained
to wrap a line.
</li>
<li>
We focus on readability over performance, at least in the first
phase, leaving source code optimization the last resource to give
out some milliseconds from my code. If the code is not performing
then
it is better to re-engineer it rather than to expand loops, take
out variable declarations and such things. If the code is
performing well and you know what the core methods are then, in the
end of the process, try to give out the best from them.
</li>
<li>
Try to javadoc-comment all methods and public/default/protected
attributes adding code comments only when you think it's really
needed (like assumptions).
</li>
<li>
Variables are declared in the inner scope regardless of
performances unless the code really needs for performances
(2 thousand loops every 5 seconds for example) like:
<source>
while( myListIterator.hasNext() )
{
final String myString = (String)myLstIterator.nextElement();
}
</source>
</li>
<li>
Variable names are every time descriptive. The cases where this rule is
not applied include; manipulating exceptions (only uppercase class
exception letters), loop declaring variables (mostly I use i,j,k and t)
and other established shortenings (like init() for initialize, sb for
StringBuffer etc). ie.
<source><![CDATA[
try
{
for( int i = 0; i < 10; i++ )
{
// some stuff
}
}
catch( final FileNotFoundException fnfe )
{
// some stuff
}
catch( final IndexOutOfBoundsException ioobe )
{
// some stuff
}
]]></source>
</li>
<li>
Use only String concatenation unlesss you really need
StringBuffer methods leaving to the compiler optimization
the stuff to replace it with StringBuffer, so use:
<source>
final String myString = "test " + "for " + "performances";
</source>
</li>
<li>
Indent comments on an 80 column basis and the code on a
100 column using a two more indention when you're constrained
to wrap a line.
</li>
<li>
Try not to declare a method as 'synchronized'. If a method accesses
a shared resource then surround accesses to that resource with
a synchronized block. Ideally the synchronized block should
surround
the smallest possible area. For example:
<source>
public void sharedMethod()
{
String display = null;
synchronized( this )
{
display = mySharedObject.getHelloWorld();
}
System.out.println( display );
}
</source>
If you are within a static method, then you may have to create
a static object whose sole purpose in life is to provide the
lock you need.
</li>
</ol>
<p>
Thanks for your cooperation.
</p>
<p>
-The Avalon Team
</p>
</s1>
</body>
</document>
1.1 jakarta-avalon/src/xdocs/contributors.xml
Index: contributors.xml
===================================================================
<?xml version="1.0"?>
<document>
<header>
<title>Avalon Contributors</title>
<authors>
<person name="Avalon Documentation Team" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Contributors">
<p>
The people listed below have made significant contributions to Avalon by
working long and hard to make quality software for the rest of the world to
use.
Contributors to the Avalon Project should be extremely proud of themselves.
</p>
<p>
If you would like to become a contributor, please see the
<link href="todo.html">Todo</link> document to find areas where you
can contribute effectively. If there is nothing in there that suits your
interest, but you still have ideas, please feel free to suggest them on
the mailing list.
</p>
<p>
The table is listed in alphabetic order.
</p>
<p>
<table>
<tr>
<td>Federico Barbieri</td>
<td><link href="mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]</link></td>
</tr>
<tr>
<td>Charles Benett</td>
<td><link href="mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]</link></td>
</tr>
<tr>
<td>Peter Donald</td>
<td><link href="mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]</link></td>
</tr>
<tr>
<td>Mike Engelhart</td>
<td><link href="mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]</link></td>
</tr>
<tr>
<td>Pierpaolo Fumagalli</td>
<td><link href="mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]</link></td>
</tr>
<tr>
<td>Serge Knystautas</td>
<td><link href="mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]</link></td>
</tr>
<tr>
<td>Roberto Lo Giacco</td>
<td><link href="mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]</link></td>
</tr>
<tr>
<td>Berin Loritsch</td>
<td><link href="mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]</link></td>
</tr>
<tr>
<td>Stefano Mazzocchi</td>
<td><link href="mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]</link></td>
</tr>
<tr>
<td>Ricardo Rocha</td>
<td><link href="mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]</link></td>
</tr>
</table>
</p>
</s1>
</body>
</document>
1.1 jakarta-avalon/src/xdocs/deployers-guide.xml
Index: deployers-guide.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "dtd/document-v10.dtd">
<document>
<header>
<title>Deployers Guide</title>
<subtitle>Introduction</subtitle>
<authors>
<person name="Peter Donald" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Introduction">
<p>
Currently deploying a server application under Phoenix is simply a
matter
of dropping the .sar file into the appropriate directory
(<code>apps/</code>)
and restarting Phoenix. In the future there will be more advanced
methods
of deploying and undeploying Server Applications without restarting
Phoenix.
</p>
<s2 title="Target Audience">
<p>
This documentation describes the methods through which you can
deploy
Server Applications under the Phoenix kernel. It will be expanded
as
the system becomes more complete.
</p>
</s2>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:47 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/design.xml
Index: design.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "./dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Developer Design Documentation</title>
<subtitle>Introduction</subtitle>
<authors>
<person name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
<person name="Peter Donald" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Introduction">
<p>
Avalon is among other things a repository of established patterns and
design standards. Developers will appreciate the thought put into the
framework, because it eases development. This documentation covers
the
overall principles behind Avalon, and the patterns involved.
</p>
<s2 title="Target Audience">
<p>
This documentation is aimed towards developers who are interested
in the design principles of Avalon, or wish to develop code that
will be incorporated into Avalon.
</p>
</s2>
<s2 title="Theoretical Aspects of Component Development">
<p>
The following documents provide basic theoretical concepts that are
applied
through-out Avalons framework. It would be good for a prospective
developer to
be at least passingly familiar with the concepts outlined in this
document.
The documentation also provides links to outside sources which can
be consulted
for further information.
</p>
<ol>
<li><link href="patterns.html">Patterns</link></li>
<li><link href="reuse-standards.html">Reuse Standards</link></li>
<li><link href="inversion-of-control.html">Inversion of
Control</link></li>
<li><link href="separation-of-concerns.html">Separation of
Concerns</link></li>
<li><link href="security.html">Security</link></li>
</ol>
</s2>
<s2 title="Concrete Descriptions of the Avalon Component model">
<p>
This section describes concrete examples of how the theoretical
ideas
are applied within the context of Avalon. It describes the
lifecycle of
a component and how the interfaces contribute to defining the
lifecycle.
</p>
<ol>
<li><link href="components.html">Designing a Component</link></li>
<li><link href="composer.html">Understanding the
Composer</link></li>
<li><link href="life-cycle.html">The components
life-cycle</link></li>
</ol>
</s2>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:47 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/features.xml
Index: features.xml
===================================================================
<?xml version="1.0"?>
<document>
<header>
<title>Features</title>
<authors>
<person name="Avalon Documentation Team" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Features">
<p>
This document will list the features of Avalon. It is yet to be completed
yet.
</p>
</s1>
</body>
</document>
1.1 jakarta-avalon/src/xdocs/getting-started.xml
Index: getting-started.xml
===================================================================
<?xml version="1.0"?>
<document>
<header>
<title>Avalon Getting Started</title>
<authors>
<person name="Avalon Documentation Team" email="[EMAIL PROTECTED]"/>
<person name="Leo Simons" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Getting Started">
<p>
This document provides developers with simple documentation for getting
started with Avalon. For information about the overall structure of
Avalon, please refer to the <link href="design.html">Design</link>
document.
</p>
<p>
Instructions for downloading and installing Avalon can be found on the
<link href="install.html">Install</link> document.
</p>
<p>
More detailed instructions will be added to this document in the future.
Feel free
to send in patches ;)
</p>
</s1>
<s1 title="View Detailed API Documentation">
<p>
To generate a full set of detailed API documentation for Avalon, go to
the base
directory of source distribution and run the appropriate build script for
your
platform with the parameter 'javadocs'.
<source><![CDATA[
> build.[bat|sh] javadocs
]]></source>
</p>
</s1>
<s1 title="Run the examples">
<p>
After you have successfully built Avalon, you can verify that it has
compiled
correctly by running the demo Service Application. To do so, fire up
phoenix
with the following command:
<source><![CDATA[
> bin/run.[bat|sh]
]]></source>
</p>
<p>
Next, fire up your favorite webbrowser and point it to
http://localhost:8999/,
where localhost is the network name of your machine ("localhost") should
work
on all windows platforms.<br />
If all goes well, you will see something like the following:
<source><![CDATA[
Hello World!
Requests so far = 9
you are 127.0.0.1 at 127.0.0.1
]]></source>
</p>
</s1>
</body>
</document>
1.1 jakarta-avalon/src/xdocs/history.xml
Index: history.xml
===================================================================
<?xml version="1.0"?>
<document>
<header>
<title>History of Avalon</title>
<authors>
<person name="Avalon Documentation Team" email="[EMAIL PROTECTED]"/>
<person name="Peter Donald" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="History">
<p>
This document tracks the history of the Avalon project. Originally
started with
a realisation that java was a great platform for developing server
products and a
<link href="call-to-vote.html">call to vote</link>. There was a lot of
work
formalizing what exactly a <link
href="what-is-a-server.html">server</link> consists
of and why Avalon was <link href="need-for-avalon.html">needed</link>.
Theses
discussions led to the initial development of Avalon framework.
</p>
<p>
Overtime the Java Apache Server Framework project was renamed Avalon.
This was in
recognition that the original ideas have evolved over time. Avalon became
a
repository of general utility code, a design and testing ground for
component based
solutions, a micro kernel and generalized server orientated services.
This combined
with a move from the Java Apache project to the jakarta project promted
the revision.
At this time the kernel code was repackaged under the name phoenix, core
services
under the name cornerstone and the avalon-independent code was moved to
util package.
</p>
</s1>
</body>
</document>
1.1 jakarta-avalon/src/xdocs/index.xml
Index: index.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "dtd/document-v10.dtd">
<document>
<header>
<title>Overview</title>
<authors>
<person id="FB" name="Federico Barbieri" email="[EMAIL PROTECTED]"/>
<person id="BL" name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
</authors>
<notice>
Avalon documentation is under construction. Everything you
can find outside this page is to be considered obsolete.
</notice>
</header>
<body>
<s1 title="What is it?">
<p>
The Avalon project is an effort to create, design, develop and maintain
a common framework for server applications written using the Java
language. This framework will not be a standalone product, but will
allow
existing and yet to be created server applications to fit into a common
platform and to share code, design and human resources.
</p>
</s1>
<s1 title="Project Goals">
<p>
As many people points out, software engineering is a very uncommon
procedure
in software development and even more uncommon in auto-organized open
source projects. The main goal of the framework project is to design
a way for
different projects to share resources avoiding as much as possible
efforts
duplication.
</p>
<p>
The framework will not be a product or an API set or a set of
interfaces: will be
a collection of code design patterns, rules, guidelines and
suggestions on how to
write server software that "plugs" into the framework. The framework
will not
impose restrictions on the server that deploy it, but rather precious
guidelines to
help the developers reuse as much work they can from other server
solutions.
</p>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:47 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/install.xml
Index: install.xml
===================================================================
<?xml version="1.0"?>
<document>
<header>
<title>Avalon Installation</title>
<authors>
<person name="Avalon Documentation Team" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Installation">
<p>
Avalon runs on a variety of platforms that have installed the Java 2
Virtual Machine.
The JSSE (Java Secure Sockets Extention) is required for users who want
to compile
Avalon to use SSL/TLS facilities.
</p>
<p>
Everything required to run Avalon and develope Avalon based products
comes with the
<link href="http://java.apache.org/framework/dist/">distribution</link>.
If you wish
to help develop Avalon then it is recomended that you obtain the full
source tree from
<link
href="http://jakarta.apache.org/getinvolved/cvsindex.html">CVS</link> or from
the
<link
href="http://jakarta.apache.org/builds/jakarta-avalon/nightly/">nightly builds
</link>
</p>
</s1>
<s1 title="Compiling">
<p>
Execute the relavent platform specific script (build.[sh|bat]) in the
base avalon directory.
Place the JSSE jars into the lib/ sub-directory if you wish to compile in
TLS/SSL support.
</p>
<p>
Executing this script will create a <filename>dist</filename> directory
within the Avalon
distribution directory. The <filename>dist</filename> directory will
contain the
compiled class files packaged into jars.
</p>
</s1>
<s1 title="Testing Your Installation">
<p>
As of the present time there is minimal support for Unit Testing and no
support for
functional testing. This will change in the future pending changes in ant
to support
such facilities.
</p>
</s1>
</body>
</document>
1.1 jakarta-avalon/src/xdocs/license.xml
Index: license.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Public License</title>
<authors>
<person id="BL" name="Avalon Documentation Team" email="[EMAIL
PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Avalon Public License">
<source><![CDATA[
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1997-2001 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The end-user documentation included with the redistribution, if any, must
include the following acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Jakarta", "Avalon" and "Apache Software Foundation" must not
be used to endorse or promote products derived from this software
without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", nor may
"Apache" appear in their name, without prior written permission of the
Apache Software Foundation.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This software consists of voluntary contributions made by many individuals
on behalf of the Apache Software Foundation. For more information on the
Apache Software Foundation, please see <http://www.apache.org/>.
]]></source>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:47 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/mail.xml
Index: mail.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Mailing List Details</title>
<authors>
<person name="Avalon Documentation Team" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Lists">
<p>
As Avalon was previously a Java Apache project before it moved to the
Jakarta Apache Project, there are two mailing list archives. The
current
archives and the historic archives. For details on how to subscribe
to the
Avalon mailing lists see the Jakarta wide <link
href="http://jakarta.apache.org/site/mail.html">Mailing list
details</link>.
</p>
<ul>
<li>
Jakarta Apache Avalon Mailing list
<link
href="http://marc.theaimsgroup.com/?l=avalon-dev&r=1&w=2">
Archives
</link>
</li>
<li>
Java Apache Avalon Mailing list
<link
href="http://marc.theaimsgroup.com/?l=java-apache-framework&r=1&w=2">
Archives
</link>
(Historic)
</li>
<li>
More complete Java Apache Avalon Mailing list
<link
href="http://list.working-dogs.com/lists/java-apache-framework">
Archives
</link>
(Historic)
</li>
</ul>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:47 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/phoenix.xml
Index: phoenix.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "dtd/document-v10.dtd">
<document>
<header>
<title>Phoenix Developer Documentation</title>
<subtitle>Introduction</subtitle>
<authors>
<person name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
<person name="Peter Donald" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Introduction">
<p>
Phoenix is a micro-kernel designed and implemented on top of the
Avalon
framework. It is both an API to program to and a reference
implementation.
The reference implementation provides a number of facilities to
manage the
environment of Server Applications. Such facilities include log
management,
classloading, thread management and security. In the future it will
conditionally offer support extra facilities such as central server
management,
server pools, and other facilities aimed at reducing the time to
market. The API
defines a standard method of piecing togther server components and
creating a server.
</p>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:47 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/to-merge.txt
Index: to-merge.txt
===================================================================
<s2 title="What Does Avalon Give Me?">
<p>
One of the nice things that Avalon affords you is that you do not
have to start from scratch. Avalon includes a number of utilities
that facilitate making your life easier. Among the utilities are
a logger, an object pool (for reusing objects), a thread pool,
and a configuration mechanism. Just this list eliminates many
hours of work that would be repeated by every Component writer
out there. It also means that the utilities are well tested and
maintained by someone else.
</p>
<s3 title="The Logger">
<p>
The Logger should always be set up for the Component before it
is created. In order to obtain a useable Logger for your
Component,
you have to perform two steps: set the global minimum priority
and create the log channel. The following source code describes
the two step process:
</p>
<source>
URL destination = new URL("file://log/dir/file.log");
LogKit.setGlobalPriority( Priority.DEBUG );
Logger myLog = LogKit.createLogger("channel-name", destination,
Priority.DEBUG);
</source>
<p>
The LogKit does have a convenience function that makes creating
the Logger instance easier. It shares the same name, but it
accepts three strings and converts them to the string, URL, and
Priority.Enum objects.
</p>
<p>
Once you have the Logger object, you can use it to your heart's
content. If a child Component requires an instance of the same
Logger object, then it can call
<code>LogKit.getLoggerFor("channel-name")</code>.
Look in the API docs for "org.apache.log" for more detail.
</p>
</s3>
<s3 title="The Thread Pool">
<p>
If your Component needs a pool of threads for it's use, then we
use the ThreadManager. The ThreadManager
(org.apache.avalon.util.lang)
keeps the number of running threads to a sane number, and manages
their reuse. You initialize the thread like this:
</p>
<source>
ThreadManager.setDefaultPool(new WorkerPool(64));
</source>
<p>
The ThreadPool has some room for expansion, in that you will be
able to have named pools at a future date. For now, when you need
a ThreadPool, the name is ignored and you always get the default
pool. In any case, the following code shows you how to actually
use the thread:
</p>
<source>
WorkerPool threads = ThreadManager.getWorkerPool("pool-name");
threads.execute(new MyRunnable());
</source>
<p>
While the named pool implementation is not yet implemented, it
would
be a good idea to program now as if it were implemented. That
way,
when the work is done, you have no rework to do.
</p>
</s3>
<s3 title="The Object Pool">
<p>
The object pool requires more in depth information, so it will be
covered in another page.
</p>
</s3>
</s2>
</s1>
<s1 title="Some notes on the org.apache.avalon package">
<p>
This package defines the base interfaces and contracts between those
interfaces for a project to be Avalon Aware.
</p>
</s1>
<s1 title="The configuration pattern">
<p>
Avalon uses XML to read configurations and load Configuration objects.
Once Avalon initializes the Block, it passes the root Configuration
object to the Block. The Block is then responsible for instantiating
Components based on the Configuration, and passes that node to the
Component that is responsible to configure itself.
</p>
</s1>
1.1 jakarta-avalon/src/xdocs/todo.xml
Index: todo.xml
===================================================================
<?xml version="1.0"?>
<document>
<header>
<title>Avalon Todo</title>
<authors>
<person name="Avalon Documentation Team" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Todo">
<p>
This document describes functionality that is either missing or not finished
within Avalon.
</p>
<p>
Wish List functionality is stuff that we would like to see implemented, but
is
not critical for release. This is the area where you can take ownership of a
part of the project and contribute back.
</p>
<p>
Critical Before Release is stuff that we feel is holding up the release of
Avalon.
</p>
<p>
If you are a new developer to Avalon or even an existing developer, these are
areas where you can take ownership and help complete. Please do not ask us
how
you can help, but rather specific questions about how you think that these
items
should be implemented. It is up to you to take initiative and provide
solutions
to the missing functionality described below. ;-)
</p>
<p>
Documentation is *always* appreciated in any form. There are two ways to
provide
helpful documentation. The first way is to write up HTML or straight text
documentation and send it to one of the primary authors directly (we are also
willing to give you CVS write access if you wish). The second way is to post
Questions/Answers to the FAQ under the Avalon sections there.
There is a Getting Started document named
"getting-started.html" that could always use additional documentation,
examples
and clarification. You need to take the initiative and just start writing
down
your thoughts and concerns and questions and answers and then giving those
back
to us.
</p>
<p>
If you need more detailed help, please send mail to the mailing list
([email protected]) and ask your specific questions there.
</p>
</s1>
<s1 title="Wish List">
<ul>
<li>
Define and implement a smart way to generate Avalon configurations.
Define configuration template containing default configuration,
user configuration file to overwrite or append configurations to
template,
implement code to merge all servers configuration file to a single
Avalon
configuration file.
</li>
<li>
Rework the DefaultTimeScheduler so that entrys are removed from heap
when
reset. Otherwise it could lead to excessive buildup of invalidated
entries
if many are reset but remain in heap.
</li>
<li>
A standard reconfiguration system. This may require the building
of FileMonitors that will read a file when it is changed. Any
kind of block or component that extends the Reconfigurable interface
gets sent the new configuration.
</li>
<li>
Create Avalon icons and images for documentations/servers. We need a
standard icon for "powered by Avalon" that meshes with our logo!
</li>
<li>
Define and implement needed stuff to allow hot and warm reconfiguration
at
runtime.
</li>
<li>
Avalon should provide default JNDI contexts
that Block implementers can extend and use like
Context, EventContext, and DirectoryContext.
</li>
<li>
JMS (Java Messaging Service) for the Connection Manager. It
will provide a standard and flexible connection service and
messaging service. It allows for both point to point messaging
and multicast messaging (subscriber/provider).
</li>
<li>
Connection Pooling for JDBC connections, Socket connections, JMS
connections, etc. (Maybe extending the store interface?)
</li>
<li>
Support for sending log events to a database. Not all logging
systems will want to send information to the filesystem.
</li>
<li>
Persistent Store should be able to optionally store in a database.
</li>
<li>
Support for server pools. Several Avalon servers should be able
to pool resources and act as one server regardless of VM, or
physical machine they are on.
</li>
<li>
Remote loading of Blocks. Avalon should be able to pull a block
at run time from a remote server, check the signature, and run it
with proper permissions. This would allow for the possibility of
automatically upgrading blocks.
</li>
<li>
Write some code to remotely control Avalon. (This will most likely be
rolled into JMX support).
</li>
<li>
Define and implement some Transaction pattern for the Repository. Maybe
JTA?
</li>
<li>
Write all documentation.
</li>
<li>
Update JavaDocs for decent developer documentation.
</li>
</ul>
</s1>
<s1 title="Critical Before Release">
<ul>
<li>
JMX (Java Management eXtentions) for central management of
Avalon. If JMX cannot be done due to licensing, we should
make the current beginnings of central management more
robust.
</li>
</ul>
</s1>
</body>
</document>
1.1 jakarta-avalon/src/xdocs/design/components.xml
Index: components.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Design Documentation</title>
<subtitle>Designing a Component</subtitle>
<version>3.0</version>
<authors>
<person id="BL" name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
</authors>
<notice>
Avalon documentation is under construction. Everything you can find
outside this page is to be considered obsolete.
</notice>
</header>
<body>
<s1 title="Introduction">
<p>
In Avalon, a Component is defined as a passive entity that performs
a specific role. This is an important concept to grasp because
it forces you to think in a specific manner when designing a system
using Components. First, a Component employs a passive API (one
that is acted upon). Second, the Component's purpose is narrowed
to perform one function.
</p>
<p>
The difference between Object Oriented Programming (OOP) and Component
Oriented Programming (COP) is the Black Box idea. Regular OOP goes
so far as to organize data objects into entities that take care of
themselves. It has many powerful features that make things that
used to be difficult to impossible relatively easy. However, its
limitation is one of object codependency. That doesn't mean that
all OOP is horrid and previous OO programmers didn't have a clue.
It means that over time a more rigid idea had to be formalized:
the Component. The key difference between a Component and an
Object is that the Component is a completely replaceable entity.
</p>
<p>
The idea of programming for replaceability is an intriguing one,
and it requires careful planning. The first point is that a
Component is not just an object by itself, but a combination of
an interface and one or more objects to perform the task at hand.
</p>
</s1>
<s1 title="Roles">
<p>
The concept of roles come from the theater. A play, musical,
or movie will have a certain number of roles that actors play.
Although there never seems to be a shortage of actors, there
are a finite number of roles. I am not going to make reference
to different types of roles at this point, but simply bring
the concept to light. The function or action of a role is
defined by it's script.
</p>
<p>
We are introducing this concept now because you need to have it
in mind when you are designing your system architecture. Think
of the different roles in your system, and you will have your
"cast" of components so to speak.
</p>
<p>
For each role, you need to specify it's script, or interface to
the rest of the system. To be honest the interface is not enough.
There are specific contracts that you must define and keep in mind
when you specify your interfaces. In other words, what users
of the Component must provide, and what the Component produces.
When the interface and contract are defined, you can work on your
implementation.
</p>
</s1>
<s1 title="Writing the Component">
<p>
John Milton wrote, "No man is an island." to communicate that we
are all interdependent. The same is true for the Component. That
is why there are different concerns regarding the Component. In
the section on roles we specified one of the concerns--the role.
The concerns directly supported by Avalon are: configuration,
external component use, management, and execution.
</p>
<p>
As you might of guessed, each one of these concerns has a separate
interface that describes that concern. We will delve deeper into
the interfaces and the reasoning behind them in other sections. It
is important to know the order of precedence for the concerns so
that you know the overall contracts of how they are put together.
</p>
<ol>
<li>
<strong>Configurable:</strong> marks an object that can be
configured.
</li>
<li>
<strong>Composer:</strong> marks an object that uses Components.
</li>
<li>
<strong>Initializable:</strong> marks an object that can be
initialized
and destroyed.
</li>
<li>
<strong>Disposable:</strong> marks an object that can be disposed.
</li>
<li>
<strong>Stoppable</strong> marks an object that can be started and
stopped.
</li>
</ol>
<p>
The contract surrounding this order means that the methods defined
by each of those interfaces are called in a specific order by the
object
that created the Component. Each interface represents a narrow view
of the Component or object being controlled.
</p>
<note>
Notice that each interface is separate from Component, so you can use
them for simple objects.
</note>
<s2 title="How is the Component Going to be Used?">
<p>
The first step in writing the Component is determining how it is
going
to be used. There will be a number of times where you have a
powerful
Component that can be used in many different contexts. Those
contexts
may include executing the Component from the command line (separate
from Avalon), using it as a part of a sub system, or using it as an
integral part of Avalon.
</p>
<s3 title="Part of Avalon">
<p>
All Components are an integral part of Avalon, so there is really
nothing to be done beyond specifying its interface (role). It is
important to identify and document it's social contract with the
rest of the system. What I mean by social contract is the order
of dependencies, what it needs to function, and what it supplies
to the rest of the system.
</p>
</s3>
<s3 title="Part of a Sub System">
<p>
A sub system can either be part of Avalon, or live in a separate
context. A perfect example would be a Component that can function
within a Servlet or Enterprise Application. Neither of those
contexts are native to Avalon (though they can easily be built
on top of Avalon).
</p>
<p>
It is important to do even more careful planning than in the
first scenario. The reason is that you want the interface to be
as generic as possible and still accurately represent its role.
</p>
<p>
Because the contexts that may not be an integral part of Avalon,
you must take care to use the Component in the same manner as
Avalon would. That means that you follow the order of concerns
that Avalon has specified for those concerns.
</p>
</s3>
<s3 title="A Stand Alone Program">
<p>
When you are designing a Component to be run from the command
line (or directly by the operating system), try to separate
the main function from the Component itself. This is imperative
in order to maintain the passive API of Avalon. By designing
you Component in the manner stated in the previous section,
you have effectively minimized what the main function has to
do.
</p>
<p>
Follow the practice of having an object dedicated to the main
function that includes the parsing of the command line parameters
and initialization of the Component. When the Component is used
the exact same way in every context (including the command line),
you minimize the number of locations to look while debugging.
</p>
<note>
A common mistake is to combine the main function in the
implementation of the Component. This requires violating the
contracts and principles that Avalon is built upon. This
violation of the pattern of "Inversion of Control" is
aptly dubbed "Subversion of Control" (thanks to Steven Coffman
for the name of the anti-pattern).
</note>
</s3>
</s2>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:48 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/design/composer.xml
Index: composer.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Design Documentation</title>
<subtitle>Understanding the Composer</subtitle>
<version>3.0</version>
<authors>
<person id="BL" name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
</authors>
<notice>
Avalon documentation is under construction. Everything you can find
outside this page is to be considered obsolete.
</notice>
</header>
<body>
<s1 title="Introduction">
<p>
In Avalon, a Composer is defined as an active entity that controls
or uses Components. It's best analogy is that of a musical composer.
The musical composer chooses what instruments (Components) by their
role in the symphony (system) and tells them which notes to play.
</p>
<p>
The Avalon Composer follows the principles of Inversion of Control,
and is assigned a Component Manager. Within this section we will
discuss how to look up specific Components, and then how to prepare
the ComponentManager for the Composer.
</p>
<note>
The Composer has a specific contract that must be enforced for
security
reasons. The ComponentManager must only be set once. That means that
the <code>compose</code> method must ignore all subsequent
requests to set the ComponentManager after it is successfully set.
</note>
</s1>
<s1 title="Finding your Component">
<s2 title="The Component Manager">
<p>
For the majority of all cases, you will need to use the
ComponentManager
get the instance of the Component you need. If you recall the
discussion
on Component Roles in the Component documentation, you already have
a head start. In Avalon, Roles are defined by the work interface a
Component has. A work interface is different from any other
interface
because it is the interface that defines the Component's Role.
Composer
and Component are concern interfaces because they address specific
concerns about the Component.
</p>
<p>
The ComponentManager has one method to retrieve all of your
Components.
The <code>lookup</code> method will look up the Component based on
the
fully qualified name (FQN) of the work interface (Role). It is
important
to realize that the ComponentManager returns Components, and
therefore
you must recast the Component to the Role you need. See the
following
example:
</p>
<source>
final MyComponent component =
(MyComponent)manager.lookup( "com.mycompany.myproject.MyComponent" );
</source>
<p>
It is important to note that Role is not the same thing as
functional
equivalence. In other words, if you have a MailSpooler that is
functionally
equivalent to a FileStore (they do the same thing), it does not
mean that
they perform the same Role. The FileStore is used to store objects
to
files, and the MailSpooler is used to temporarily store messages
until
they are sent. Thus they are separate roles. Sometimes you need to
create a new interface name that does nothing more than allow
access to
alternate roles who have the same role.
</p>
</s2>
<s2 title="The Component Selector">
<p>
Sometimes you will have several Components that function in the
same role.
For those cases, you will use the ComponentSelector to choose the
exact
one you need. The best way to describe it's proper use is the
scenario
described here. You have several formatters that have the same
Role:
to take an input document and format it according to the rules in
the
individual Component implementations. One formatter may take a
text file
and remove all tabs and replace them with four spaces. Another
formatter
may reverse the formerly mentioned one. Yet another takes the text
file
and formats it for a canvas object. For the Composer, it makes no
difference
what the implementation does--just that it formats the text.
</p>
<p>
Using the processing chain example in the previous paragraph, we
realize
the unsuitability of the ComponentManager for getting the right
Component.
The Component addresses the concern of one Component per role.
Fortunately,
the ComponentSelector is a Component. That means we use the
ComponentManager
to lookup the ComponentSelector. The ComponentSelector is designed
to choose
the specific Component out of many that perform the
<strong>same</strong>
Role. The following code will help:
</p>
<source>
final ComponentSelector selector =
(ComponentSelector)manager.lookup(
"org.mycompany.myproject.FormatterSelector" );
final Formatter formatter = (Formatter)selector.select( myURL );
</source>
<p>
The selector does not discriminate against lookup keys. In that
respect it
acts much like a hashtable lookup. Keep in mind that the
implementation of the
selector does not limit you to a hashtable lookup--you can
dynamically
instantiate objects as well. It takes an object (a hint), and
returns the
specific Component based on that hint.
</p>
</s2>
</s1>
<s1 title="Populating the ComponentManager">
<p>
It is the responsibility of the entity that creates the Composer to
give it a
ComponentManager with all of the Roles populated. If you create your
own
implementations of the ComponentManager and ComponentSelector then
you have
the liberty of deciding how to populate them. Keep in mind that
there are
default implementations included, and you should model their behavior
as
much as possible.
</p>
<s2 title="DefaultComponentManager">
<p>
The DefaultComponentManager is nothing more than a Hashtable lookup
of roles
and Components. It even gives you the method <code>put</code> to
populate
the ComponentManager. One feature of the DefaultComponentManager
is that
it can cascade. In other words, if the role is not found in this
ComponentManager,
the default implementation will look in the parent ComponentManager.
</p>
<p>
For the paranoid developer, the Cascading feature of the
ComponentManager
can be seen as a security hole as opposed to a usability
enhancement. You
are free to create your own implementation that does not use the
Cascading
feature--but you have to manually populate it with anything that
would
have been in the parent ComponentManager that your child Composer
needs.
Truth be told, there is very little risk due to the set once
contract for
ComponentManagers. The method is never exposed to hostile agents
before
the ComponentManager is set.
</p>
</s2>
<s2 title="DefaultComponentSelector">
<p>
The DefaultComponentSelector again is simply a Hashtable selection
of Components
based on hints. It gives the method <code>put</code> to populate
the ComponentSelector.
The ComponentSelector does not have the cascading feature of the
ComponentManager,
nor should it. A ComponentSelector simply holds a number of
Components that
implement the same role--there really is no need to cascade.
</p>
<p>
After the ComponentSelector is populated, you must put it in the
ComponentManager.
Please use the role of the Component you are selecting, not the
role of the selector
itself. An acceptable convention is to add the "Selector" name to
the end of the
Role you are looking up. Just be consistent.
</p>
</s2>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:48 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/design/inversion-of-control.xml
Index: inversion-of-control.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Developer Documentation</title>
<subtitle>Patterns</subtitle>
<authors>
<person name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Inversion of Control">
<p>
One of the key design principles behind Avalon is the principle
of <em>Inversion of Control</em>. <em>Inversion of Control</em> is
a concept promoted by one of the founders of the Avalon project,
<link href="mailto:[EMAIL PROTECTED]">Stefano Mazzocchi</link>. The
principle enforces security by design.
</p>
<p>
It is difficult to track down one paper that defines this pattern
at length, so here are a couple of different definitions of
<em>Inversion of Control</em>.
</p>
<s2 title="What it Means">
<p>
The Framework plays the role of the main program in coordinating
and sequencing events and application activity.
</p>
<p>
A designer sets up a chain among objects that can all react
to certain messages in a delegation hierarchy.
</p>
<s3 title="Definition by Analogy">
<p>
There are a couple of different analogies that make
understanding <em>Inversion of Control</em> easier. We
experience this in many different ways in regular life,
so we are borrowing the form in code. The best analogy,
however, is called "Chain of Command" in the
military.
</p>
<s4 title="Chain of Command">
<p>
This is probably the clearest parallel to <em>Inversion
of Control</em>. The military provides each new recruit
with the basic things they need to operate at their rank,
and issues commands that recruit must obey. The same
principle applies in code. Each Component is given the
provisions they need to operate by the instantiating
entity (i.e. Commanding Officer in this analogy). The
instantiating entity then acts on that Component how it
needs to act.
</p>
</s4>
</s3>
</s2>
<s2 title="How to Apply It">
<p>
<em>Inversion of Control</em> is applied in a very simple
manner. Basically, it means that the Component architecture
employs a <em>passive</em> structure. See the following code:
</p>
<source>
class MyComponent implements Component, Composer {
ComponentManager manager;
MyComponent() {
// Nothing to do here.
}
setComponentManager(ComponentManager manager){
this.manager = manager;
}
myMethod() {
Logger logger = (Logger)
manager.getComponent("org.apache.avalon.blocks.Logger");
logger.log("MyComponent", "Hello World!", Logger.INFO);
}
}
</source>
<p>
The parent of MyComponent instantiates MyComponent, sets the
ComponentManager, and calls myMethod. The Component is not
autonomous, and is given a ComponentManager that has an instance
of the Logger object that is called by role.
</p>
<p>
The MyComponent class has no state apart from the parent, and
has no way of obtaining a reference to the Logger implementation
without the parent telling it which implementation it can receive.
</p>
</s2>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:48 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/design/life-cycle.xml
Index: life-cycle.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Component Developers Documentation</title>
<subtitle>Lifecycle methods</subtitle>
<authors>
<person id="BL" name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
<person id="PD" name="Peter Donald" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Lifecycle">
<p>A <code>Component</code>'s lifecycle depends on the specific
interface
implemented by the <code>Component</code> and the interfaces honored by
it's
container. Note that it is up to each individual Component Container to
indicate
which lifecycle methods it will honor. These should be documented along
with a
description of the container.</p>
<p>Each of the following interfaces add some lifecycle stages to the
component lifecycle. The interfaces related to lifecycle are:</p>
<ol>
<li>Loggable</li>
<li>Contextualizable</li>
<li>Composer</li>
<li>Configurable</li>
<li>Initializable</li>
<li>Startable</li>
<li>Runnable</li>
<li>Suspendable</li>
<li>Recontextualizable</li>
<li>Recomposer</li>
<li>Reconfigurable</li>
<li>Resumeable</li>
<li>Stoppable</li>
<li>Disposable</li>
</ol>
<p>The lifecycle of a <code>Component</code> implementing only
Configurable for
example will be:</p>
<ol>
<li>constructor</li>
<li>configure</li>
<li>finalize</li>
</ol>
<p>The lifecycle of a <code>Component</code> implementing only Composer
will be:</p>
<ol>
<li>constructor</li>
<li>compose</li>
<li>finalize</li>
</ol>
<p>If a <code>Component</code> implements more than one interface the
order of
the events (compose, configure etc.) follow a specific order. A
<code>Component
</code> implementing all above interfaces for example will follow the
specific
path:</p>
<ol>
<li>constructor</li>
<li>contextualize</li>
<li>compose</li>
<li>configure</li>
<li>init</li>
<li>start</li>
<li>run</li>
<li>
<ol>
<li>suspend</li>
<li>reconfigure</li>
<li>recontextualize</li>
<li>recompose</li>
<li>resume</li>
</ol>
</li>
<li>stop</li>
<li>dispose</li>
<li>finalize</li>
</ol>
<p>This is a possible lifecycle. By definition the [start,run,stop] can
occur one
or more times while [reconfigure] [recompose] [recontextualize] can
occur
zero or more times in any order inside the [suspend,resume] cycle.
So another possible life can be:</p>
<ol>
<li>constructor</li>
<li>setLogger</li>
<li>contextualize</li>
<li>compose</li>
<li>configure</li>
<li>init</li>
<li>start</li>
<li>run</li>
<li>suspend</li>
<li>recontextualize</li>
<li>reconfigure</li>
<li>resume</li>
<li>suspend</li>
<li>recompose</li>
<li>reconfigure</li>
<li>resume</li>
<li>stop</li>
<li>dispose</li>
<li>finalize</li>
</ol>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:48 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/design/patterns.xml
Index: patterns.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Developer Documentation</title>
<subtitle>Patterns</subtitle>
<authors>
<person name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Introduction to Design Patterns">
<p>
I highly recommend reading the essay
<link href="http://xent.ics.uci.edu/~khare/Alexander.htmld/">
"On the diffusion of Christopher Alexander's <em>A Pattern
Language</em> into Software Architecture"
</link>
by Rohit Khare. That essay is a good primer on the principles
behind Design Patterns and how they came into being.
</p>
<p>
Avalon takes many design patterns and architectural mindsets,
and implements the best ones for Servers. There are different
kinds of patterns that represent different aspects of Avalon.
Avalon uses three main conceptual patterns called Inversion
of Control, Multi-Dimensional Separation of Concerns, and
Aspect Oriented Programming. Avalon also uses several architectural
patterns like the Singleton and the Factory. Detailed information
about all of these patterns will be included in their respective
pages.
</p>
<p>
You can find more information about patterns from the following links:
</p>
<ol>
<li><link href="http://www.laputan.org/foote/papers.html">Brian
Foote's Pattern documents</link></li>
</ol>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:48 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/design/reuse-standards.xml
Index: reuse-standards.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Developer Documentation</title>
<subtitle>Designing for Reuse</subtitle>
<authors>
<person name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Rules for Reuse">
<p>
If you are asking yourself why this section is even included,
the answer is that a well designed framework is designed to
be modular and black-box in nature. If you are new to Object
Oriented Programming (OOP), then I suggest you read
<link href="http://www.laputan.org/drc/drc.html">
"Designing Reusable Classes"
</link> by Ralph E. Johnson and Brian Foote. It provides a
good primer on OOP techniques.
</p>
<p>
Within this chapter, I will summarize the 12 rules for designing
for code reuse (what frameworks promote).
</p>
<s2 title="Recursion Introduction">
<p>
Use the same interface for communication with components of
the same type. It allows the swapping of those components
for other components of the same type without breaking existing
code.
</p>
<p>
If you need additional functionality, either create proxy
objects that implement the interface, or add it by subclassing
(hence the name "Recursion Introduction". Even if
there is no recursion happening, it appears to opperate in the
same manner.
</p>
</s2>
<s2 title="Eliminate Case Analysis">
<p>
Avoid testing to see if an object is an instance of a particular
class. Usually, if you think you need that approach then a
redesign will help emmensely.
</p>
</s2>
<s2 title="Reduce the Number of Arguments">
<p>
Methods with a half-dozen arguments are hard to read, and can
usually be accomplished with an object that represents that
set of arguments. It also makes it easier to track down the
problems.
</p>
</s2>
<s2 title="Reduce the Size of Methods">
<p>
Most of your methods should only need to be a few lines long.
Methods that are very long (like 50 lines or so) are too complex,
and should be considered guilty of bad design until proven
innocent.
</p>
</s2>
<s2 title="Class Heirarchies Should be Deep and Narrow">
<p>
Basically, this rule is saying it is better to start with an
Abstract object, and specialize off of that than it is to
reimplement the interface for each object. For example, in
a GUI you will have an HTMLTextBox that extends PlainTextBox
that extends AbstractTextBox that extends AbstractControl.
You do that instead of an HTMLTextBox that implements the
Control interface. (You get the point).
</p>
</s2>
<s2 title="The Top of the Class Heirarchy Should be Abstract">
<p>
Always provide an abstract base class to extend for your
specializations. The majority of the functionality and
behavior is well defined in those cases--making it easier
to deciphor what the intents of the interface designer were.
</p>
</s2>
<s2 title="Minimize Accesses to Variables">
<p>
This point formalizes the principles of data hiding. Try not
to expose class attributes to other classes, but protect them
by methods. If an attribute changes name, then you only have
one place to update the code instead of hundreds.
</p>
</s2>
<s2 title="Subclasses Should be Specializations">
<p>
Think a subclass "is a" [superclass]. If what you
are trying to do is make a Component into a ComponentManager,
then you are violating the spirit of the framework. A better
approach is to use containment in that case (i.e. a class
"has a" external class).
</p>
</s2>
<s2 title="Split Large Classes">
<p>
If a class has 50+ methods, then it is most likely trying to
do too much. Look at separating the functionality into
separate components. Like methods that are too long, classes
that violate this rule should be considered guilty of wrong
design until proven innocent.
</p>
</s2>
<s2 title="Factor Implementation Differences Into Subcomponents">
<p>
If a subclass implements a method completely different from
the superclass, then it is not really a specialization. It
should be split off from that class heirarchy tree.
</p>
</s2>
<s2 title="Separate Methods that Do Not Communicate">
<p>
Sometimes in building a framework you run into a case where
you have different views of the same data. In these cases,
you can have some attributes that describe how to generate
the data, and some attributes that describe the data itself.
It is better to separate these two views into separate classes.
The semantics are different enough to justify this solution.
</p>
</s2>
<s2 title="Send Messages to Components instead of to This">
<p>
The point of this point is that you want to build your framework
based on Components, and not inheritance. Avalon takes this
point to heart. In order to illustrate, I will give two examples
of the same thing. The scenario is that we have a data structure
that we want to output to an arbitrary format.
</p>
<p>
In the following example, we will use the java <code>this</code>
object and an inheritance based framework. As you can see, this
would be a bear to maintain, and it won't easily be extended.
</p>
<source>
abstract class AbstractExampleDocument {
// skip some code ...
public void output(Example structure) {
if (structure != null) {
this.format(Example structure);
}
}
protected void format(Example structure);
}
</source>
<p>
In the next example, we will use the Avalon Component based
architecture. There is a clean separation between the purpose
of the objects, and you can exchange and extend formatting
without worrying about any other concerns.
</p>
<source>
class DefaultExampleDocument {
// skip some code ...
public void output(Example structure) {
ExampleFormatter output = (ExampleFormatter)
manager.lookup(Roles.FORMATTER);
if (structure != null) {
output.format(structure);
}
}
}
</source>
<p>
An inheritance based framework (White Box) can be converted
into a component based framework (Black Box) structure by
replacing overridden methods by method calls (message sends)
to components. Component based architecture is much more
flexible in this regard.
</p>
</s2>
<s2 title="Eliminate Implicit Parameter Passing">
<p>
Just because two methods share the same information within the
class does not mean that it should be done in that manner.
Many times, that attribute that is shared should be passed
as a parameter of the method instead of directly accessing
the attribute.
</p>
</s2>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:48 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/design/security.xml
Index: security.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Developer Documentation</title>
<subtitle>Security Concerns</subtitle>
<authors>
<person name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Security Concerns">
<p>
One major concern for many companies is the security of a system.
In this context security is defined as protection of data, and
quality of service (QOS). Both of these fall under security because
a system must protect itself from these two forms of attack. When
a company loses a system, they lose business, and the money the
lose are scary amounts.
</p>
<p>
For the purpose of this discussion, we will address the first
aspect (protection from crackers and system infiltration). Many
times, the same fixes for this type of protection inherently fix
the other (QOS). System security has three distinct concerns
that have been well defined: authentication, authorization, and
architecture. Why didn't I say encryption? It is because
encryption is only part of the architecture.
</p>
<s2 title="Authentication">
<p>
Authentication is the process of identifying parties. In a
completely
trusted system, authentication is as simple as grabbing a reference
to the object or entity you want to manipulate. However, sometimes
you have trusted systems running in hostile environments (e.g. the
world wide web). In those cases you have to make sure that the
entity
is the correct one.
</p>
<p>
There are two sides of authentication. There is the side that you
are authenticating an entity you want to do business with. Then
there
is the side of an entity wanting to do business with you. This is
best understood when you bring it into a financial realm. Let's say
you want to get a loan from XYZ bank. If you initiate the exchange
at their facility, you have already authenticated them--although you
will have to jump through hoops to authenticate yourself. If a
telemarketer calls from ACME Loan Machine, Inc., they know who you
are--although if you are smart, you will make them jump through
hoops to authenticate themselves.
</p>
<p>
Currently, Avalon identifies Blocks as trusted parties. In other
words, the fact that they are installed correctly in the proper
directory is enough to mark them as authenticated. Much like a
good friend--you know them by their voice. Because of the
architecture
of Avalon, Blocks define their own authentication system. That
means that whether the Block assumes all Components are trusted
or it forces the blocks to authenticate themselves is up to the
block.
</p>
<p>
For systems that deal with sensitive information, authentication
becomes more of an issue. You must validate that the Components
in use are the ones you have authorized for use. The more open a
system is, the more authentication and authorization play an
important
role. If you have Components that are transmitted over some form
of communications system (wire, air, etc.) you must verify that
they are Kosher.
</p>
<p>
For this purpose, protocols like Kerberos and Leighton-Micali have
been defined. It is beyond the scope of this page to discuss the
pros and cons of each system.
</p>
</s2>
<s2 title="Authorization">
<p>
Once a Component has been authenticated (in other words it's
identity
has been authoritatively validated), then you must decide what
access
it has to your systems. A fully trusted Component can do what it
likes.
An untrusted Component must be denied functions it is not allowed.
</p>
<p>
Authorization is part of the architecture, but is significant enough
to warrant it's own concern. The best rule of thumb is to hide
access
to everything unless the Component is trusted. When hiding is not
an option, then you have to resort to denying access. For the
security
conscious, all denied accesses should be logged along with the
Component's
identifier.
</p>
</s2>
<s2 title="Architecture">
<p>
Avalon already has the framework for the proper secure architecture.
With proper planning, security can be added without recoding the
Components.
However there are some rules of thumb for paranoid programming.
</p>
<ol>
<li>
Never expose anything that does not need to be exposed.
Information
hiding is as much an important part of security as it is in
Component
Oriented Programming (COP).
</li>
<li>
Any Component that originates from your own jar should be
trusted--you
provided it after all.
</li>
<li>
Any Component that originates from another source, and especially
over
a wire should be treated with suspicion. Authenticate it, and if
it
checks out, trust it. Otherwise, don't give it access--you don't
know
where it's been or who created it.
</li>
<li>
Encrypt <strong>all</strong> communications. Period.
</li>
</ol>
</s2>
</s1>
<s1 title="From the Sublime to the Rediculous">
<p>
Throughout my short career I have been exposed to a wide range of
security
implementations. Having worked for a DoD contractor, I learned about
physical
security requirements (how to manage paper files, and the rules and
regulations
regarding secure information). However in a recent attempt to
install a
solution at our customer's site, I learned the most about computer
security
than I have at any other time.
</p>
<p>
Our customer, being a well known corporation whom I will call ACME for
anonymity is in custody of sensitive information. Product movement
data,
financial data, and demographic data are all stored in one of a couple
huge server farms. Our application was to reside in the De-Militarize
Zone (DMZ), and talk to a database behind the firewall. When they
discovered
that the application server we chose required Remote Procedure Calls
(the
result of many CERT advisories in the Unix world) we hit a brick
wall. Our
application was no longer trusted, and was not to be installed.
Luckily
the next version of the application server fixed that problem.
</p>
<p>
In the midst of this, I decided to learn as much as I could about
operating
in a hardened environment. Hardening involves turning off access to
anything
that is not needed, and only allowing what is needed. All mail
servers, ftp
servers, rpc services, telnet, or any other clear text communications
port needs
to be removed. All communications into and out of the box needs to be
encrypted, with the exception of HTTP (although we were using HTTPS).
</p>
<p>
All of this was necessary. I understand the principles behind it.
However,
I decided to ask their security analyst how to learn more--so we
don't run
into this problem again. He gave me a link to
<link href="www.sans.org">SANS institute</link> and a word of advice,
"Be
paranoid. Don't trust anything."
</p>
<p>
There is a point where the aforementioned philosophy goes a bit too
far. The
case and point relates to a story I heard working with the DoD.
During the
height of the "Cold War" between the US and Russia, a US
commanding
officer required that all the computers be placed on these huge power
conditioners to reduce the Electro-Magnetic Interference (EMI) coming
from the
computers. His rationalization was that he was positive KGB agents
had the
technology that they could read the EMI interference on the power
lines and
read the bits on the computers. In hind sight this is absurd, no one
can
identify the bits traveling on a computer from EMI due to the level
of noise
(clocks, addressing lines, <em>encrypted data</em>, and other
computers on the
network).
</p>
<p>
The morale of the story is be paranoid to a point. Avalon is
designed to be
a trusted system, and will be improved to work in an untrusted
network.
</p>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:48 $
</legal>
</footer>
</document>
1.1
jakarta-avalon/src/xdocs/design/separation-of-concerns.xml
Index: separation-of-concerns.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Avalon Developer Documentation</title>
<subtitle>Multi Dimensional Separation of Concerns</subtitle>
<authors>
<person name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Separation of Concerns">
<p>
The concept of using different points of view within the the system
goes a long way in the overall comprehension of the system.
</p>
<p>You can get more formal information in this paper: <link
href="http://www.research.ibm.com/hyperspace/MDSOC.htm">Multi-Dimensional
Separation of Concerns</link>.</p><s2 title="What it Means">
<p>
"Separation of Concerns" in its simplest form is
separating
a problem into different points of view. For instance, the
documentation
uses the "Separation of Concerns" pattern to make the
documents
comprehensible (we have separate documents for Developers,
Administrators,
and Block Implementers). The documents also use the pattern with
XML and
XSL so that the look is separated from the content. Either can
change
without breaking the other.
</p>
<p>
This pattern is less clear to point out in the code, however the
concept
is evident. There are several interfaces included in Avalon that
identify
an object's role within the system. For instance, all Components
have certain
contracts -- therefore any object that implements the Component
interface
must comply with those Contracts. This allows developers to
manipulate
Components using a standard interface, without worrying about the
semantics
of the implementation. They are separate concerns.
</p>
</s2>
<s2 title="How to Use It">
<p>
There are many ways to separate concern areas, but in Avalon
we use interfaces to define the concern areas addressed in
code.
</p>
<p>
Every time you use interfaces within Object Oriented Programming
(OOP),
you are using the "Separation of Concerns" Pattern. The
interface
separates the concern of the implementation from the concern of the
user
of the interface. For example, every Object that can be configured
implements the Configurable interface. The contract surrounding the
Configurable interface is that the instantiator of the object
passes a
Configuration object to the Configurable object (see "Inversion
of Control"). Just what the Configurable object does with the
passed Configuration object is irrelevant to the instantiator.
</p>
</s2>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:48 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/dtd/changes-v10.dtd
Index: changes-v10.dtd
===================================================================
<!-- ===================================================================
Apache Changes DTD (Version 1.0)
PURPOSE:
This DTD was developed to create a simple yet powerful document
type for software development changes for use with the Apache projects.
It is an XML-compliant DTD and it's maintained by the Apache XML
project.
TYPICAL INVOCATION:
<!DOCTYPE document PUBLIC
"-//APACHE//DTD Changes Vx.yz//EN"
"http://xml.apache.org/DTD/changes-vxyz.dtd">
where
x := major version
y := minor version
z := status identifier (optional)
NOTES:
It is important, expecially in open developped software projects, to keep
track of software changes both to give users indications of bugs that might
have been resolved, as well, and not less important, to provide credits
for the support given to the project. It is considered vital to provide
adequate payback using recognition and credits to let users and developers
feel part of the community, thus increasing development power.
AUTHORS:
Stefano Mazzocchi <[EMAIL PROTECTED]>
FIXME:
CHANGE HISTORY:
19991129 Initial version. (SM)
20000316 Added bugfixing attribute. (SM)
COPYRIGHT:
Copyright (c) @year@ The Apache Software Foundation.
Permission to copy in any form is granted provided this notice is
included in all copies. Permission to redistribute is granted
provided this file is distributed untouched in all its parts and
included files.
==================================================================== -->
<!-- =============================================================== -->
<!-- Extend the Documentation DTD -->
<!-- =============================================================== -->
<!-- FIXME (SM): this is hardcoding. Find a better way of doing this
possibly using public identifiers -->
<!ENTITY % document-dtd SYSTEM "document-v10.dtd">
%document-dtd;
<!-- =============================================================== -->
<!-- Common entities -->
<!-- =============================================================== -->
<!ENTITY % types "add|remove|update|fix">
<!-- =============================================================== -->
<!-- Document Type Definition -->
<!-- =============================================================== -->
<!ELEMENT changes (devs, release*)>
<!ATTLIST changes %common.att;
%title.att;>
<!ELEMENT devs (person+)>
<!ATTLIST devs %common.att;>
<!ELEMENT release (action+)>
<!ATTLIST release %common.att;
version CDATA #REQUIRED
date CDATA #REQUIRED>
<!ELEMENT action (%content.mix;)*>
<!ATTLIST action %common.att;
dev IDREF #REQUIRED
type (%types;) #IMPLIED
due-to CDATA #IMPLIED
due-to-email CDATA #IMPLIED
fixes-bug CDATA #IMPLIED>
<!-- =============================================================== -->
<!-- End of DTD -->
<!-- =============================================================== -->
1.1 jakarta-avalon/src/xdocs/dtd/characters.ent
Index: characters.ent
===================================================================
<!--
Portions (C) International Organization for Standardization 1986
Permission to copy in any form is granted for use with
conforming SGML systems and applications as defined in
ISO 8879, provided this notice is included in all copies.
-->
<!--
Character entity set.
-->
<!-- Latin A -->
<!ENTITY nbsp " "> <!-- U+00A0 ISOnum - no-break space =
non-breaking space -->
<!ENTITY iexcl "¡"> <!-- U+00A1 ISOnum - inverted exclamation
mark -->
<!ENTITY cent "¢"> <!-- U+00A2 ISOnum - cent sign
-->
<!ENTITY pound "£"> <!-- U+00A3 ISOnum - pound sign
-->
<!ENTITY curren "¤"> <!-- U+00A4 ISOnum - currency sign
-->
<!ENTITY yen "¥"> <!-- U+00A5 ISOnum - yen sign = yuan sign
-->
<!ENTITY brvbar "¦"> <!-- U+00A6 ISOnum - broken bar = broken
vertical bar -->
<!ENTITY sect "§"> <!-- U+00A7 ISOnum - section sign
-->
<!ENTITY uml "¨"> <!-- U+00A8 ISOdia - diaeresis = spacing
diaeresis -->
<!ENTITY copy "©"> <!-- U+00A9 ISOnum - copyright sign
-->
<!ENTITY ordf "ª"> <!-- U+00AA ISOnum - feminine ordinal
indicator -->
<!ENTITY laquo "«"> <!-- U+00AB ISOnum - left-pointing double
angle quotation mark = left pointing guillemet -->
<!ENTITY not "¬"> <!-- U+00AC ISOnum - not sign
-->
<!ENTITY shy "­"> <!-- U+00AD ISOnum - soft hyphen =
discretionary hyphen -->
<!ENTITY reg "®"> <!-- U+00AE ISOnum - registered sign =
registered trade mark sign -->
<!ENTITY macr "¯"> <!-- U+00AF ISOdia - macron = spacing macron
= overline = APL overbar -->
<!ENTITY deg "°"> <!-- U+00B0 ISOnum - degree sign
-->
<!ENTITY plusmn "±"> <!-- U+00B1 ISOnum - plus-minus sign =
plus-or-minus sign -->
<!ENTITY sup2 "²"> <!-- U+00B2 ISOnum - superscript two =
superscript digit two = squared -->
<!ENTITY sup3 "³"> <!-- U+00B3 ISOnum - superscript three =
superscript digit three = cubed -->
<!ENTITY acute "´"> <!-- U+00B4 ISOdia - acute accent = spacing
acute -->
<!ENTITY micro "µ"> <!-- U+00B5 ISOnum - micro sign
-->
<!ENTITY para "¶"> <!-- U+00B6 ISOnum - pilcrow sign = paragraph
sign -->
<!ENTITY middot "·"> <!-- U+00B7 ISOnum - middle dot = Georgian
comma = Greek middle dot -->
<!ENTITY cedil "¸"> <!-- U+00B8 ISOdia - cedilla = spacing
cedilla -->
<!ENTITY sup1 "¹"> <!-- U+00B9 ISOnum - superscript one =
superscript digit one -->
<!ENTITY ordm "º"> <!-- U+00BA ISOnum - masculine ordinal
indicator -->
<!ENTITY raquo "»"> <!-- U+00BB ISOnum - right-pointing double
angle quotation mark = right pointing guillemet -->
<!ENTITY frac14 "¼"> <!-- U+00BC ISOnum - vulgar fraction one
quarter = fraction one quarter -->
<!ENTITY frac12 "½"> <!-- U+00BD ISOnum - vulgar fraction one half
= fraction one half -->
<!ENTITY frac34 "¾"> <!-- U+00BE ISOnum - vulgar fraction three
quarters = fraction three quarters -->
<!ENTITY iquest "¿"> <!-- U+00BF ISOnum - inverted question mark =
turned question mark -->
<!ENTITY Agrave "À"> <!-- U+00C0 ISOlat1 - latin capital letter A
with grave = latin capital letter A grave -->
<!ENTITY Aacute "Á"> <!-- U+00C1 ISOlat1 - latin capital letter A
with acute -->
<!ENTITY Acirc "Â"> <!-- U+00C2 ISOlat1 - latin capital letter A
with circumflex -->
<!ENTITY Atilde "Ã"> <!-- U+00C3 ISOlat1 - latin capital letter A
with tilde -->
<!ENTITY Auml "Ä"> <!-- U+00C4 ISOlat1 - latin capital letter A
with diaeresis -->
<!ENTITY Aring "Å"> <!-- U+00C5 ISOlat1 - latin capital letter A
with ring above = latin capital letter A ring -->
<!ENTITY AElig "Æ"> <!-- U+00C6 ISOlat1 - latin capital letter AE
= latin capital ligature AE -->
<!ENTITY Ccedil "Ç"> <!-- U+00C7 ISOlat1 - latin capital letter C
with cedilla -->
<!ENTITY Egrave "È"> <!-- U+00C8 ISOlat1 - latin capital letter E
with grave -->
<!ENTITY Eacute "É"> <!-- U+00C9 ISOlat1 - latin capital letter E
with acute -->
<!ENTITY Ecirc "Ê"> <!-- U+00CA ISOlat1 - latin capital letter E
with circumflex -->
<!ENTITY Euml "Ë"> <!-- U+00CB ISOlat1 - latin capital letter E
with diaeresis -->
<!ENTITY Igrave "Ì"> <!-- U+00CC ISOlat1 - latin capital letter I
with grave -->
<!ENTITY Iacute "Í"> <!-- U+00CD ISOlat1 - latin capital letter I
with acute -->
<!ENTITY Icirc "Î"> <!-- U+00CE ISOlat1 - latin capital letter I
with circumflex -->
<!ENTITY Iuml "Ï"> <!-- U+00CF ISOlat1 - latin capital letter I
with diaeresis -->
<!ENTITY ETH "Ð"> <!-- U+00D0 ISOlat1 - latin capital letter ETH
-->
<!ENTITY Ntilde "Ñ"> <!-- U+00D1 ISOlat1 - latin capital letter N
with tilde -->
<!ENTITY Ograve "Ò"> <!-- U+00D2 ISOlat1 - latin capital letter O
with grave -->
<!ENTITY Oacute "Ó"> <!-- U+00D3 ISOlat1 - latin capital letter O
with acute -->
<!ENTITY Ocirc "Ô"> <!-- U+00D4 ISOlat1 - latin capital letter O
with circumflex -->
<!ENTITY Otilde "Õ"> <!-- U+00D5 ISOlat1 - latin capital letter O
with tilde -->
<!ENTITY Ouml "Ö"> <!-- U+00D6 ISOlat1 - latin capital letter O
with diaeresis -->
<!ENTITY times "×"> <!-- U+00D7 ISOnum - multiplication sign
-->
<!ENTITY Oslash "Ø"> <!-- U+00D8 ISOlat1 - latin capital letter O
with stroke = latin capital letter O slash -->
<!ENTITY Ugrave "Ù"> <!-- U+00D9 ISOlat1 - latin capital letter U
with grave -->
<!ENTITY Uacute "Ú"> <!-- U+00DA ISOlat1 - latin capital letter U
with acute -->
<!ENTITY Ucirc "Û"> <!-- U+00DB ISOlat1 - latin capital letter U
with circumflex -->
<!ENTITY Uuml "Ü"> <!-- U+00DC ISOlat1 - latin capital letter U
with diaeresis -->
<!ENTITY Yacute "Ý"> <!-- U+00DD ISOlat1 - latin capital letter Y
with acute -->
<!ENTITY THORN "Þ"> <!-- U+00DE ISOlat1 - latin capital letter
THORN -->
<!ENTITY szlig "ß"> <!-- U+00DF ISOlat1 - latin small letter sharp
s = ess-zed -->
<!ENTITY agrave "à"> <!-- U+00E0 ISOlat1 - latin small letter a
with grave = latin small letter a grave -->
<!ENTITY aacute "á"> <!-- U+00E1 ISOlat1 - latin small letter a
with acute -->
<!ENTITY acirc "â"> <!-- U+00E2 ISOlat1 - latin small letter a
with circumflex -->
<!ENTITY atilde "ã"> <!-- U+00E3 ISOlat1 - latin small letter a
with tilde -->
<!ENTITY auml "ä"> <!-- U+00E4 ISOlat1 - latin small letter a
with diaeresis -->
<!ENTITY aring "å"> <!-- U+00E5 ISOlat1 - latin small letter a
with ring above = latin small letter a ring -->
<!ENTITY aelig "æ"> <!-- U+00E6 ISOlat1 - latin small letter ae =
latin small ligature ae -->
<!ENTITY ccedil "ç"> <!-- U+00E7 ISOlat1 - latin small letter c
with cedilla -->
<!ENTITY egrave "è"> <!-- U+00E8 ISOlat1 - latin small letter e
with grave -->
<!ENTITY eacute "é"> <!-- U+00E9 ISOlat1 - latin small letter e
with acute -->
<!ENTITY ecirc "ê"> <!-- U+00EA ISOlat1 - latin small letter e
with circumflex -->
<!ENTITY euml "ë"> <!-- U+00EB ISOlat1 - latin small letter e
with diaeresis -->
<!ENTITY igrave "ì"> <!-- U+00EC ISOlat1 - latin small letter i
with grave -->
<!ENTITY iacute "í"> <!-- U+00ED ISOlat1 - latin small letter i
with acute -->
<!ENTITY icirc "î"> <!-- U+00EE ISOlat1 - latin small letter i
with circumflex -->
<!ENTITY iuml "ï"> <!-- U+00EF ISOlat1 - latin small letter i
with diaeresis -->
<!ENTITY eth "ð"> <!-- U+00F0 ISOlat1 - latin small letter eth
-->
<!ENTITY ntilde "ñ"> <!-- U+00F1 ISOlat1 - latin small letter n
with tilde -->
<!ENTITY ograve "ò"> <!-- U+00F2 ISOlat1 - latin small letter o
with grave -->
<!ENTITY oacute "ó"> <!-- U+00F3 ISOlat1 - latin small letter o
with acute -->
<!ENTITY ocirc "ô"> <!-- U+00F4 ISOlat1 - latin small letter o
with circumflex -->
<!ENTITY otilde "õ"> <!-- U+00F5 ISOlat1 - latin small letter o
with tilde -->
<!ENTITY ouml "ö"> <!-- U+00F6 ISOlat1 - latin small letter o
with diaeresis -->
<!ENTITY divide "÷"> <!-- U+00F7 ISOnum - division sign
-->
<!ENTITY oslash "ø"> <!-- U+00F8 ISOlat1 - latin small letter o
with stroke = latin small letter o slash -->
<!ENTITY ugrave "ù"> <!-- U+00F9 ISOlat1 - latin small letter u
with grave -->
<!ENTITY uacute "ú"> <!-- U+00FA ISOlat1 - latin small letter u
with acute -->
<!ENTITY ucirc "û"> <!-- U+00FB ISOlat1 - latin small letter u
with circumflex -->
<!ENTITY uuml "ü"> <!-- U+00FC ISOlat1 - latin small letter u
with diaeresis -->
<!ENTITY yacute "ý"> <!-- U+00FD ISOlat1 - latin small letter y
with acute -->
<!ENTITY thorn "þ"> <!-- U+00FE ISOlat1 - latin small letter thorn
-->
<!ENTITY yuml "ÿ"> <!-- U+00FF ISOlat1 - latin small letter y
with diaeresis -->
<!-- Latin Extended-A -->
<!ENTITY OElig "Œ"> <!-- U+0152 ISOlat2 - latin capital ligature
OE -->
<!ENTITY oelig "œ"> <!-- U+0153 ISOlat2 - latin small ligature oe
-->
<!-- ligature is a misnomer, this is a separate character in some languages
-->
<!ENTITY Scaron "Š"> <!-- U+0160 ISOlat2 - latin capital letter S
with caron -->
<!ENTITY scaron "š"> <!-- U+0161 ISOlat2 - latin small letter s
with caron -->
<!ENTITY Yuml "Ÿ"> <!-- U+0178 ISOlat2 - latin capital letter Y
with diaeresis -->
<!-- Spacing Modifier Letters -->
<!ENTITY circ "ˆ"> <!-- U+02C6 ISOpub - modifier letter
circumflex accent -->
<!ENTITY tilde "˜"> <!-- U+02DC ISOdia - small tilde
-->
<!-- General Punctuation -->
<!ENTITY ensp " "> <!-- U+2002 ISOpub - en space
-->
<!ENTITY emsp " "> <!-- U+2003 ISOpub - em space
-->
<!ENTITY thinsp " "> <!-- U+2009 ISOpub - thin space
-->
<!ENTITY zwnj "‌"> <!-- U+200C RFC 2070 - zero width non-joiner
-->
<!ENTITY zwj "‍"> <!-- U+200D RFC 2070 - zero width joiner
-->
<!ENTITY lrm "‎"> <!-- U+200E RFC 2070 - left-to-right mark
-->
<!ENTITY rlm "‏"> <!-- U+200F RFC 2070 - right-to-left mark
-->
<!ENTITY ndash "–"> <!-- U+2013 ISOpub - en dash
-->
<!ENTITY mdash "—"> <!-- U+2014 ISOpub - em dash
-->
<!ENTITY lsquo "‘"> <!-- U+2018 ISOnum - left single quotation
mark -->
<!ENTITY rsquo "’"> <!-- U+2019 ISOnum - right single quotation
mark -->
<!ENTITY sbquo "‚"> <!-- U+201A NEW - single low-9 quotation
mark -->
<!ENTITY ldquo "“"> <!-- U+201C ISOnum - left double quotation
mark -->
<!ENTITY rdquo "”"> <!-- U+201D ISOnum - right double quotation
mark, -->
<!ENTITY bdquo "„"> <!-- U+201E NEW - double low-9 quotation
mark -->
<!ENTITY dagger "†"> <!-- U+2020 ISOpub - dagger
-->
<!ENTITY Dagger "‡"> <!-- U+2021 ISOpub - double dagger
-->
<!ENTITY permil "‰"> <!-- U+2030 ISOtech - per mille sign
-->
<!ENTITY lsaquo "‹"> <!-- U+2039 ISO prop. - single left-pointing
angle quotation mark -->
<!-- lsaquo is proposed but not yet ISO standardized -->
<!ENTITY rsaquo "›"> <!-- U+203A ISO prop. - single right-pointing
angle quotation mark -->
<!-- rsaquo is proposed but not yet ISO standardized -->
<!ENTITY euro "€"> <!-- U+20AC NEW - euro sign
-->
<!-- Latin Extended-B -->
<!ENTITY fnof "ƒ"> <!-- U+0192 ISOtech - latin small f with hook
= function = florin -->
<!-- Greek -->
<!ENTITY Alpha "Α"> <!-- U+0391 - greek capital letter
alpha -->
<!ENTITY Beta "Β"> <!-- U+0392 - greek capital letter
beta -->
<!ENTITY Gamma "Γ"> <!-- U+0393 ISOgrk3 - greek capital letter
gamma -->
<!ENTITY Delta "Δ"> <!-- U+0394 ISOgrk3 - greek capital letter
delta -->
<!ENTITY Epsilon "Ε"> <!-- U+0395 - greek capital letter
epsilon -->
<!ENTITY Zeta "Ζ"> <!-- U+0396 - greek capital letter
zeta -->
<!ENTITY Eta "Η"> <!-- U+0397 - greek capital letter eta
-->
<!ENTITY Theta "Θ"> <!-- U+0398 ISOgrk3 - greek capital letter
theta -->
<!ENTITY Iota "Ι"> <!-- U+0399 - greek capital letter
iota -->
<!ENTITY Kappa "Κ"> <!-- U+039A - greek capital letter
kappa -->
<!ENTITY Lambda "Λ"> <!-- U+039B ISOgrk3 - greek capital letter
lambda -->
<!ENTITY Mu "Μ"> <!-- U+039C - greek capital letter mu
-->
<!ENTITY Nu "Ν"> <!-- U+039D - greek capital letter nu
-->
<!ENTITY Xi "Ξ"> <!-- U+039E ISOgrk3 - greek capital letter xi
-->
<!ENTITY Omicron "Ο"> <!-- U+039F - greek capital letter
omicron -->
<!ENTITY Pi "Π"> <!-- U+03A0 ISOgrk3 - greek capital letter pi
-->
<!ENTITY Rho "Ρ"> <!-- U+03A1 - greek capital letter rho
-->
<!ENTITY Sigma "Σ"> <!-- U+03A3 ISOgrk3 - greek capital letter
sigma -->
<!ENTITY Tau "Τ"> <!-- U+03A4 - greek capital letter tau
-->
<!ENTITY Upsilon "Υ"> <!-- U+03A5 ISOgrk3 - greek capital letter
upsilon -->
<!ENTITY Phi "Φ"> <!-- U+03A6 ISOgrk3 - greek capital letter phi
-->
<!ENTITY Chi "Χ"> <!-- U+03A7 - greek capital letter chi
-->
<!ENTITY Psi "Ψ"> <!-- U+03A8 ISOgrk3 - greek capital letter psi
-->
<!ENTITY Omega "Ω"> <!-- U+03A9 ISOgrk3 - greek capital letter
omega -->
<!ENTITY alpha "α"> <!-- U+03B1 ISOgrk3 - greek small letter alpha
-->
<!ENTITY beta "β"> <!-- U+03B2 ISOgrk3 - greek small letter beta
-->
<!ENTITY gamma "γ"> <!-- U+03B3 ISOgrk3 - greek small letter gamma
-->
<!ENTITY delta "δ"> <!-- U+03B4 ISOgrk3 - greek small letter delta
-->
<!ENTITY epsilon "ε"> <!-- U+03B5 ISOgrk3 - greek small letter
epsilon -->
<!ENTITY zeta "ζ"> <!-- U+03B6 ISOgrk3 - greek small letter zeta
-->
<!ENTITY eta "η"> <!-- U+03B7 ISOgrk3 - greek small letter eta
-->
<!ENTITY theta "θ"> <!-- U+03B8 ISOgrk3 - greek small letter theta
-->
<!ENTITY iota "ι"> <!-- U+03B9 ISOgrk3 - greek small letter iota
-->
<!ENTITY kappa "κ"> <!-- U+03BA ISOgrk3 - greek small letter kappa
-->
<!ENTITY lambda "λ"> <!-- U+03BB ISOgrk3 - greek small letter
lambda -->
<!ENTITY mu "μ"> <!-- U+03BC ISOgrk3 - greek small letter mu
-->
<!ENTITY nu "ν"> <!-- U+03BD ISOgrk3 - greek small letter nu
-->
<!ENTITY xi "ξ"> <!-- U+03BE ISOgrk3 - greek small letter xi
-->
<!ENTITY omicron "ο"> <!-- U+03BF NEW - greek small letter
omicron -->
<!ENTITY pi "π"> <!-- U+03C0 ISOgrk3 - greek small letter pi
-->
<!ENTITY rho "ρ"> <!-- U+03C1 ISOgrk3 - greek small letter rho
-->
<!ENTITY sigmaf "ς"> <!-- U+03C2 ISOgrk3 - greek small letter final
sigma -->
<!ENTITY sigma "σ"> <!-- U+03C3 ISOgrk3 - greek small letter sigma
-->
<!ENTITY tau "τ"> <!-- U+03C4 ISOgrk3 - greek small letter tau
-->
<!ENTITY upsilon "υ"> <!-- U+03C5 ISOgrk3 - greek small letter
upsilon -->
<!ENTITY phi "φ"> <!-- U+03C6 ISOgrk3 - greek small letter phi
-->
<!ENTITY chi "χ"> <!-- U+03C7 ISOgrk3 - greek small letter chi
-->
<!ENTITY psi "ψ"> <!-- U+03C8 ISOgrk3 - greek small letter psi
-->
<!ENTITY omega "ω"> <!-- U+03C9 ISOgrk3 - greek small letter omega
-->
<!ENTITY thetasym "ϑ"> <!-- U+03D1 NEW - greek small letter theta
symbol -->
<!ENTITY upsih "ϒ"> <!-- U+03D2 NEW - greek upsilon with hook
symbol -->
<!ENTITY piv "ϖ"> <!-- U+03D6 ISOgrk3 - greek pi symbol
-->
<!-- General Punctuation -->
<!ENTITY bull "•"> <!-- U+2022 ISOpub - bullet = black small
circle -->
<!ENTITY hellip "…"> <!-- U+2026 ISOpub - horizontal ellipsis =
three dot leader -->
<!ENTITY prime "′"> <!-- U+2032 ISOtech - prime = minutes = feet
-->
<!ENTITY Prime "″"> <!-- U+2033 ISOtech - double prime = seconds =
inches -->
<!ENTITY oline "‾"> <!-- U+203E NEW - overline = spacing
overscore -->
<!ENTITY frasl "⁄"> <!-- U+2044 NEW - fraction slash
-->
<!-- Letterlike Symbols -->
<!ENTITY weierp "℘"> <!-- U+2118 ISOamso - script capital P = power
set = Weierstrass p -->
<!ENTITY image "ℑ"> <!-- U+2111 ISOamso - blackletter capital I =
imaginary part -->
<!ENTITY real "ℜ"> <!-- U+211C ISOamso - blackletter capital R =
real part symbol -->
<!ENTITY trade "™"> <!-- U+2122 ISOnum - trade mark sign
-->
<!ENTITY alefsym "ℵ"> <!-- U+2135 NEW - alef symbol = first
transfinite cardinal -->
<!-- Arrows -->
<!ENTITY larr "←"> <!-- U+2190 ISOnum - leftwards arrow
-->
<!ENTITY uarr "↑"> <!-- U+2191 ISOnum - upwards arrow
-->
<!ENTITY rarr "→"> <!-- U+2192 ISOnum - rightwards arrow
-->
<!ENTITY darr "↓"> <!-- U+2193 ISOnum - downwards arrow
-->
<!ENTITY harr "↔"> <!-- U+2194 ISOamsa - left right arrow
-->
<!ENTITY crarr "↵"> <!-- U+21B5 NEW - downwards arrow with
corner leftwards = carriage return -->
<!ENTITY lArr "⇐"> <!-- U+21D0 ISOtech - leftwards double arrow
-->
<!ENTITY uArr "⇑"> <!-- U+21D1 ISOamsa - upwards double arrow
-->
<!ENTITY rArr "⇒"> <!-- U+21D2 ISOtech - rightwards double arrow
-->
<!ENTITY dArr "⇓"> <!-- U+21D3 ISOamsa - downwards double arrow
-->
<!ENTITY hArr "⇔"> <!-- U+21D4 ISOamsa - left right double arrow
-->
<!-- Mathematical Operators -->
<!ENTITY forall "∀"> <!-- U+2200 ISOtech - for all
-->
<!ENTITY part "∂"> <!-- U+2202 ISOtech - partial differential
-->
<!ENTITY exist "∃"> <!-- U+2203 ISOtech - there exists
-->
<!ENTITY empty "∅"> <!-- U+2205 ISOamso - empty set = null set =
diameter -->
<!ENTITY nabla "∇"> <!-- U+2207 ISOtech - nabla = backward
difference -->
<!ENTITY isin "∈"> <!-- U+2208 ISOtech - element of
-->
<!ENTITY notin "∉"> <!-- U+2209 ISOtech - not an element of
-->
<!ENTITY ni "∋"> <!-- U+220B ISOtech - contains as member
-->
<!ENTITY prod "∏"> <!-- U+220F ISOamsb - n-ary product = product
sign -->
<!ENTITY sum "∑"> <!-- U+2211 ISOamsb - n-ary sumation
-->
<!ENTITY minus "−"> <!-- U+2212 ISOtech - minus sign
-->
<!ENTITY lowast "∗"> <!-- U+2217 ISOtech - asterisk operator
-->
<!ENTITY radic "√"> <!-- U+221A ISOtech - square root = radical
sign -->
<!ENTITY prop "∝"> <!-- U+221D ISOtech - proportional to
-->
<!ENTITY infin "∞"> <!-- U+221E ISOtech - infinity
-->
<!ENTITY ang "∠"> <!-- U+2220 ISOamso - angle
-->
<!ENTITY and "∧"> <!-- U+2227 ISOtech - logical and = wedge
-->
<!ENTITY or "∨"> <!-- U+2228 ISOtech - logical or = vee
-->
<!ENTITY cap "∩"> <!-- U+2229 ISOtech - intersection = cap
-->
<!ENTITY cup "∪"> <!-- U+222A ISOtech - union = cup
-->
<!ENTITY int "∫"> <!-- U+222B ISOtech - integral
-->
<!ENTITY there4 "∴"> <!-- U+2234 ISOtech - therefore
-->
<!ENTITY sim "∼"> <!-- U+223C ISOtech - tilde operator = varies
with = similar to -->
<!ENTITY cong "≅"> <!-- U+2245 ISOtech - approximately equal to
-->
<!ENTITY asymp "≈"> <!-- U+2248 ISOamsr - almost equal to =
asymptotic to -->
<!ENTITY ne "≠"> <!-- U+2260 ISOtech - not equal to
-->
<!ENTITY equiv "≡"> <!-- U+2261 ISOtech - identical to
-->
<!ENTITY le "≤"> <!-- U+2264 ISOtech - less-than or equal to
-->
<!ENTITY ge "≥"> <!-- U+2265 ISOtech - greater-than or equal to
-->
<!ENTITY sub "⊂"> <!-- U+2282 ISOtech - subset of
-->
<!ENTITY sup "⊃"> <!-- U+2283 ISOtech - superset of
-->
<!ENTITY nsub "⊄"> <!-- U+2284 ISOamsn - not a subset of
-->
<!ENTITY sube "⊆"> <!-- U+2286 ISOtech - subset of or equal to
-->
<!ENTITY supe "⊇"> <!-- U+2287 ISOtech - superset of or equal to
-->
<!ENTITY oplus "⊕"> <!-- U+2295 ISOamsb - circled plus = direct
sum -->
<!ENTITY otimes "⊗"> <!-- U+2297 ISOamsb - circled times = vector
product -->
<!ENTITY perp "⊥"> <!-- U+22A5 ISOtech - up tack = orthogonal to
= perpendicular -->
<!ENTITY sdot "⋅"> <!-- U+22C5 ISOamsb - dot operator
-->
<!-- Miscellaneous Technical -->
<!ENTITY lceil "⌈"> <!-- U+2308 ISOamsc - left ceiling = apl
upstile -->
<!ENTITY rceil "⌉"> <!-- U+2309 ISOamsc - right ceiling
-->
<!ENTITY lfloor "⌊"> <!-- U+230A ISOamsc - left floor = apl
downstile -->
<!ENTITY rfloor "⌋"> <!-- U+230B ISOamsc - right floor
-->
<!ENTITY lang "〈"> <!-- U+2329 ISOtech - left-pointing angle
bracket = bra -->
<!ENTITY rang "〉"> <!-- U+232A ISOtech - right-pointing angle
bracket = ket -->
<!-- Geometric Shapes -->
<!ENTITY loz "◊"> <!-- U+25CA ISOpub - lozenge
-->
<!-- Miscellaneous Symbols -->
<!ENTITY spades "♠"> <!-- U+2660 ISOpub - black spade suit
-->
<!ENTITY clubs "♣"> <!-- U+2663 ISOpub - black club suit =
shamrock -->
<!ENTITY hearts "♥"> <!-- U+2665 ISOpub - black heart suit =
valentine -->
<!ENTITY diams "♦"> <!-- U+2666 ISOpub - black diamond suit
-->
1.1 jakarta-avalon/src/xdocs/dtd/document-v10.dtd
Index: document-v10.dtd
===================================================================
<!-- ===================================================================
Apache Documentation DTD (Version 1.0)
PURPOSE:
This DTD was developed to create a simple yet powerful document
type for software documentation for use with the Apache projects.
It is an XML-compliant DTD and it's maintained by the Apache XML
project.
TYPICAL INVOCATION:
<!DOCTYPE document PUBLIC
"-//APACHE//DTD Documentation Vx.yz//EN"
"http://xml.apache.org/DTD/document-vxyz.dtd">
where
x := major version
y := minor version
z := status identifier (optional)
NOTES:
Many of the design patterns used in this DTD were take from the
W3C XML Specification DTD edited by Eve Maler <[EMAIL PROTECTED]>.
Where possible, great care has been used to reutilize HTML tag
names to reduce learning efforts and to allow HTML editors to be
used for complex authorings like tables and lists.
AUTHORS:
Stefano Mazzocchi <[EMAIL PROTECTED]>
Berin Loritsch <[EMAIL PROTECTED]>
FIXME:
- how can we include char entities without hardwiring them?
- should "form" tags be included?
- should all style-free HTML 4.0 markup tags be included?
- how do we handle the idea of "soft" xlinks?
- should we add "soft" links to images?
CHANGE HISTORY:
19991121 Initial version. (SM)
19991123 Replaced "res" with more standard "strong" for emphasis. (SM)
19991124 Added "fork" element for window forking behavior. (SM)
19991124 Added "img-inline" element to separate from "img". (SM)
19991129 Removed "affiliation" from "author". (SM)
19991129 Made "author" empty and moved "name|email" as attributes (SM)
19991215 Simplified table section (SM)
19991215 Changed "img-block" in more friendly "figure" (SM)
20000125 Added the "icon" image (SM)
20000126 Allowed "anchor" in all levels (SM)
20000404 Removed the "role" attribute from common-xxx.att (SM)
20000606 Allowed nested markup tags (SM)
20000911 Allowed link tags inside markup (BL)
COPYRIGHT:
Copyright (c) 1999-2000 The Apache Software Foundation.
Permission to copy in any form is granted provided this notice is
included in all copies. Permission to redistribute is granted
provided this file is distributed untouched in all its parts and
included files.
==================================================================== -->
<!-- =============================================================== -->
<!-- Common character entities (included from external file) -->
<!-- =============================================================== -->
<!-- FIXME (SM): this is hardcoding. Find a better way of doing this
possibly using public identifiers of ISO latin char sets -->
<!ENTITY % charEntity SYSTEM "characters.ent">
%charEntity;
<!-- =============================================================== -->
<!-- Userful entitieis for increased DTD readability -->
<!-- =============================================================== -->
<!ENTITY % text "#PCDATA">
<!-- =============================================================== -->
<!-- Entities for general XML compliance -->
<!-- =============================================================== -->
<!-- Common attributes
Every element has an ID attribute (sometimes required,
but usually optional) for links. %common.att;
is for common attributes where the ID is optional, and
%common-idreq.att; is for common attributes where the
ID is required.
-->
<!ENTITY % common.att
'id ID #IMPLIED
xml:lang NMTOKEN #IMPLIED'>
<!ENTITY % common-idreq.att
'id ID #REQUIRED
xml:lang NMTOKEN #IMPLIED'>
<!-- xml:space attribute ===============================================
Indicates that the element contains white space
that the formatter or other application should retain,
as appropriate to its function.
==================================================================== -->
<!ENTITY % xmlspace.att
'xml:space (default|preserve) #FIXED "preserve"'>
<!-- def attribute =====================================================
Points to the element where the relevant definition can be
found, using the IDREF mechanism. %def.att; is for optional
def attributes, and %def-req.att; is for required def
attributes.
==================================================================== -->
<!ENTITY % def.att
'def IDREF #IMPLIED'>
<!ENTITY % def-req.att
'def IDREF #REQUIRED'>
<!-- ref attribute =====================================================
Points to the element where more information can be found,
using the IDREF mechanism. %ref.att; is for optional
ref attributes, and %ref-req.att; is for required ref
attributes.
================================================================== -->
<!ENTITY % ref.att
'ref IDREF #IMPLIED'>
<!ENTITY % ref-req.att
'ref IDREF #REQUIRED'>
<!-- =============================================================== -->
<!-- Entities for XLink compliance -->
<!-- =============================================================== -->
<!ENTITY % xlink-simple.att
'type (simple|extended|locator|arc) #FIXED "simple"
href CDATA #IMPLIED
role CDATA #IMPLIED
title CDATA #IMPLIED '>
<!-- 'xmlns CDATA #FIXED
"http://www.w3.org/XML/XLink/0.9" -->
<!-- FIXME: brain-dead IE5 has broken support for
namespace validation and since I use it for editing
I remove this for now -->
<!ENTITY % xlink-user-replace.att
'show (new|parsed|replace) #FIXED "replace"
actuate (user|auto) #FIXED "user" '>
<!ENTITY % xlink-user-new.att
'show (new|parsed|replace) #FIXED "new"
actuate (user|auto) #FIXED "user" '>
<!ENTITY % xlink-auto-parsed.att
'show (new|parsed|replace) #FIXED "parsed"
actuate (user|auto) #FIXED "auto" '>
<!-- FIXME (SM): XLink doesn't yet cover the idea of soft links so
introducing it here using the same namespace is _somewhat_
illegal. Should we create it own namespace?
-->
<!ENTITY % xlink-soft.att
'mode (hard|soft) #FIXED "soft" '>
<!-- =============================================================== -->
<!-- Entities for general usage -->
<!-- =============================================================== -->
<!-- Key attribute =====================================================
Optionally provides a sorting or indexing key, for cases when
the element content is inappropriate for this purpose.
==================================================================== -->
<!ENTITY % key.att
'key CDATA #IMPLIED'>
<!-- Title attributes ==================================================
Indicates that the element requires to have a title.
==================================================================== -->
<!ENTITY % title.att
'title CDATA #REQUIRED'>
<!-- Name attributes ==================================================
Indicates that the element requires to have a name.
==================================================================== -->
<!ENTITY % name.att
'name CDATA #REQUIRED'>
<!-- Email attributes ==================================================
Indicates that the element requires to have an email.
==================================================================== -->
<!ENTITY % email.att
'email CDATA #REQUIRED'>
<!-- =============================================================== -->
<!-- General definitions -->
<!-- =============================================================== -->
<!-- A person is a general human entity -->
<!ELEMENT person EMPTY>
<!ATTLIST person %common.att;
%name.att;
%email.att;>
<!-- =============================================================== -->
<!-- Content definitions -->
<!-- =============================================================== -->
<!ENTITY % local.content.mix "">
<!ENTITY % markup "strong|em|code|sub|sup">
<!ENTITY % links "link|connect|jump|fork|anchor">
<!ENTITY % special "br|img|icon">
<!ENTITY % link-content.mix "%text;|%markup;|%special;%local.content.mix;">
<!ENTITY % content.mix "%link-content.mix;|%links;">
<!-- ==================================================== -->
<!-- Phrase Markup -->
<!-- ==================================================== -->
<!-- Strong (typically bold) -->
<!ELEMENT strong (%text;|%markup;|%links;)*>
<!ATTLIST strong %common.att;>
<!-- Emphasis (typically italic) -->
<!ELEMENT em (%text;|%markup;|%links;)*>
<!ATTLIST em %common.att;>
<!-- Code (typically monospaced) -->
<!ELEMENT code (%text;|%markup;|%links;)*>
<!ATTLIST code %common.att;>
<!-- Superscript (typically smaller and higher) -->
<!ELEMENT sup (%text;|%markup;|%links;)*>
<!ATTLIST sup %common.att;>
<!-- Subscript (typically smaller and lower) -->
<!ELEMENT sub (%text;|%markup;|%links;)*>
<!ATTLIST sub %common.att;>
<!-- FIXME (SM): should we add these HTML 4.0 markups
which are style-free?
-dfn
-samp
-kbd
-var
-cite
-abbr
-acronym
-->
<!-- ==================================================== -->
<!-- Hypertextual Links -->
<!-- ==================================================== -->
<!-- hard replacing link (equivalent of <a ...>) -->
<!ELEMENT link (%link-content.mix;)*>
<!ATTLIST link %common.att;
%xlink-simple.att;
%xlink-user-replace.att;>
<!-- Hard window replacing link (equivalent of <a ... target="_top">) -->
<!ELEMENT jump (%link-content.mix;)*>
<!ATTLIST jump anchor CDATA #IMPLIED
%common.att;
%xlink-simple.att;
%xlink-user-new.att;>
<!-- Hard window forking link (equivalent of <a ... target="_new">) -->
<!ELEMENT fork (%link-content.mix;)*>
<!ATTLIST fork %common.att;
%xlink-simple.att;
%xlink-user-new.att;>
<!-- Anchor point (equivalent of <a name="...">) -->
<!ELEMENT anchor EMPTY>
<!ATTLIST anchor %common-idreq.att;>
<!-- Soft link between processed pages (no equivalent in HTML) -->
<!ELEMENT connect (%link-content.mix;)*>
<!ATTLIST connect %common.att;
%xlink-simple.att;
%xlink-user-replace.att;
%xlink-soft.att;>
<!-- ==================================================== -->
<!-- Specials -->
<!-- ==================================================== -->
<!-- Breakline Object (typically forces line break) -->
<!ELEMENT br EMPTY>
<!ATTLIST br %common.att;>
<!-- Image Object (typically an inlined image) -->
<!-- FIXME (SM): should we have the notion of soft links even here
for inlined objects? -->
<!ELEMENT img EMPTY>
<!ATTLIST img src CDATA #REQUIRED
alt CDATA #REQUIRED
height CDATA #IMPLIED
width CDATA #IMPLIED
usemap CDATA #IMPLIED
ismap (ismap) #IMPLIED
%common.att;>
<!-- Image Icon (typically an inlined image placed as graphical item) -->
<!-- FIXME (SM): should we have the notion of soft links even here
for inlined objects? -->
<!ELEMENT icon EMPTY>
<!ATTLIST icon src CDATA #REQUIRED
alt CDATA #REQUIRED
height CDATA #IMPLIED
width CDATA #IMPLIED
%common.att;>
<!-- =============================================================== -->
<!-- Blocks definitions -->
<!-- =============================================================== -->
<!ENTITY % local.blocks "">
<!ENTITY % paragraphs "p|source|note|fixme|figure">
<!ENTITY % local.lists "%paragraphs;">
<!ENTITY % tables "table">
<!ENTITY % lists "ol|ul|sl|dl|%local.lists;">
<!ENTITY % blocks "anchor|%paragraphs;|%tables;|%lists; %local.blocks;">
<!-- ==================================================== -->
<!-- Paragraphs -->
<!-- ==================================================== -->
<!-- Text Paragraph (normally vertically space delimited) -->
<!ELEMENT p (%content.mix;)*>
<!ATTLIST p %common.att;>
<!-- Source Paragraph (normally space is preserved) -->
<!ELEMENT source (%content.mix;)*>
<!ATTLIST source %common.att;
%xmlspace.att;>
<!-- Note Paragraph (normally shown encapsulated) -->
<!ELEMENT note (%content.mix;)*>
<!ATTLIST note %common.att;>
<!-- Fixme Paragraph (normally not shown) -->
<!ELEMENT fixme (%content.mix;)*>
<!-- the "author" attribute should match the "key" attribute of the
<author> element -->
<!ATTLIST fixme author CDATA #REQUIRED
%common.att;>
<!-- ==================================================== -->
<!-- Tables -->
<!-- ==================================================== -->
<!-- Attributes that indicate the spanning of the table cell -->
<!ENTITY % cell.span
'colspan CDATA "1"
rowspan CDATA "1"'>
<!-- Table element -->
<!ELEMENT table (caption?, tr+)>
<!ATTLIST table %common.att;>
<!-- The table title -->
<!ELEMENT caption (%content.mix;)*>
<!ATTLIST caption %common.att;>
<!-- The table row element -->
<!ELEMENT tr (th|td)+>
<!ATTLIST tr %common.att;>
<!-- The table row header element -->
<!ELEMENT th (%content.mix;)*>
<!ATTLIST th %common.att;
%cell.span;>
<!-- The table row description element -->
<!ELEMENT td (%content.mix;)*>
<!ATTLIST td %common.att;
%cell.span;>
<!-- ==================================================== -->
<!-- Lists -->
<!-- ==================================================== -->
<!-- Unordered list (typically bulleted) -->
<!ELEMENT ul (li|%lists;)+>
<!-- spacing attribute:
Use "normal" to get normal vertical spacing for items;
use "compact" to get less spacing. The default is dependent
on the stylesheet. -->
<!ATTLIST ul
%common.att;
spacing (normal|compact) #IMPLIED>
<!-- Ordered list (typically numbered) -->
<!ELEMENT ol (li|%lists;)+>
<!-- spacing attribute:
Use "normal" to get normal vertical spacing for items;
use "compact" to get less spacing. The default is dependent
on the stylesheet. -->
<!ATTLIST ol
%common.att;
spacing (normal|compact) #IMPLIED>
<!-- Simple list (typically with no mark) -->
<!ELEMENT sl (li|%lists;)+>
<!ATTLIST sl %common.att;>
<!-- List item -->
<!ELEMENT li (%content.mix;|%lists;)*>
<!ATTLIST li %common.att;>
<!-- Definition list (typically two-column) -->
<!ELEMENT dl (dt,dd)+>
<!ATTLIST dl %common.att;>
<!-- Definition term -->
<!ELEMENT dt (%content.mix;)*>
<!ATTLIST dt %common.att;>
<!-- Definition description -->
<!ELEMENT dd (%content.mix;)*>
<!ATTLIST dd %common.att;>
<!-- ==================================================== -->
<!-- Special Blocks -->
<!-- ==================================================== -->
<!-- Image Block (typically a separated and centered image) -->
<!-- FIXME (SM): should we have the notion of soft links even here
for inlined objects? -->
<!ELEMENT figure EMPTY>
<!ATTLIST figure src CDATA #REQUIRED
alt CDATA #REQUIRED
height CDATA #IMPLIED
width CDATA #IMPLIED
usemap CDATA #IMPLIED
ismap (ismap) #IMPLIED
%common.att;>
<!-- =============================================================== -->
<!-- Document -->
<!-- =============================================================== -->
<!ELEMENT document (header?, body, footer?)>
<!ATTLIST document %common.att;>
<!-- ==================================================== -->
<!-- Header -->
<!-- ==================================================== -->
<!ENTITY % local.headers "">
<!ELEMENT header (title, subtitle?, version?, type?, authors,
notice*, abstract? %local.headers;)>
<!ATTLIST header %common.att;>
<!ELEMENT title (%text;)>
<!ATTLIST title %common.att;>
<!ELEMENT subtitle (%text;)>
<!ATTLIST subtitle %common.att;>
<!ELEMENT version (%text;)>
<!ATTLIST version %common.att;>
<!ELEMENT type (%text;)>
<!ATTLIST type %common.att;>
<!ELEMENT authors (person+)>
<!ATTLIST authors %common.att;>
<!ELEMENT notice (%content.mix;)*>
<!ATTLIST notice %common.att;>
<!ELEMENT abstract (%content.mix;)*>
<!ATTLIST abstract %common.att;>
<!-- ==================================================== -->
<!-- Body -->
<!-- ==================================================== -->
<!ENTITY % local.sections "">
<!ENTITY % sections "s1|anchor %local.sections;">
<!ELEMENT body (%sections;)+>
<!ATTLIST body %common.att;>
<!ELEMENT s1 (s2|%blocks;)*>
<!ATTLIST s1 %title.att; %common.att;>
<!ELEMENT s2 (s3|%blocks;)*>
<!ATTLIST s2 %title.att; %common.att;>
<!ELEMENT s3 (s4|%blocks;)*>
<!ATTLIST s3 %title.att; %common.att;>
<!ELEMENT s4 (%blocks;)*>
<!ATTLIST s4 %title.att; %common.att;>
<!-- ==================================================== -->
<!-- Footer -->
<!-- ==================================================== -->
<!ENTITY % local.footers "">
<!ELEMENT footer (legal %local.footers;)>
<!ELEMENT legal (%content.mix;)*>
<!ATTLIST legal %common.att;>
<!-- =============================================================== -->
<!-- End of DTD -->
<!-- =============================================================== -->
1.1 jakarta-avalon/src/xdocs/history/call-to-vote.xml
Index: call-to-vote.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>History</title>
<subtitle>Proposal</subtitle>
<authors>
<person id="SM" name="Stefano Mazzocchi" email="[EMAIL PROTECTED]"/>
</authors>
<notice>
Avalon documentation is under construction. Everything you
can find outside this page is to be considered obsolete.
</notice>
<abstract>
In this mail to the Java Apache mail list, the author
proposes the creation of the Java Apache Server
Framework and explains its goals and requirements.
</abstract>
</header>
<body>
<s1 title="Introduction">
<p>
I spent some time thinking about some of the issues that were
discussed on this
list in the last month, after the first release of Apache JServ 1.0b
and after the
development pressure was reduced.
</p>
<p>
It is clear, to me and to others on this list, that Apache JServ 1.0
just barely
scratched the potentials of this project in sharing IQ and ideas
aiming to fill
those gaps the advent of the Java technology on the server world
produced.
</p>
<p>
It is also clear, from different perspectives (users, developers,
software
engineers, management people), that servers are a big part of the
present/future
of everyday work and that Java allows the creation of performance
oriented, solid and
rapid-delivered server solutions. Other languages do not perform as
good when
all these three "forces" are evaluated together (besides, maybe,
SmallTalk, but
this is another issue).
</p>
<p>
Java is trendy, that's true, but we all know that Java is a
well-designed object
oriented language. May not be the best, I grant that, but it's the
only one that came
to please all those people I listed above.
</p>
<p>
Following this direction, and feeling the lack of professional Java
server
solutions on many fields, the Java Apache Project was created to fill
this gap
using the power of open source. We don't want to compete with Apache
or with
any other server implementation. We are betting on Java for the
server side, but
we will never "rewrite" some server implementation in Java, unless
this can
lead to significant improvements and doesn't go against other open
source
projects.
</p>
<p>
The final goal is a family of 100% pure server solutions for the Java
Virtual
Machine.
</p>
<p>
Since server applications share lots of logic/code between them, it
is obvious
that a common server framework, along with design rules and abstract
implementations, would allow faster time-to-market, easier code
management,
parallel development, bug fix reflection on all projects and tight
integration
between the different server solutions.
</p>
<p>
I do believe that the time taken to design and develop such a
framework will be
"invested" by this project and its developers. The creation of this
project doesn't
mean other projects can't continue to evolve: the final goal is to
integrate
existing server solutions (JServ) into the framework but this is not
a short term
goal so this doesn't influence it's evolution/time-to-market for
future
releases/features.
</p>
</s1>
<s1 title="Request For Vote">
<p>
For the reasons above, I propose the creation of a new project to
handle the
design of a the Java Apache Server Framework that will be the
foundation on
which all server projects hosted by the Java Apache Project will be
based on.
</p>
<p>
This project goals are:
</p>
<ol>
<li>
Design and documentation of the Java Apache Server Framework.
</li>
<li>
Creation and implementation of this framework (interfaces, abstract
classes,
and shared modules).
</li>
<li>
Centralized management of the evolution/fixing/patching of both the
shared
code and the framework design.
</li>
</ol>
</s1>
<s1 title="What the Java Apache Server Framework Is">
<p>
It's a design methodology that allows design reuse as well as code
reuse between
different server projects. These projects gain the advantage of
software reuse
and the simplicity of developing/managing only the different logic.
</p>
<p>
This framework will be based on Java technology and would allow:
</p>
<ol>
<li>
Partition of shared logic context into polymorphic modules that are
used
through their public interfaces and not through their actual
implementation (Log
systems, Object stores, Virtual File Systems, Configuration
repository,
Concurrency Strategies, etc..)
</li>
<li>
Creation of a common lifecycle for server operations (the Service
interface)
</li>
<li>
Creation of a ServiceManager for service management (maybe both
internal
or external the JVM: native wrapping and control via JNI would allow
better fault tolerance for the JVM through process separation)
</li>
<li>
Shared resources can be either centralized or duplicated for each
service,
allowing the use of a single JVM for multiple servers and common
logic
sharing (i.e. common thread pools, log systems and configuration
repositories...)
</li>
<li>
A central access point for configuration (via HTTP, SMTP, voice,
RMI,
SNMP, IIOP, depending on the services implemented)
</li>
<li>
Reduced effort in service development since they become plugins for
this
framework and reuse big parts of the code base. The design and
behavior is
also documented and shared between different services.
</li>
</ol>
</s1>
</body>
<footer>
<legal>
Copyright (c) 1997-2001 The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:49 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/history/need-for-avalon.xml
Index: need-for-avalon.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>History</title>
<subtitle>Do we really need this?</subtitle>
<authors>
<person id="SM" name="Stefano Mazzocchi" email="[EMAIL PROTECTED]"/>
</authors>
<abstract>
In this document, I introduce my vision for the Java Apache
Server Framework project. I explain why I believe that
open-source projects should invest more time in software
engineering and why this may be worth even if very successful
and high quality software projects.
</abstract>
</header>
<body>
<s1 title="Hardware vs. Software">
<p>
One thing that always puzzled me is the different quality meters used
on hardware and software by users: little flaws in software systems
are accepted as inevitable, while hardware flaws (even small ones) may
even create market panic if discovered. It's hard to tell why this is
so, but today's software quality standards are becoming more and more
selective, especially when monopolies are broken and users are able to
judge the differences between products and solutions.
</p>
</s1>
<s1 title="Open Source as Quality Management">
<p>
The open source development model has emerged as a powerful way to
control and improve software quality. The most important assumption,
in this case, is the fact that debugging and code testing are
parallelizable tasks. For this reason, different individuals are able
to track down problems right into the source code, independently from
one another. In open source projects, compared to closed source ones,
the complexity of the software system grows slower than the ability to
debug it, due to this parallelizable effort.
</p>
<p>
Open source processes are auto-organizative: when a seed of ideas
and goals is thrown in the right place at the right time, it catalyzes
the development process. Usually, when this happens, the user base
expands, the complexity of the software system grows to meet the
requirements of this bigger user base, incorporating new ideas,
solutions and code and creating a positive feedback that keeps the
process going.
</p>
</s1>
<s1 title="Software Engineering and Open Source">
<p>
Software engineering doesn't fit well into an auto-organized system
driven by user requirements. Still, I believe that careful software
design may allow the development process to <em>know</em> the ability
of its developers and to provide them guidelines to reduce the work
and to increase parallel capabilities. Of course, due to the extreme
flexibility that open source projects show, software engineers should
carefully design the system to match this flexibility and to avoid any
restriction that may create friction with users and developers.
</p>
<p>
It is evident how the use of modern object oriented programming
languages like Java helps the development and reduces the debugging
efforts because most error prone tasks are handled automatically by
the language itself. Still, the most important object oriented
solutions (such as Interfaces and abstract classes) are very much
unused in auto-organized project, where the work is usually done with
the smallest possible effort to get something working.
</p>
<p>
The incredible improvement in time-to-market offered by these
programming languages that reduce the debugging process to logical
bugs rather than developer's programming mistakes, is a great feature
and it's well appreciated, but it may lead, on the longer term, to
code maintenance problems.
</p>
<p>
In all software systems, the maintenance costs greatly exceed the
first development ones. In open source software systems, the cost is
measured in terms of <em>time</em> and <em>energy</em> spent by
developers to meet the new requirements and to expand the complexity
of the software system. It has been shown (in the Apache JServ
project) that the wrong use of object oriented features may lead to
project stall and create friction between developers and users about
the need for <em>revolutions</em> instead of <em>evolutions</em>
driven by the need of a complete code redesign.
</p>
<p>
The rules "if it works it's good enough" and "if it
works don't change it" may fit well in those programming contexts
where developers need to design the code on their own to make it work.
In object oriented systems, more than ever, working code is not
automatically good code.
</p>
</s1>
<s1 title="Frameworks and Patterns">
<p>
The solution I propose is the introduction of coding guidelines to
place new requirements to meet the "working" state: by
introducing the use of software frameworks and design patterns, we are
able to <em>shape</em> the work of developers without restricting
their creativity. While object oriented languages don't pose such
limitations or guidelines, the introduction of carefully designed
engineering rules, contracts and patterns would create some additional
requirements to the development process, but will allow better code
maintenance, a more coherent parallel development process and, in the
longer run, easier maintenance.
</p>
</s1>
<s1 title="Conclusions">
<p>
The use of development guidelines and frameworks is proposed as a way
to reduce internal tensions that produce revolutionary development
processes rather than evolutionary ones. Even if such ability is yet
to be demonstrated, it has been shown how object oriented languages
require different approaches and more careful design stages to be
successful in the long run.
</p>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:49 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/history/what-is-a-server.xml
Index: what-is-a-server.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>History</title>
<subtitle>How to write servers using Avalon</subtitle>
<authors>
<person id="PF" name="Pierpaolo Fumagalli" email="[EMAIL PROTECTED]"/>
</authors>
<notice>
Avalon documentation is under construction. Everything you
can find outside this page is to be considered obsolete.
</notice>
<abstract>
In this document I try to explain how a server could be developed
using the benefits offered by the Java Apache Server Framework
(Avalon) and I introduce the reader to the concept of what a
<code>Block</code> is.
</abstract>
</header>
<body>
<s1 title="Introduction: Servers and Services?">
<p>
It's somehow difficult to give a proper definition of
"server",
due to the confusion created in the time so far by the different
meanings
that term had, facing the different evolution of the technologies.
</p>
<p>
The term "server" is commonly used with at least three
different
meanings:
</p>
<ul>
<li>
<strong>"Server" as computer:</strong> With this meaning
the
server term is intended to be the computer sharing resources.
<br/>
<em>
Ex. Our corporate "server" is a double Pentium II
running at 450 MHz with 12 GB of SCSI hard disk running Linux.
</em>
</li>
<li>
<strong>"Server" as a program:</strong> With this meaning
the
server term is intended to be the application that enables the
resource sharing, not caring about the network protocols it
implements.
<br/>
<em>
Ex. Our Mail server is FlosieTek FTGate release 2.1 which
implements the SMTP and POP3 protocols.
</em>
</li>
<li>
<strong>"Server" as a protocol handler:</strong> With
this meaning
the server term is intended to be the application that enables
the access to shared resources via a specified protocol.
<br/>
<em>
Ex. Our HTTP server is Apache 1.3.4.
</em>
</li>
</ul>
<p>
While we can clearly see the difference between the first definition
of
"server" (computer) and the other two (applications), it's
hard
to see the difference between the second definition
("server" as
a multi-protocol handler) and the third ("server" as a
single
protocol handler).
</p>
<p>
Since it's crucial for all developers involved in the Avalon project
to
share the same common idea of "server", I would like to
define
a server as a <strong>protocol handler</strong>. We would, then, have
HTTP servers,
SMTP servers or POP3 servers, but we cannot use the term MAIL server.
</p>
<p>
What we called the mail server is in fact the union of two (or more)
different "server"s (in our example the union of a SMTP and
a
POP3 server).
</p>
<p>
We can clearly see, anyway, that a POP3 and an SMTP server will have
to
share most resources and code to build up a complete mailing system,
like,
for example, a central repository where messages could be stored. We
would
then define the union of the SMTP server, the POP3 server and the
central
messages repository (we could call it <strong>Mail Engine</strong>)
as a Mail
"service". To clarify things a little bit, maybe a picture
would
help:
</p>
<figure src="images/server-01.gif" alt="Server 1"/>
</s1>
<s1 title="Dividing the code">
<p>
We can clearly see, however, how this approach to the problem brings
to
a monolithic implementation of the code, not allowing, or making
really
difficult, for other persons to add features, for example,
integrating an
IMAP server within our Mail Service.
</p>
<p>
In fact, if we don't clearly separate the code (and a good developer
should always keep in mind his server expansion) adding a feature
like an
IMAP server into our service could become hell, and, most developers
will
try to find other solutions already in the market rather than using
and
improving what we have done.
</p>
<p>
The solution would be to have a sort of "in-core" modularization of
our
server.... To be continued...
</p>
<figure src="images/server-02.gif" alt="Server 2"/>
<figure src="images/server-03.gif" alt="Server 3"/>
</s1>
<s1 title="The concept of a Block">
<figure src="images/server-04.gif" alt="Server 4"/>
</s1>
<s1 title="The Avalon Framework">
<fixme author="PF">We need some info in here.</fixme>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:49 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/history/images/server-01.gif
<<Binary file>>
1.1 jakarta-avalon/src/xdocs/history/images/server-02.gif
<<Binary file>>
1.1 jakarta-avalon/src/xdocs/history/images/server-03.gif
<<Binary file>>
1.1 jakarta-avalon/src/xdocs/history/images/server-04.gif
<<Binary file>>
1.1 jakarta-avalon/src/xdocs/images/add.jpg
<<Binary file>>
1.1 jakarta-avalon/src/xdocs/images/remove.jpg
<<Binary file>>
1.1 jakarta-avalon/src/xdocs/images/update.jpg
<<Binary file>>
1.1
jakarta-avalon/src/xdocs/phoenix/assembly-xml-specification.xml
Index: assembly-xml-specification.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Server Assemblers Guide</title>
<subtitle>Specification of assembly.xml </subtitle>
<authors>
<person id="PD" name="Peter Donald" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Introduction">
<p>
The purpose of the <code>assembly.xml</code> file is to define how
the Server
Application is assembled from it's component Blocks. This requires
naming each
block, specifying the implementation class for each block and wiring
together
blocks. The wiring is done via provides elements. Each provide
element maps a
block instance to a role of a dependency specified in the BlockInfo
file. See
below for a sample assembly.xml file.
</p>
<p>
At the current time configuration data is also specified in the
assembly.xml
file. The format of the configuration data is block specifc and you
should
refer to the Blocks documentation to discover the format. In the
future this
configuration data will be removed.
</p>
</s1>
<s1 title="Sample assembly.xml file">
<source><![CDATA[
<?xml version="1.0"?>
<avalon>
<block name="myAuthorizer"
class="com.biz.cornerstone.blocks.MyAuthorizer">
<configuration>
...configuration data here...
</configuration>
</block>
<block name="myBlock" class="com.biz.cornerstone.blocks.MyBlock">
<provide name="myAuthorizer"
role="com.biz.cornerstone.services.Authorizer"/>
</block>
</avalon>]]>
</source>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:50 $
</legal>
</footer>
</document>
1.1
jakarta-avalon/src/xdocs/phoenix/blockinfo-specification.xml
Index: blockinfo-specification.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Block Developers Guide</title>
<subtitle>The BlockInfo Specification</subtitle>
<version>3.0</version>
<authors>
<person id="PD" name="Peter Donald" email="[EMAIL PROTECTED]"/>
</authors>
<abstract>
Specifies the format of BlockInfo files and the reasons for particular
aspects.
</abstract>
</header>
<body>
<s1 title="Block Metadata">
<p>
The meta-data about each block is stored in a BlockInfo file. The
meta-data
includes details on what version the block is, what
<code>Service</code>s
it depends upon and which <code>Service</code>s it can offer to other
Blocks.
The meta-data also has links to the location of documentation,
license details,
authors and icons.
</p>
<p>
The BlockInfo file has the same name as the Block except with the
extention
<code>.xinfo</code>. Thus if you were looking up the meta info for a
block named
<code>com.biz.cornerstone.blocks.MyBlock</code> you would look up the
resource
<code>com/biz/cornerstone/blocks/MyBlock.xinfo</code> in the same bar
file that
the block was packaged in. The BlockInfo file is a simple XML format.
An
example of such a file follows.
</p>
<source>
<![CDATA[
<?xml version="1.0"?>
<blockinfo>
<meta>
<version>1.2.3</version>
<icon>resources/myBlock-16x16.jpg</icon>
<large-icon>resources/myBlock-32x32.jgp</large-icon>
<documentation>http://www.biz.com/docs/blocks/myBlock.html</documentation>
<license>http://www.biz.com/docs/blocks/myBlock-license.html</license>
<update>http://www.biz.com/docs/blocks/myBlock-latest.bar</update>
<contributors>
<author name="Silent Bob" email="[EMAIL PROTECTED]"/>
</contributors>
</meta>
<services>
<service name="com.biz.cornerstone.services.MyService" version="2.1.3" />
</services>
<dependencies>
<dependency>
<role>com.biz.cornerstone.services.Authorizer</role>
<service name="com.biz.cornerstone.service.Authorizer" version="1.0"/>
</dependency>
</dependencies>
</blockinfo>
]]>
</source>
<!-- Things to consider adding to the blockinfo descriptor
<homepage URL="[URLtoprojecthomepage]"/>
<doc type="html" URL="[URLtohtmldocs]"/>
<doc type="pdf" URL="[URLtopdfdocs]"/>
<updates type="jar" URL="[URLtojar]"/>
<updates type="rpm" URL="[URLtorpm]"/>
<licence URL="[URLtolicence]"/>
-->
<p>
You will notice that the information in the BlockInfo file is
separated into
three main sections; <code>meta</code>, <code>services</code> and
<code>dependencies</code>.
</p>
<s2 title="BlockInfo 'meta' Section">
<p>The meta section should be largely self explanatory. The icons are
used to
support future assembly of blocks in a GUI environment. As of the
time of
writing Atlantis currently does not require specification of this
section.</p>
</s2>
<s2 title="BlockInfo 'services' Section">
<p>The services section documents the services that this block can
offer other
Blocks. The service instances indicate an interface and a version.
The interface
MUST extend <code>org.apache.phoenix.Service</code>. This section is
optional
and a Block can choose to not offer any services.</p>
</s2>
<s2 title="BlockInfo 'dependencies' Section">
<p>The services section documents the services that this block
requires to operate.
Required services are placed in the Blocks ComponentManager under the
name
specified by the <code>role</code> element of service. As is
documented in the
<link href="components.html">components</link> section, the concept
of Role is more
than just a behavioural contract. A <code>Service</code> is a
behavioural contract
and thus the necessity to support the role element. In most cases
however the role
element and the name attribute of the service will be identical.</p>
</s2>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:51 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/phoenix/creating-a-block.xml
Index: creating-a-block.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Block Developers Guide</title>
<subtitle>Creating a Block</subtitle>
<authors>
<person id="PD" name="Peter Donald" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Creating your first Block">
<p>
This document will describe the process for creating your first
block. There
are essentially three steps that must be completed before your block
is ready
for assembling.
</p>
<ol>
<li>Write the Block component.</li>
<li>Write the BlockInfo meta-info description file.</li>
<li>Package the component and related resources into a bar file.</li>
</ol>
</s1>
<s1 title="Writing the Block component">
<p>
Writing the Block is the main task you will be called to do. It
follows all
the rules of writing a standard Avalon component. Block writers must
also
extend the <code>org.apache.phoenix.Block</code> interface.
</p>
<p>
If a block implements the Composer interface it will be passed an
instance
of <code>org.apache.phoenix.BlockContext</code> which is an extended
version
of <code>org.apache.avalon.Context</code>. Other than this minor
change the
Block's container (the Phoenix Kernel) supports all the Avalon
lifecycle
methods or will in the near future (at the moment suspend/resume is
not yet
supported).
</p>
<p>
The block can implement an instance of
<code>org.apache.phoenix.Service</code>
if it wishes to export a service to external blocks. It is also
possible to
aquire services from other blocks in the <code>compose()</code>
method.
</p>
</s1>
<s1 title="Write the BlockInfo">
<p>
You must create this file to indicate which services this Block
depends upon
and those services which it offers. It is more fully documented in
the
<link href="blockinfo-specification.html">BlockInfo
Specification</link> document.
</p>
</s1>
<s1 title="Create the bar package">
<p>
The final step is packaging up the implementation files, BlockInfos
and other
resources into a bar file. The bar file is a jar file with extra
manifest entries.
Specifically for every Block that is included in the archive a new
manifest attribute
must be added, namely "Avalon-Block: true". An example
manifest file is
displayed below.
</p>
<source>
Manifest-Version: 1.0
Created-By: Apache Avalon Project
Name: com/biz/cornerstone/blocks/MyBlock.class
Avalon-Block: true
</source>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:51 $
</legal>
</footer>
</document>
1.1
jakarta-avalon/src/xdocs/phoenix/creating-a-server-application.xml
Index: creating-a-server-application.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Server Assemblers Guide</title>
<subtitle>Creating a Server Application</subtitle>
<authors>
<person id="PD" name="Peter Donald" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Creating a Server Application">
<p>
This document will describe the process for assembling your first
Server
Application. There is a number of steps in creating a Server
Application.
These are;
</p>
<ol>
<li>Select the blocks you wish to assemble.</li>
<li>Write the assembly.xml file.</li>
<li>Write the server.xml file.</li>
<li>Package the component and related resources into a sar file.</li>
</ol>
</s1>
<s1 title="Select the Blocks to Assemble">
<p>
As a assembler it is your responsibility to select the particular
Blocks
required to build your application. You may aquire the Blocks from a
number
of sources depending on your resources. You may use the core Blocks
supplied
with Phoenix, contract someone to build the component or download the
Block
from an online repository.
</p>
</s1>
<s1 title="Write the assembly.xml file">
<p>
The next stage is to write the assembly.xml file. The assembly.xml
specifies
the instances of Blocks that are part of the Server Application. Each
Block has a name. Each block may also have dependencies that need to
be
satisfied and this can be done via the 'provide' sub-elements. The
provide element maps block instances from the Server Application
namespace
to the Block role namespace specified in BlockInfo files. At the
present
time the configuration data for blocks is also stored in the
assembly.xml file
but this will change in the future. For more detail on the format of
assembly.xml see the <link href="assembly-xml-specification.html">
specification</link>.
</p>
</s1>
<s1 title="Write the server.xml file">
<p>
The next stage is to write the server.xml file. The server.xml is
used to
configure the code-based security policy, log management and thread
pooling.
For more detail on the format of server.xml see the
<link href="server-xml-specification.html">specification</link>.
</p>
</s1>
<s1 title="Create the sar file">
<p>
The sar file format is the standard distribution format of Phoenix
Server
Applications. It is a standard Jar file with a specific directory
layout.
The server.xml and assembly.xml file must be stored in
<code>conf/</code>
of the archive. All bar (Block ARchive) files must be stored in the
<code>blocks/</code> subdirectory while all supporting jar and zip
files
must be stored in the <code>lib/</code> subdirectory.
</p>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:51 $
</legal>
</footer>
</document>
1.1
jakarta-avalon/src/xdocs/phoenix/server-xml-specification.xml
Index: server-xml-specification.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Server Assemblers Guide</title>
<subtitle>Specification of server.xml</subtitle>
<authors>
<person id="PD" name="Peter Donald" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Introduction">
<p>
The purpose of the <code>server.xml</code> file is to configure
Server
Application wide settings. Currently this means being able to set the
security policy, configure logging and setup thread pools. An sample
<code>server.xml</code> follows.
</p>
</s1>
<s1 title="Sample server.xml file">
<source><![CDATA[
<?xml version="1.0"?>
<server>
<logs>
<category name="" target="default" priority="DEBUG" />
<category name="myAuthorizer" target="myAuthorizer-target"
priority="DEBUG" />
<log-target name="default" location="/logs/default.log" />
<log-target name="myAuthorizer-target" location="/logs/authorizer.log"
/>
</logs>
<threads>
<thread-group>
<name>default</name>
<priority>5</priority>
<is-daemon>false</is-daemon>
<min-threads>20</min-threads>
<min-spare-threads>20</min-spare-threads>
<max-threads>40</max-threads>
</thread-group>
</threads>
<policy>
<keystore name="foo-keystore"
location="file:${app.home}${/}conf${/}keystore"
type="JKS" />
<grant signed-by="Bob"
code-base="file:${app.home}${/}blocks${/}*"
key-store="foo-keystore" >
<permission class="java.io.FilePermission" target="${/}tmp${/}*"
action="read,write" />
</grant>
</policy>
</server>]]>
</source>
<p>
The format of the policy section should be self evident if the
assembler
has experienve with standard policy files. It should be noted that if
no
policy section is given then the Server Application runs at full
permissions.
The evaluation of properties occurs in a similar manner to standard
policy file property expansion. There are a number of extra
properties that
will be evaluated. These include; <code>app.home</code>,
<code>app.name</code>,
<code>app.blocks</code>, <code>app.lib</code> and
<code>app.conf</code>.
</p>
<p>
The format of the threads section should be largely self explanatory.
The only
complication is that there must be a thread group declared with name
of "default".
It also should have a max-threads larger than the number of Blocks
that implement
Runnable. Otherwise the initialisation sequence could hang
indefinetly.
</p>
<p>
The logs section can currently have two types of elements;
<em>log-target</em>s
which represent destinations for logging and <em>category</em>s.
There must be a
log-target with the name "default". Categories are hierarchial in
nature, have a
priority and are associated with one or more log-targets. See the
logging
documentation for a further description of this section.
</p>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:51 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/src/xdocs/phoenix/what-is-a-block.xml
Index: what-is-a-block.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Block Developers Guide</title>
<subtitle>What is a Block?</subtitle>
<authors>
<person id="FB" name="Federico Barbieri" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="Introduction">
<p>In Avalon, there are three component layers:</p>
<ul>
<li>Blocks</li>
<li>Components</li>
<li>Classes</li>
</ul>
<p>
They represent ever narrowing views of a component based architecture.
The best analogy is that of hardware. In the PC world, a Block would
be like a PCI card, a Motherboard, a Case, or a Hard Drive. A
Component
would be like the chips on the cards. And classes would be like the
individual transistors on the chip. Granted, the actual economies
of scale in this analogy don't hold to software (a component will
not have millions of classes).
</p>
</s1>
<s1 title="What is a Block?">
<p>
A Block is a Component on a larger scale. It is usually the
implementation of a Service. Examples of Blocks are
"Persistent Object Store", "Connection Pools", "XML Database",
"Authenticator" and so on.
</p>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:51 $
</legal>
</footer>
</document>
1.1
jakarta-avalon/src/xdocs/phoenix/what-is-a-server-application.xml
Index: what-is-a-server-application.xml
===================================================================
<?xml version="1.0"?>
<!DOCTYPE document SYSTEM "../dtd/document-v10.dtd">
<document>
<header>
<title>Server Assemblers Guide</title>
<subtitle>What is a Server Application?</subtitle>
<authors>
<person id="PD" name="Peter Donald" email="[EMAIL PROTECTED]"/>
<person id="BL" name="Berin Loritsch" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<s1 title="What is a Server Application?">
<p>
In Phoenix, a Server Application is a set of Blocks that act in
concert
to provide a unified user service. Example Server Applications
include a Mail
Server, File Server, Web Server etc. The Server Application is a high
level
component that contains a set of Block components.
</p>
<p>
A Server Application requires a number of components other than
Blocks to
be complete. A Server Application requires configuration files to
define
Server Application wide settings (threading, security, logging), to
define
how blocks are wired together, and to define configuration data for
the
Block instances. A Block can also require other resources that are
application specific.
</p>
</s1>
</body>
<footer>
<legal>
Copyright (c) @year@ The Jakarta Apache Project All rights reserved.
$Revision: 1.1 $ $Date: 2001/02/23 10:47:51 $
</legal>
</footer>
</document>
1.1 jakarta-avalon/tools/bin/ant
Index: ant
===================================================================
#! /bin/sh
if [ -f $HOME/.antrc ] ; then
. $HOME/.antrc
fi
# Cygwin support. $cygwin _must_ be set to either true or false.
case "`uname`" in
CYGWIN*) cygwin=true ;;
*) cygwin=false ;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin; then
[ -n "$ANT_HOME" ] &&
ANT_HOME=`cygpath --unix "$ANT_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
if [ "$ANT_HOME" = "" ] ; then
# try to find ANT
if [ -d /opt/ant ] ; then
ANT_HOME=/opt/ant
fi
if [ -d ${HOME}/opt/ant ] ; then
ANT_HOME=${HOME}/opt/ant
fi
## resolve links - $0 may be a link to ant's home
PRG=$0
progname=`basename $0`
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '.*/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname $PRG`/$link"
fi
done
ANT_HOME=`dirname "$PRG"`/..
fi
if [ "$JAVA_HOME" != "" ] ; then
if [ "$JAVACMD" = "" ] ; then
JAVACMD=$JAVA_HOME/bin/java
fi
else
if [ "$JAVACMD" = "" ] ; then
JAVACMD=java
fi
fi
# add in the dependency .jar files
DIRLIBS=${ANT_HOME}/lib/*.jar
for i in ${DIRLIBS}
do
# if the directory is empty, then it will return the input string
# this is stupid, so case for it
if [ "$i" != "${DIRLIBS}" ] ; then
LOCALCLASSPATH=$LOCALCLASSPATH:"$i"
fi
done
if [ "$CLASSPATH" != "" ] ; then
LOCALCLASSPATH=$CLASSPATH:$LOCALCLASSPATH
fi
if [ "$JAVA_HOME" != "" ] ; then
if test -f $JAVA_HOME/lib/tools.jar ; then
LOCALCLASSPATH=$LOCALCLASSPATH:$JAVA_HOME/lib/tools.jar
fi
if test -f $JAVA_HOME/lib/classes.zip ; then
LOCALCLASSPATH=$LOCALCLASSPATH:$JAVA_HOME/lib/classes.zip
fi
else
echo "Warning: JAVA_HOME environment variable is not set."
echo " If build fails because sun.* classes could not be found"
echo " you will need to set the JAVA_HOME environment variable"
echo " to the installation directory of java."
fi
# supply JIKESPATH to Ant as jikes.class.path
if [ "$JIKESPATH" != "" ] ; then
if [ "$ANT_OPTS" != "" ] ; then
ANT_OPTS="$ANT_OPTS -Djikes.class.path=$JIKESPATH"
else
ANT_OPTS=-Djikes.class.path=$JIKESPATH
fi
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
ANT_HOME=`cygpath --path --windows "$ANT_HOME"`
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
LOCALCLASSPATH=`cygpath --path --windows "$LOCALCLASSPATH"`
fi
$JAVACMD -classpath "$LOCALCLASSPATH" -Dant.home="${ANT_HOME}" $ANT_OPTS
org.apache.tools.ant.Main "$@"
1.1 jakarta-avalon/tools/bin/ant.bat
Index: ant.bat
===================================================================
@echo off
if exist "%HOME%\antrc_pre.bat" call "%HOME%\antrc_pre.bat"
if not "%OS%"=="Windows_NT" goto win9xStart
:winNTStart
@setlocal
rem %~dp0 is name of current script under NT
set DEFAULT_ANT_HOME=%~dp0
rem : operator works similar to make : operator
set DEFAULT_ANT_HOME=%DEFAULT_ANT_HOME:\bin\=%
if %ANT_HOME%a==a set ANT_HOME=%DEFAULT_ANT_HOME%
set DEFAULT_ANT_HOME=
rem On NT/2K grab all arguments at once
set ANT_CMD_LINE_ARGS=%*
goto doneStart
:win9xStart
rem Slurp the command line arguments. This loop allows for an unlimited
number of
rem agruments (up to the command line limit, anyway).
set ANT_CMD_LINE_ARGS=
:setupArgs
if %1a==a goto doneStart
set ANT_CMD_LINE_ARGS=%ANT_CMD_LINE_ARGS% %1
shift
goto setupArgs
:doneStart
rem This label provides a place for the argument list loop to break out
rem and for NT handling to skip to.
rem find ANT_HOME
if not "%ANT_HOME%"=="" goto checkJava
rem check for ant in Program Files on system drive
if not exist "%SystemDrive%\Program Files\ant" goto checkSystemDrive
set ANT_HOME=%SystemDrive%\Program Files\ant
goto checkJava
:checkSystemDrive
rem check for ant in root directory of system drive
if not exist "%SystemDrive%\ant" goto noAntHome
set ANT_HOME=%SystemDrive%\ant
goto checkJava
:noAntHome
echo ANT_HOME is not set and ant could not be located. Please set ANT_HOME.
goto end
:checkJava
set _JAVACMD=%JAVACMD%
set LOCALCLASSPATH="%CLASSPATH%"
for %%i in ("%ANT_HOME%\lib\*.jar") do call "%ANT_HOME%\bin\lcp.bat" "%%i"
if "%JAVA_HOME%" == "" goto noJavaHome
if "%_JAVACMD%" == "" set _JAVACMD=%JAVA_HOME%\bin\java
if exist "%JAVA_HOME%\lib\tools.jar" call "%ANT_HOME%\bin\lcp.bat"
"%JAVA_HOME%\lib\tools.jar"
if exist "%JAVA_HOME%\lib\classes.zip" call "%ANT_HOME%\bin\lcp.bat"
"%JAVA_HOME%\lib\classes.zip"
goto checkJikes
:noJavaHome
if "%_JAVACMD%" == "" set _JAVACMD=java
echo.
echo Warning: JAVA_HOME environment variable is not set.
echo If build fails because sun.* classes could not be found
echo you will need to set the JAVA_HOME environment variable
echo to the installation directory of java.
echo.
:checkJikes
if not "%JIKESPATH%" == "" goto runAntWithJikes
:runAnt
%_JAVACMD% -classpath %LOCALCLASSPATH% -Dant.home="%ANT_HOME%" %ANT_OPTS%
org.apache.tools.ant.Main %ANT_CMD_LINE_ARGS%
goto end
:runAntWithJikes
%_JAVACMD% -classpath %LOCALCLASSPATH% -Dant.home="%ANT_HOME%"
-Djikes.class.path=%JIKESPATH% %ANT_OPTS% org.apache.tools.ant.Main
%ANT_CMD_LINE_ARGS%
:end
set LOCALCLASSPATH=
set ANT_CMD_LINE_ARGS=
if not "%OS%"=="Windows_NT" goto mainEnd
:winNTend
@endlocal
:mainEnd
if exist "%HOME%\antrc_post.bat" call "%HOME%\antrc_post.bat"
1.1 jakarta-avalon/tools/bin/antRun
Index: antRun
===================================================================
#! /bin/sh
# Args: DIR command
cd "$1"
CMD="$2"
shift
shift
exec $CMD "$@"
1.1 jakarta-avalon/tools/bin/antRun.bat
Index: antRun.bat
===================================================================
@echo off
cd %1
set ANT_RUN_CMD=%2
shift
shift
set PARAMS=
:loop
if ""%1 == "" goto runCommand
set PARAMS=%PARAMS% %1
shift
goto loop
:runCommand
rem echo %ANT_RUN_CMD% %PARAMS%
%ANT_RUN_CMD% %PARAMS%
1.1 jakarta-avalon/tools/bin/lcp.bat
Index: lcp.bat
===================================================================
set LOCALCLASSPATH=%1;%LOCALCLASSPATH%
1.1 jakarta-avalon/tools/lib/ant.jar
<<Binary file>>
1.1 jakarta-avalon/tools/lib/optional.jar
<<Binary file>>
1.1 jakarta-avalon/tools/lib/stylebook-1.0-b2.jar
<<Binary file>>
1.1 jakarta-avalon/tools/lib/testlet.jar
<<Binary file>>
1.1 jakarta-avalon/tools/lib/xalan_1_2_D02.jar
<<Binary file>>