leosimons 2003/01/27 08:55:43
Added: fortress/src/java/org/apache/avalon/fortress Container.java
ContainerConstants.java ContainerManager.java
ContainerManagerConstants.java
InitializationException.java RoleEntry.java
RoleManager.java package.html
fortress/src/java/org/apache/avalon/fortress/impl
AbstractContainer.java ComponentHandlerEntry.java
ComponentHandlerMetaData.java DefaultContainer.java
DefaultContainerManager.java
LifecycleExtensionManager.java package.html
fortress/src/java/org/apache/avalon/fortress/impl/handler
AbstractComponentHandler.java ComponentFactory.java
ComponentHandler.java FactoryComponentHandler.java
LEAwareComponentHandler.java
PassThroughInvocationHandler.java
PerThreadComponentHandler.java
PoolableComponentHandler.java
PrepareHandlerCommand.java ProxyHelper.java
ProxyObjectFactory.java
ThreadSafeComponentHandler.java package.html
fortress/src/java/org/apache/avalon/fortress/impl/lookup
FortressServiceManager.java
FortressServiceSelector.java package.html
fortress/src/java/org/apache/avalon/fortress/impl/role
AbstractRoleManager.java
ConfigurableRoleManager.java
FortressRoleManager.java package.html
fortress/src/java/org/apache/avalon/fortress/util
CachedArrayList.java CompositeException.java
ContextBuilder.java ContextManager.java
ContextManagerConstants.java FortressConfig.java
OverridableContext.java package.html
Log:
Wholesale refactoring. Moved classes to org.apache.avalon.fortress, changed
exception handling, removed inner class, documentation changes, removed some
remnants from ECM copy-pasting. Seperated interfaces from implementation.
Consider this a proposal. The excalibur.fortress tree can be removed if no-one
objects to these changes.
Revision Changes Path
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/Container.java
Index: Container.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress;
import org.apache.avalon.framework.service.ServiceException;
/**
* The Container is an interface used to mark the Containers in your system.
* It is used to functionally identify Containers. It's primary use is to
* assist Container developers to obtain the desired object from the Context.
* All communication from the ContainerManager to the Container is through the
* Context object.
*
* @author <a href="mailto:[email protected]">The Avalon Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:40 $
* @see ContainerConstants for the contract surrounding the Container context
* @see <a
href="http://jakarta.apache.org/avalon/framework/guide-cop-in-avalon.html">COP
In Avalon</a>
*/
public interface Container
{
/**
* This is the method that the ContainerComponentManager and Selector use
* to gain access to the ComponentHandlers and ComponentSelectors. The
* actual access of the ComponentHandler is delegated to the Container.
*
* @param role The role we intend to access a Component for.
* @param hint The hint that we use as a qualifier
* (note: if null, the default implementation is returned).
*
* @return Object a reference to the ComponentHandler or
* ComponentSelector for the role/hint combo.
*/
Object get( String key, Object hint ) throws ServiceException;
/**
* This is the method that the ContainerComponentManager and Selector use
* to gain access to the ComponentHandlers and ComponentSelectors. The
* actual access of the ComponentHandler is delegated to the Container.
*
* @param role The role we intend to access a Component for.
* @param hint The hint that we use as a qualifier
* (note: if null, the default implementation is returned).
*
* @return true if a reference to the role exists.
*/
boolean has( String key, Object hint );
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/ContainerConstants.java
Index: ContainerConstants.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress;
/**
* Provides constants used to access the Context object for containers.
* A impl should allow these values to propagate down to child
* containers, so that they may create child containers in turn.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:40 $
*/
public interface ContainerConstants
{
/**
* Context Directory: The location of the context.
*/
String CONTEXT_DIRECTORY = "context-root";
/**
* Work Directory: The location the impl can store temperorary files.
*/
String WORK_DIRECTORY = "impl.workDir";
/**
* Threads per CPU: Information about the hardware the impl is running on.
*/
String THREADS_CPU = "impl.threadsPerCPU";
/**
* Thread timeout: Information about the hardware the impl is running on.
*/
String THREAD_TIMEOUT = "impl.threadTimeout";
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/ContainerManager.java
Index: ContainerManager.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress;
/**
* The ContainerManager is a single point of contact to manage your Container
* resources. It takes care of creating the other managers that a Container
* needs to use, as well as initializing the Container. It is designed to be
* directly instantiated by whatever class needs to initialize your system.
*
* <p>
* The ContainerManager provides some constants used in the initial
* <code>Parameters</code> passed into the ContainerManager. The
* ContainerManager uses these values to create all the pieces necessary
* for the Container. Below is a table that describes what those options
* are.
* </p>
*
* <p>You can think of a ContainerManager is a pocket universe for a impl and
its
* components.</p>
*
* <p><b>Case 1: Use by a servlet or other "root" entity</b></p>
*
* <pre>
* <code>
* FortressConfig config = new FortressConfig();
* config.setContainerClass(
Thread.currentThread().getContextClassLoader().loadClass(
"org.apache.avalon.fortress.test.TestContainer" ) );
* config.setContextDirectory( "./" );
* config.setWorkDirectory( "./" );
* config.setContainerConfiguration(
"resource://org.apache.avalon.fortress/test/ContainerProfile.xconf" );
* config.setLoggerManagerConfiguration(
"resource://org.apache.avalon.fortress/test/ContainerProfile.xlog" );
*
* ContainerManager cm = new DefaultContainerManager( config.getContext()
);
* ContainerUtil.initialize( cm );
* </code>
* </pre>
*
* Then, for example, wait for a request and pass it on to the impl:
*
* <pre>
* <code>
* TestContainer impl = (TestContainer) cm.getContainer();
* impl.handleRequest( ... );
* </code>
* </pre>
*
* When done, dispose of the managers.
*
* <pre>
* <code>
* ContainerUtil.dispose( containerManager );
* ContainerUtil.dispose( contextManager );
* </code>
* </pre>
*
* @author <a href="mailto:[email protected]">The Avalon Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:40 $
* @see ContainerManagerConstants for the contract surrounding the
ContainerManager context
*/
public interface ContainerManager
{
/**
* Get a reference to the managed Container. This instance is typically
cast to
* the interface used to interact with the impl.
*/
Object getContainer();
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/ContainerManagerConstants.java
Index: ContainerManagerConstants.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress;
import org.apache.avalon.framework.service.ServiceManager;
/**
* Provides constants used to access the Context object for impl
* managers. A impl manager can assume that all these elements are
* present in the initial context.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Leo Sutic</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:40 $
*/
public interface ContainerManagerConstants extends ContainerConstants
{
/**
* Class: The class of the impl.
*/
String CONTAINER_CLASS = "impl.class";
/**
* ComponentLocator: The component manager to give to the impl.
*/
String SERVICE_MANAGER = ServiceManager.class.getName();
/**
* Configuration: The configuration to give to the impl.
*/
String CONFIGURATION = "impl.configuration";
/**
* Assembly Configuration: The assembly info to give to the impl.
*/
String ASSEMBLY_CONFIGURATION = "impl.assembly.config";
/**
* Parameters: The Parameters object to give to the impl.
*/
String PARAMETERS = "impl.parameters";
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/InitializationException.java
Index: InitializationException.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress;
import org.apache.avalon.framework.CascadingException;
/**
* This exception is used to indicate something went horribly wrong in the
* ContainerManager, and it is unable to create a new instance of your
* Container.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:40 $
*/
public class InitializationException extends CascadingException
{
public InitializationException( final String message )
{
super( message );
}
public InitializationException( final String message, final Throwable
source )
{
super( message, source );
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/RoleEntry.java
Index: RoleEntry.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.avalon.fortress;
/**
* Keeps track of the relationship of all the associated meta data for a
* component type. It records the role, short name, component class, and
* the handler class used to manage it. The short name is included strictly
* to enable "self-healing" configuration files.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version $Revision: 1.1 $ $Date: 2003/01/27 16:55:40 $
*/
public class RoleEntry
{
private final String m_shortName;
private final String m_role;
private final Class m_componentClass;
private final Class m_handlerClass;
/**
* Create a <code>RoleEntry</code> with all the associated information.
* All arguments must be supplied.
*
* @param role Role name for this component type
* @param shortname Short name for this component type
* @param componentClass <code>Class</code> to instantiate the
* component type
* @param handlerClass <code>Class</code> to instantiate the
* component handler
*
* @exception <code>IllegalArgumentException</code> if any argument is
* <code>null</code>.
*/
public RoleEntry( final String role,
final String shortName,
final Class componentClass,
final Class handlerClass ) throws
IllegalArgumentException
{
if( null == role )
{
throw new IllegalArgumentException( "\"role\" cannot be null." );
}
if( null == shortName )
{
throw new IllegalArgumentException( "\"shortname\" cannot be
null." );
}
if( null == componentClass )
{
throw new IllegalArgumentException( "\"componentClass\" cannot be
null." );
}
if( null == handlerClass )
{
throw new IllegalArgumentException( "\"handlerClass\" cannot be
null." );
}
m_role = role;
m_shortName = shortName;
m_componentClass = componentClass;
m_handlerClass = handlerClass;
}
/**
* Get the role name for the component type.
*
* @return the role name
*/
public String getRole()
{
return m_role;
}
/**
* Get the short name for the component type. This is used in
* "self-healing" configuration files.
*
* @return the short name
*/
public String getShortname()
{
return m_shortName;
}
/**
* Get the <code>Class</code> for the component type.
*
* @return the <code>Class</code>
*/
public Class getComponentClass()
{
return m_componentClass;
}
/**
* Get the <code>Class</code> for the component type's [EMAIL PROTECTED]
ComponentHandler}.
*
* @return the <code>Class</code>
*/
public Class getHandlerClass()
{
return m_handlerClass;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/RoleManager.java
Index: RoleManager.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress;
/**
* RoleManager Interface, use this to specify the Components and how they
* correspond to easy shorthand names. The RoleManager assumes a one to one
* relationship of shorthand names to classes, and a flat relationship of
* classes to roles. Any one role can have multiple classes associated with
* it.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:40 $
* @since 4.1
*/
public interface RoleManager
{
/**
* Convenience constant to make lookup of the RoleManager easer.
*/
String ROLE = RoleManager.class.getName();
/**
* Get a <code>RoleEntry</code> for a short name. The short name is an
* alias for a component type.
*
* @param shortname The shorthand name for the component type.
*
* @return the proper [EMAIL PROTECTED]
org.apache.avalon.fortress.RoleEntry}
*/
org.apache.avalon.fortress.RoleEntry getRoleForShortName( String
shortname );
/**
* Get a <code>RoleEntry</code> for a component type. This facilitates
* self-healing configuration files where the impl reads the
* configuration and translates all <code><component/></code>
* entries to use the short hand name for readability.
*
* @param classname The component type name
*
* @return the proper [EMAIL PROTECTED]
org.apache.avalon.fortress.RoleEntry}
*/
org.apache.avalon.fortress.RoleEntry getRoleForClassname( String
classname );
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/package.html
Index: package.html
===================================================================
<body>
<p>
The <code>fortress</code> package contains an implementation of a component
containment system that follows the ECM
semantic concerning component resolution.
See <a href="http://jakarta.apache.org/avalon/excalibur/fortress/"></a> for
more information.</p>
<p>
The contents of this package form the fortress client API.
</p>
</body>
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/AbstractContainer.java
Index: AbstractContainer.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.avalon.excalibur.logger.LoggerManager;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.service.DefaultServiceManager;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.commons.collections.BoundedFifoBuffer;
import org.apache.commons.collections.StaticBucketMap;
import org.apache.excalibur.event.Queue;
import org.apache.avalon.fortress.Container;
import org.apache.avalon.fortress.impl.handler.PrepareHandlerCommand;
import org.apache.avalon.fortress.impl.handler.ComponentFactory;
import org.apache.avalon.fortress.impl.handler.ComponentHandler;
import org.apache.avalon.fortress.impl.handler.LEAwareComponentHandler;
import org.apache.avalon.fortress.impl.handler.ProxyObjectFactory;
import org.apache.avalon.fortress.impl.lookup.FortressServiceManager;
import org.apache.avalon.fortress.impl.lookup.FortressServiceSelector;
import org.apache.avalon.fortress.impl.role.FortressRoleManager;
import org.apache.avalon.fortress.util.CompositeException;
import org.apache.avalon.fortress.RoleEntry;
import org.apache.avalon.fortress.RoleManager;
import org.apache.excalibur.instrument.InstrumentManager;
import org.apache.excalibur.instrument.Instrumentable;
import org.apache.excalibur.mpool.ObjectFactory;
import org.apache.excalibur.mpool.PoolManager;
/**
* This abstract implementation provides basic functionality for building
* an implementation of the [EMAIL PROTECTED] Container} interface.
* It exposes a protected getServiceManager() method so that the
* Container's Manager can expose that to the instantiating class.
*
* @author <a href="mailto:[email protected]">The Avalon Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
*/
public abstract class AbstractContainer
extends AbstractLogEnabled
implements Contextualizable, Serviceable, Initializable, Disposable,
Container
{
/** contains the impl's context passed in through contextualize() */
protected Context m_context;
/** contains the ServiceManager the impl will use, based on the one
passed in through service() */
protected ServiceManager m_serviceManager;
/** contains the impl's LoggerManager, which is extracted from
m_serviceManager */
protected LoggerManager m_loggerManager;
/** contains the impl's PoolManager, which is extracted from
m_serviceManager */
protected PoolManager m_poolManager;
/** contains the impl's Queue, which is extracted from m_serviceManager */
protected Queue m_commandQueue;
/** contains the impl's root ClassLoader, which is extracted from
m_serviceManager */
protected ClassLoader m_classLoader;
/** contains the impl's RoleManager, which is extracted from
m_serviceManager */
protected RoleManager m_roleManager;
/** contains the impl's InstrumentManager, which is extracted from
m_serviceManager */
protected InstrumentManager m_instrumentManager;
/** contains the impl's LifecycleExtensionManager, which is extracted
from m_serviceManager */
protected org.apache.avalon.fortress.impl.LifecycleExtensionManager
m_extManager;
/**
* Contains entries mapping roles to hint maps, where the hint map
contains
* mappings from hints to ComponentHandlers.
*/
protected StaticBucketMap m_mapper = new StaticBucketMap();
/** Contains an entry for each ComponentHandler */
protected List m_components = new ArrayList( 10 );
/**
* Pull the manager items from the context so we can use them to set up
* the system.
* @param context the impl context
* @exception ContextException if a contexaulization error occurs
* @avalon.context type="ClassLoader" optional="true"
*/
public void contextualize( final Context context )
throws ContextException
{
m_context = context;
try
{
m_classLoader = (ClassLoader)context.get(
ClassLoader.class.getName() );
}
catch( ContextException ce )
{
m_classLoader = Thread.currentThread().getContextClassLoader();
}
}
/**
* Root ServiceManager. The Container may choose to have it's
* ServiceManager delegate to the root manager, or it may choose to be
* entirely self contained.
*
* @param serviceManager the service manager to apply to the impl
* @exception ServiceException is a servicing related error occurs
*
* @avalon.dependency type="LoggerManager"
* @avalon.dependency type="PoolManager"
* @avalon.dependency type="InstrumentManager"
* @avalon.dependency type="LifecycleExtensionManager" optional="true"
* @avalon.dependency type="RoleManager" optional="true"
* @avalon.dependency type="Queue" optional="true"
*/
public void service( final ServiceManager serviceManager )
throws ServiceException
{
// get non-optional services
m_loggerManager = (LoggerManager)serviceManager.lookup(
LoggerManager.ROLE );
m_poolManager = (PoolManager)serviceManager.lookup( PoolManager.ROLE
);
m_instrumentManager = (InstrumentManager)serviceManager.lookup(
InstrumentManager.ROLE );
// get optional services, or a default if the service isn't provided
if( serviceManager.hasService(
org.apache.avalon.fortress.impl.LifecycleExtensionManager.ROLE ) )
{
m_extManager =
(org.apache.avalon.fortress.impl.LifecycleExtensionManager)serviceManager.lookup(
org.apache.avalon.fortress.impl.LifecycleExtensionManager.ROLE );
}
else
{
m_extManager = new
org.apache.avalon.fortress.impl.LifecycleExtensionManager();
m_extManager.enableLogging( getLogger() );
if( getLogger().isDebugEnabled() )
{
final String message =
"No Container.LIFECYCLE_EXTENSION_MANAGER is given, " +
"installing default lifecycle extension manager with " +
"0 extensions";
getLogger().debug( message );
}
}
if( serviceManager.hasService( Queue.ROLE ) )
{
m_commandQueue = (Queue)serviceManager.lookup( Queue.ROLE );
}
else
{
final String message =
"No Container.COMMAND_QUEUE is given, all " +
"management will be performed synchronously";
getLogger().warn( message );
}
if( serviceManager.hasService( RoleManager.ROLE ) )
{
m_roleManager = (RoleManager)serviceManager.lookup(
RoleManager.ROLE );
}
else
{
try
{
m_roleManager = createDefaultRoleManager();
}
catch( final Exception e )
{
final String message = "Unable to create default role
manager";
throw new ServiceException( RoleManager.ROLE, message, e );
}
}
// set up our ServiceManager
m_serviceManager = new FortressServiceManager( this, serviceManager );
}
/**
* Create a default RoleManager that can be used to addRole system.
*
* @return the default role manager
* @throws Exception if unable to create role manager
*/
private FortressRoleManager createDefaultRoleManager()
throws Exception
{
final FortressRoleManager roleManager =
new FortressRoleManager( null, m_classLoader );
ContainerUtil.enableLogging( roleManager, getLogger().getChildLogger(
"roles" ) );
ContainerUtil.initialize( roleManager );
return roleManager;
}
/**
* Add a Component into the impl. This sets the component up for
management
* by the impl by creating an appropriate [EMAIL PROTECTED]
ComponentHandler}.
*
* @param metaData the information needed to construct a ComponentHandler
for the component
* @throws IllegalArgumentException if the classname defined by the meta
data
* argument is undefined within the scope of the role manager
* @throws Exception if unable to create a Handler for the component
*/
protected void addComponent( final ComponentHandlerMetaData metaData )
throws IllegalArgumentException, Exception
{
// figure out Role
final String classname = metaData.getClassname();
final RoleEntry roleEntry = m_roleManager.getRoleForClassname(
classname );
if( null == roleEntry )
{
final String message = "No role defined for " + classname;
throw new IllegalArgumentException( message );
}
// create a handler for the combo of Role+MetaData
final ComponentHandler handler =
getComponentHandler( roleEntry, metaData );
final String role = roleEntry.getRole();
// put the role into our role mapper. If the role doesn't exist
// yet, just stuff it in as "default". If it does, we create a
// ServiceSelector and put that in as "selector".
if( null != role && null != classname && null != handler )
{
Map hintMap = (StaticBucketMap)m_mapper.get( role );
if( null == hintMap ) // never heard of this role before.
{
hintMap = new StaticBucketMap();
hintMap.put( "default", handler );
m_mapper.put( role, hintMap );
}
else // know it already. add something to the hintmap
{
hintMap.put( metaData.getName(), handler );
if( hintMap.containsKey( "default" ) )
{
if( !hintMap.containsKey( "selector" ) )
{
hintMap.put( "selector",
new FortressServiceSelector( this, role
) );
}
}
else
{
hintMap.put( "default", handler );
}
}
}
}
/**
* Get a ComponentHandler with the default constructor for the component
class passed in.
*
* @param roleEntry the description of the Role this handler will be for
* @param metaData the information needed to construct a ComponentHandler
for the component
* @return the component handler
* @throws Exception if unable to provide a componenthandler
*/
private ComponentHandler getComponentHandler( final RoleEntry roleEntry,
final
ComponentHandlerMetaData metaData )
throws Exception
{
// get info from params
ComponentHandler handler = null;
final String classname = roleEntry.getComponentClass().getName();
final Configuration configuration = metaData.getConfiguration();
try
{
final ObjectFactory factory =
createObjectFactory( classname, configuration );
// create the appropriate handler instance
final ComponentHandler targetHandler =
(ComponentHandler)roleEntry.getHandlerClass().newInstance();
// do the handler lifecycle
ContainerUtil.contextualize( targetHandler, m_context );
final DefaultServiceManager serviceManager =
new DefaultServiceManager( getServiceManager() );
serviceManager.put( ObjectFactory.ROLE, factory );
serviceManager.makeReadOnly();
ContainerUtil.service( targetHandler, serviceManager );
ContainerUtil.configure( targetHandler, configuration );
ContainerUtil.initialize( targetHandler );
if( targetHandler instanceof Instrumentable )
{
final Instrumentable instrumentable =
(Instrumentable)targetHandler;
final String name = instrumentable.getInstrumentableName();
m_instrumentManager.registerInstrumentable( instrumentable,
name );
}
// no other lifecycle stages supported for ComponentHandler;
// ComponentHandler is not a "true" avalon component
handler =
new LEAwareComponentHandler( targetHandler, m_extManager,
m_context );
}
catch( final Exception e )
{
// if anything went wrong, the component cannot be worked with
// and it cannot be added into the impl, so don't provide
// a handler
if( getLogger().isDebugEnabled() )
{
final String message =
"Could not create the handler for the '" +
classname + "' component.";
getLogger().debug( message, e );
}
throw e;
}
if( getLogger().isDebugEnabled() )
{
final String message =
"Component " + classname +
" uses handler " + roleEntry.getHandlerClass().getName();
getLogger().debug( message );
}
// we're still here, so everything went smooth. Register the handler
// and return it
final ComponentHandlerEntry entry =
new ComponentHandlerEntry( handler, metaData );
m_components.add( entry );
return handler;
}
/**
* Create an objectFactory for specified Object configuration.
*
* @param classname the classname of object
* @param configuration the objests configuration
* @return the ObjectFactory
* @throws ClassNotFoundException if the specified class does not exist
*/
protected ObjectFactory createObjectFactory( final String classname,
final Configuration
configuration )
throws ClassNotFoundException
{
final Class clazz = m_classLoader.loadClass( classname );
final ComponentFactory componentFactory =
new ComponentFactory( clazz, configuration,
m_serviceManager, m_context,
m_loggerManager, m_extManager,
m_instrumentManager );
return new ProxyObjectFactory( componentFactory );
}
/**
* This is the method that the ContainerComponentManager and Selector use
* to gain access to the ComponentHandlers and ComponentSelectors. The
* actual access of the ComponentHandler is delegated to the Container.
*
* @param role The role we intend to access a Component for.
* @param hint The hint that we use as a qualifier
* (note: if null, the default implementation is returned).
*
* @return Object a reference to the ComponentHandler or
* ComponentSelector for the role/hint combo.
*/
public Object get( final String role, final Object hint )
throws ServiceException
{
final Map hintMap = (StaticBucketMap)m_mapper.get( role );
Object value;
if( null == hintMap )
{
final String key = getRoleKey( role, hint );
final String message = "Component does not exist";
throw new ServiceException( key, message );
}
if( null == hint )
{
// no hint -> try selector
value = hintMap.get( "selector" );
if( null == value )
{
// no selector -> use default
value = hintMap.get( "default" );
}
return value;
}
// got a hint -> use it
value = hintMap.get( hint );
if( null == value )
{
final String key = getRoleKey( role, hint );
final String message = "Component does not exist";
throw new ServiceException( key, message );
}
return value;
}
/**
* Get the composite role name based on the specified role and hint.
* The default implementation puts a "/" on the end of the rolename
* and then adds the string representation of the hint.
* This is used <i>for informational display purposes only</i>.
*
* @param role
* @param hint
* @return
*/
protected static String getRoleKey( final String role, final Object hint )
{
return role + "/" + hint;
}
/**
* This is the method that the ContainerComponentManager and Selector use
* to gain access to the ComponentHandlers and ComponentSelectors. The
* actual access of the ComponentHandler is delegated to the Container.
*
* @param role The role we intend to access a Component for.
* @param hint The hint that we use as a qualifier
* (note: if null, the default implementation is returned).
*
* @return true if a reference to the role exists.
*/
public boolean has( final String role, final Object hint )
{
final Map hintMap = (StaticBucketMap)m_mapper.get( role );
boolean hasComponent = false;
if( null != hintMap )
{
hasComponent = true;
}
if( hasComponent )
{
if( null == hint )
{
// no hint -> try selector
hasComponent = hintMap.containsKey( "selector" );
if( !hasComponent )
{
// no hint -> try default
hasComponent = hintMap.containsKey( "default" );
}
}
else
{
// hint -> find it
hasComponent = hintMap.containsKey( hint );
}
}
return hasComponent;
}
/**
* Initializes the impl and all the components it hosts so that they are
ready to be used.
* Unless components ask for lazy activation, this is where they are
activated.
*
* @throws CompositeException if one or more components could not be
initialized.
* The system <i>is</i> running properly so if the
missing components are
* not vital to operation, it should be possible to
recover gracefully
*/
public void initialize()
throws CompositeException
{
// go over all components
final Iterator i = m_components.iterator();
final BoundedFifoBuffer buffer = new BoundedFifoBuffer(
m_components.size() );
ComponentHandlerEntry entry;
while( i.hasNext() )
{
entry = (ComponentHandlerEntry)i.next();
try
{
final ComponentHandler handler = entry.getHandler();
// if the component is not lazy, prepare it now,
// otherwise, don't do anything yet
if( !entry.getMetaData().isLazyActivation() )
{
// if we're doing queueing, enqueue, otherwise tell
// the handler to prepare itself and its components.
if( null != m_commandQueue )
{
final PrepareHandlerCommand element =
new PrepareHandlerCommand( handler, getLogger() );
m_commandQueue.enqueue( element );
}
else
{
handler.prepareHandler();
}
}
else
{
if( getLogger().isDebugEnabled() )
{
final String message = "ComponentHandler (" + handler
+
") has specified request time initialization
policy, " +
"initialization deferred till first use";
getLogger().debug( message );
}
}
}
catch( final Exception e )
{
final String cName = entry.getMetaData().getName();
if( getLogger().isWarnEnabled() )
{
final String message = "Could not initialize component "+
cName;
getLogger().warn( message, e );
}
buffer.add( e );
}
}
// if we were unable to activate one or more components,
// throw an exception
if( buffer.size() > 0 )
{
throw new CompositeException( (Exception[])buffer.toArray( new
Exception[0] ),
"unable to instantiate one or more components" );
}
}
/**
* Disposes of all components and frees resources that they consume.
*/
public void dispose()
{
final Iterator i = m_components.iterator();
while( i.hasNext() )
{
final ComponentHandlerEntry entry =
(ComponentHandlerEntry)i.next();
final ComponentHandler handler = entry.getHandler();
if (getLogger().isDebugEnabled()) getLogger().debug("Shutting
down: " + handler);
ContainerUtil.dispose( handler );
if (getLogger().isDebugEnabled()) getLogger().debug("Done.");
}
}
/**
* Exposes to subclasses the service manager which this impl
* uses to manage its child components.
* The returned ServiceManager <i>is</i> aware of the services passed
* in to <i>this</i> impl, and services that were passed in through
* service() are hence available to subclasses.
*
* @return the service manager that contains the child components.
*/
protected ServiceManager getServiceManager()
{
return m_serviceManager;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/ComponentHandlerEntry.java
Index: ComponentHandlerEntry.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.avalon.fortress.impl;
import org.apache.avalon.fortress.impl.handler.ComponentHandler;
/**
* This is the impl of runtime information about a
* ComponentHandler.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
*/
class ComponentHandlerEntry
{
private final ComponentHandler m_handler;
private final ComponentHandlerMetaData m_metaData;
/**
* Create an entry for a particular handler.
*
* @param handler the handler
* @param metaData the metadata for handler
*/
public ComponentHandlerEntry( final ComponentHandler handler,
final ComponentHandlerMetaData metaData )
{
if( null == handler )
{
throw new NullPointerException( "handler" );
}
if( null == metaData )
{
throw new NullPointerException( "metaData" );
}
m_handler = handler;
m_metaData= metaData;
}
/**
* Return the handler that entry manages.
*
* @return the handler that entry manages.
*/
public ComponentHandler getHandler()
{
return m_handler;
}
/**
* Return the meta data for handler.
*
* @return the meta data for handler.
*/
public ComponentHandlerMetaData getMetaData()
{
return m_metaData;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/ComponentHandlerMetaData.java
Index: ComponentHandlerMetaData.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.avalon.fortress.impl;
import org.apache.avalon.framework.configuration.Configuration;
/**
* A class holding metadata about a component handler.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
*/
public class ComponentHandlerMetaData
{
private final String m_name;
private final String m_classname;
private final Configuration m_configuration;
private final boolean m_lazyActivation;
/**
* Creation of a new impl handler meta data instance.
* @param name the handler name
* @param classname the handler classname
* @param configuration the handler configuration
* @param laxyActivation the activation policy
*/
public ComponentHandlerMetaData( final String name,
final String classname,
final Configuration configuration,
final boolean lazyActivation )
{
if( null == name )
{
throw new NullPointerException( "name" );
}
if( null == classname )
{
throw new NullPointerException( "classname" );
}
if( null == configuration )
{
throw new NullPointerException( "configuration" );
}
m_name = name;
m_classname = classname;
m_configuration = configuration;
m_lazyActivation = lazyActivation;
}
/**
* Returns the handler name
* @return the handler name
*/
public String getName()
{
return m_name;
}
/**
* Returns the handler classname
* @return the classname
*/
public String getClassname()
{
return m_classname;
}
/**
* Returns the handler configuration
* @return the configuration
*/
public Configuration getConfiguration()
{
return m_configuration;
}
/**
* Returns the handler activation policy
* @return the activation policy
*/
public boolean isLazyActivation()
{
return m_lazyActivation;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/DefaultContainer.java
Index: DefaultContainer.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.fortress.RoleEntry;
/**
* This is the default implementation of [EMAIL PROTECTED]
org.apache.avalon.fortress.Container},
* adding configuration markup semantics to the [EMAIL PROTECTED]
AbstractContainer}.
*
* @author <a href="mailto:[email protected]">The Avalon Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
*/
public class DefaultContainer
extends AbstractContainer
implements Configurable
{
/**
* <p>Process the configuration and set up the components and their
* mappings. At this point, all components are prepared and all mappings
* are made. However, nothing is initialized.</p>
*
* <p>The native Configuration format follows a specific convention. If
* you use a RoleManager to map roles and implementations to more helpful
* names, we will internally rewrite the configuration to match this
* format. Please note: If a configuration element does
* <strong>not</strong> have a unique id, it will not be treated as a
* Component. That ID is used as the hint when there is more than one
* implementation of a role.</p>
*
* <pre>
* <component
role="org.apache.avalon.excalibur.datasource.DataSourceComponent"
* id="default-connection"
*
class="org.apache.avalon.excalibur.datasource.JdbcDataSourceComponent"
*
handler="org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler">
*
* <!-- Component specific configuration -->
*
* </component>
* </pre>
*
* @param config The configuration element to translate into the
* list of components this impl managers.
*
* @throws ConfigurationException if the configuration is not valid
*/
public void configure( final Configuration config )
throws ConfigurationException
{
final Configuration[] elements = config.getChildren();
for( int i = 0; i < elements.length; i++ )
{
final Configuration element = elements[ i ];
final String hint = element.getAttribute( "id", null );
if ( null == hint )
{
// Only components with an id attribute are treated as
components.
getLogger().debug( "Ignoring configuration for component, " +
element.getName()
+ ", because the id attribute is missing." );
}
else
{
final String classname = getClassname( element );
final boolean isLazy = isLazyComponentHandler( element );
final ComponentHandlerMetaData metaData =
new ComponentHandlerMetaData( hint, classname, element,
isLazy );
addComponent( metaData );
}
}
}
/**
* Retrieve the classname for component configuration.
*
* @param config the component configuration
* @return the class name
*/
private String getClassname( final Configuration config )
throws ConfigurationException
{
if( "component".equals( config.getName() ) )
{
return config.getAttribute( "class" );
}
else
{
final org.apache.avalon.fortress.RoleEntry roleEntry =
m_roleManager.getRoleForShortName( config.getName() );
if( null == roleEntry )
{
final String message = "No class found matching configuration
name " +
"[name: " + config.getName() + ", location: " +
config.getLocation() + "]";
throw new ConfigurationException( message );
}
return roleEntry.getComponentClass().getName();
}
}
/**
* Helper method to determine whether a given component handler
* configuration requests a lazy or startup based initialization policy.
*
* @param component <code>Configuration</code>
*
* @return true if the given handler configuration specifies a lazy init
* policy, false otherwise
*
* @throws java.lang.IllegalArgumentException if the handler specifies an
unknown init
* policy
*/
private boolean isLazyComponentHandler( Configuration component )
{
String policy = component.getAttribute( "activation", "startup" );
final boolean isLazy = "request".equalsIgnoreCase( policy );
final boolean isNonLazy = "startup".equalsIgnoreCase( policy );
if( isNonLazy )
{
return false;
}
else if( isLazy )
{
return true;
}
else
{
// policy was not null, but didn't match anything above
final String classname = component.getAttribute( "class", null );
final String message =
"Unknown activation policy for class " + classname + ": " +
policy;
throw new IllegalArgumentException( message );
}
}
/**
* Return the ServiceManager that exposes all the services in impl.
*
* @return the ServiceManager that exposes all the services in impl.
*/
public ServiceManager getServiceManager()
{
return super.getServiceManager();
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/DefaultContainerManager.java
Index: DefaultContainerManager.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl;
import org.apache.avalon.excalibur.logger.LoggerManager;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.component.Composable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.service.DefaultServiceManager;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.excalibur.event.Queue;
import org.apache.avalon.fortress.util.ContextManager;
import org.apache.excalibur.instrument.InstrumentManager;
import org.apache.excalibur.mpool.PoolManager;
/**
* This is the default implementation of the [EMAIL PROTECTED]
org.apache.avalon.fortress.ContainerManager} interface.
* See that interface for a description.
*
* @author <a href="mailto:[email protected]">The Avalon Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
*/
public class DefaultContainerManager
implements Initializable, Disposable,
org.apache.avalon.fortress.ContainerManager,
org.apache.avalon.fortress.ContainerManagerConstants
{
private final ContextManager m_contextManager;
private Logger m_logger;
private Object m_containerInstance;
public DefaultContainerManager( final ContextManager contextManager )
{
this( contextManager, null );
}
public DefaultContainerManager( final ContextManager contextManager,
final Logger logger )
{
m_contextManager = contextManager;
m_logger = ( logger == null ?
createLoggerFromContext(
m_contextManager.getContainerManagerContext() ) : logger );
}
public DefaultContainerManager( final Context initParameters )
{
this( initParameters, null );
}
public DefaultContainerManager( final Context initParameters,
final Logger logger )
{
this( getInitializedContextManager( initParameters, logger ), logger
);
}
/**
* Creates and initializes a contextManager given an initialization
context.
* This is necessary so that these operations can complete before the
* super constructor has been executed.
*/
private static ContextManager getInitializedContextManager( final Context
initParameters,
Logger logger
)
{
// The context manager will use an internal coonsole logger if logger
is null.
ContextManager contextManager = new ContextManager( initParameters,
logger );
try
{
contextManager.initialize();
return contextManager;
}
catch( Exception e )
{
if( logger == null )
{
logger = new ConsoleLogger( ConsoleLogger.LEVEL_INFO );
}
logger.fatalError( "Unable to initialize the contextManager.", e
);
// What should happen now. There needs to be a failure mode here.
// As is, this will result in an NPE, but it can't really be
allowed
// to continue without having been initialized.
return null;
}
}
protected Logger createLoggerFromContext( Context initParameters )
{
try
{
return ( (LoggerManager)initParameters.get( LoggerManager.ROLE )
).getDefaultLogger();
}
catch( ContextException ce )
{
final Logger consoleLogger = new ConsoleLogger();
consoleLogger.error( "ContainerManager could not obtain logger
manager from context "
+ "(this should not happen). Using console
instead." );
return consoleLogger;
}
}
/**
* Initialize the ContainerManager
*/
public void initialize() throws Exception
{
initializeContainer();
}
protected void initializeContainer() throws
org.apache.avalon.fortress.InitializationException
{
if( null == m_containerInstance )
{
createContainer();
}
}
private void createContainer()
throws org.apache.avalon.fortress.InitializationException
{
final Context managerContext =
m_contextManager.getContainerManagerContext();
Object instance = null;
try
{
final Class clazz = (Class)managerContext.get( CONTAINER_CLASS );
instance = clazz.newInstance();
}
catch( Exception e )
{
final String message =
"Cannot set up impl. Unable to create impl class";
throw new org.apache.avalon.fortress.InitializationException(
message, e );
}
try
{
ContainerUtil.enableLogging( instance, m_logger );
ContainerUtil.contextualize( instance, managerContext );
if( instance instanceof Composable )
{
throw new org.apache.avalon.fortress.InitializationException(
"Composable containers are not supported" );
}
final ServiceManager serviceManager =
createServiceManager( managerContext );
ContainerUtil.service( instance, serviceManager );
final Configuration config =
(Configuration)getContextEntry( managerContext, CONFIGURATION
);
ContainerUtil.configure( instance, config );
final Parameters parameters =
(Parameters)getContextEntry( managerContext, PARAMETERS );
ContainerUtil.parameterize( instance, parameters );
ContainerUtil.initialize( instance );
ContainerUtil.start( instance );
m_containerInstance = instance;
}
catch( Exception e )
{
final String message =
"Cannot set up impl. Startup lifecycle failure";
throw new org.apache.avalon.fortress.InitializationException(
message, e );
}
}
private ServiceManager createServiceManager( final Context managerContext
)
{
final ServiceManager smanager =
(ServiceManager)getContextEntry( managerContext, SERVICE_MANAGER
);
final DefaultServiceManager serviceManager = new
DefaultServiceManager( smanager );
addService( Queue.ROLE, managerContext, serviceManager );
addService( LoggerManager.ROLE, managerContext, serviceManager );
addService( PoolManager.ROLE, managerContext, serviceManager );
addService( InstrumentManager.ROLE, managerContext, serviceManager );
addService( org.apache.avalon.fortress.RoleManager.ROLE,
managerContext, serviceManager );
addService(
org.apache.avalon.fortress.impl.LifecycleExtensionManager.ROLE, managerContext,
serviceManager );
serviceManager.makeReadOnly();
return serviceManager;
}
private void addService( final String role,
final Context context,
final DefaultServiceManager serviceManager )
{
try
{
final Object object = context.get( role );
serviceManager.put( role, object );
}
catch( ContextException e )
{
}
}
/**
* Retrieve an entry from context if it exists, else return null.
*
* @param context the context
* @param key the key
* @return the entry
*/
private Object getContextEntry( final Context context, final String key )
{
try
{
return context.get( key );
}
catch( ContextException e )
{
return null;
}
}
protected void disposeContainer()
{
if( null != m_containerInstance )
{
try
{
ContainerUtil.stop( m_containerInstance );
}
catch( Exception e )
{
if( getLogger().isWarnEnabled() )
{
getLogger().warn( "Caught an exception when stopping the
Container, "
+ "continuing with shutdown", e );
}
}
ContainerUtil.dispose( m_containerInstance );
m_containerInstance = null;
}
}
/**
* Dispose of the ContainerManager and managed Container
*/
public void dispose()
{
disposeContainer();
m_contextManager.dispose();
}
/**
* Get a reference to your Container. Typically, you would cast this to
* whatever interface you will use to interact with it.
*/
public Object getContainer()
{
return m_containerInstance;
}
/**
* Allows to get the logger and associated hierarchy for logging.
* @return Logger
*/
public final Logger getLogger()
{
// (mschier) was protected.
// Made public to get to the logger at the impl setup level.
return m_logger;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/LifecycleExtensionManager.java
Index: LifecycleExtensionManager.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl;
import java.util.Iterator;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.excalibur.container.lifecycle.Accessor;
import org.apache.excalibur.container.lifecycle.Creator;
import org.apache.avalon.fortress.util.CachedArrayList;
/**
* <code>LifecycleExtensionManager</code> class. This class manages a list
* of extensions objects that are executed on components during the various
* stages of their lifecycles.
*
* <p>
* It provides methods for adding extension objects to the system,
* and a method for executing them on a particular component object. The
* current context is also passed in to the extension objects to facilitate
* the communication of any global values.
* </p>
*
* <p>
* Extensions are stored internally in a list. This guarentees that the
* order in which they are executed matches the order in which they are
* inserted.
* </p>
*
* @author <a href="mailto:[EMAIL PROTECTED]">Marcus Crafter</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
* @todo use something from Commons instead of CachedArrayList?
*/
public class LifecycleExtensionManager
extends AbstractLogEnabled
{
public static final String ROLE =
LifecycleExtensionManager.class.getName();
// extensions objects
private final CachedArrayList m_accessorExtensions = new
CachedArrayList();
private final CachedArrayList m_creatorExtensions = new CachedArrayList();
/**
* <code>executeAccessExtensions</code> method, executes all access
* level extensions on the given component.
*
* @param component a <code>Component</code> instance
* @param context a <code>Context</code> instance
* @exception java.lang.Exception if an error occurs
*/
public void executeAccessExtensions( Object component, Context context )
throws Exception
{
executeExtensions( m_accessorExtensions.toArray(), component,
context, ACCESS );
}
/**
* <code>executeReleaseExtensions</code> method, executes all release
* level extensions on the given component.
*
* @param component a <code>Component</code> instance
* @param context a <code>Context</code> instance
* @exception java.lang.Exception if an error occurs
*/
public void executeReleaseExtensions( Object component, Context context )
throws Exception
{
executeExtensions( m_accessorExtensions.toArray(), component,
context, RELEASE );
}
/**
* <code>executeCreationExtensions</code> method, executes all creation
* level extensions on the given component.
*
* @param component a <code>Component</code> instance
* @param context a <code>Context</code> instance
* @exception java.lang.Exception if an error occurs
*/
public void executeCreationExtensions( Object component, Context context )
throws Exception
{
executeExtensions( m_creatorExtensions.toArray(), component, context,
CREATE );
}
/**
* <code>executeDestructionExtensions</code> method, executes all
* destruction level extensions on the given component.
*
* @param component a <code>Component</code> instance
* @param context a <code>Context</code> instance
* @exception java.lang.Exception if an error occurs
*/
public void executeDestructionExtensions( Object component, Context
context )
throws Exception
{
executeExtensions( m_creatorExtensions.toArray(), component, context,
DESTROY );
}
// The following methods define operations that modify the internal list
// of extensions. I've refrained from returning the List directly, via a
// getExtensions() method for the following reasons:
//
// 1. Returning List breaks encapsulation, implicitly exposing all of
List's
// current and future operations to the client
// 2. List operates with type Object, not LifecycleExtension which means
we need
// more error handling code if we make it possible for the user to add
instances
// of any type to the extension lists.
// 3. Wrapping add/remove methods allow us to add optimizations to
improve performance
// (eg. to convert the List to an array upon each add/remove, and not
upon each
// execute operation)
// 4. The book 'Refactoring' says we shouldn't do it :-)
//
// I'm open to suggestions though if there's any better ideas ?
/**
* Adds an accessor extension to the manager
*
* @param extension a <code>Accessor</code> instance
*/
public void addAccessorExtension( Accessor extension )
{
m_accessorExtensions.add( extension );
}
/**
* Adds a creator extension to the manager
*
* @param extension a <code>Creator</code> instance
*/
public void addCreatorExtension( Creator extension )
{
m_creatorExtensions.add( extension );
}
/**
* Inserts an accessor extension at a given index in the manager
*
* @param position an <code>int</code> index value
* @param extension a <code>Accessor</code> instance
*/
public void insertAccessorExtension( int position, Accessor extension )
{
m_accessorExtensions.insert( position, extension );
}
/**
* Inserts a creator extension at a given index in the manager
*
* @param position an <code>int</code> index value
* @param extension a <code>Creator</code> instance
*/
public void insertCreatorExtension( int position, Creator extension )
{
m_accessorExtensions.insert( position, extension );
}
/**
* Removes a particular accessor extension from the manager
*
* @param position an <code>int</code> index value
* @return a <code>Accessor</code> instance
*/
public Accessor removeAccessorExtension( int position )
{
return (Accessor)m_accessorExtensions.remove( position );
}
/**
* Removes a particular creator extension from the manager
*
* @param position an <code>int</code> index value
* @return a <code>Creator</code> instance
*/
public Creator removeCreatorExtension( int position )
{
return (Creator)m_creatorExtensions.remove( position );
}
/**
* Obtain an iterator.
*
* @return an <code>Iterator</code> instance
*/
public Iterator accessorExtensionsIterator()
{
return m_accessorExtensions.iterator();
}
/**
* Obtain an iterator.
*
* @return an <code>Iterator</code> instance
*/
public Iterator creatorExtensionsIterator()
{
return m_creatorExtensions.iterator();
}
/**
* Find out the total number of accessor extensions registered with this
manager
*
* @return an <code>int</code> value
*/
public int accessorExtensionsCount()
{
return m_accessorExtensions.size();
}
/**
* Find out the total number of creator extensions registered with this
manager
*
* @return an <code>int</code> value
*/
public int creatorExtensionsCount()
{
return m_creatorExtensions.size();
}
/**
* Obtain the particular accessor extension at the given index
*
* @param index an <code>int</code> index value
* @return a <code>Accessor</code> instance
*/
public Accessor getAccessorExtension( int index )
{
return (Accessor)m_accessorExtensions.get( index );
}
/**
* Obtain the particular creator extension at the given index
*
* @param index an <code>int</code> index value
* @return a <code>Creator</code> instance
*/
public Creator getCreatorExtension( int index )
{
return (Creator)m_creatorExtensions.get( index );
}
/**
* Clears all accessor extensions registered with this manager
*/
public void clearAccessorExtensions()
{
m_accessorExtensions.clear();
}
/**
* Clears all creator extensions registered with this manager
*/
public void clearCreatorExtensions()
{
m_creatorExtensions.clear();
}
// Lifecycle method constants, these are passed to executeExtensions()
protected static final int ACCESS = 0;
protected static final int RELEASE = 1;
protected static final int CREATE = 2;
protected static final int DESTROY = 3;
/**
* <code>executeExtensions</code> method, executes a given array of
* lifecycle interfaces on a given component.
*
* @param component a <code>Component</code> instance
* @param context a <code>Context</code> instance
* @param type a constant, referencing which phase the
* extensions array adheres to
*
* @exception java.lang.Exception if an error occurs
*/
protected void executeExtensions( final Object[] extensions,
final Object component,
final Context context,
final int type )
throws Exception
{
switch( type )
{
case ACCESS:
for( int i = 0; i < extensions.length; ++i )
{
( (Accessor)extensions[ i ] ).access( component, context
);
}
break;
case RELEASE:
for( int i = 0; i < extensions.length; ++i )
{
( (Accessor)extensions[ i ] ).release( component, context
);
}
break;
case CREATE:
for( int i = 0; i < extensions.length; ++i )
{
( (Creator)extensions[ i ] ).create( component, context );
}
break;
case DESTROY:
for( int i = 0; i < extensions.length; ++i )
{
( (Creator)extensions[ i ] ).destroy( component, context
);
}
break;
default:
if( getLogger().isErrorEnabled() )
{
final String message =
"Incorrect extension phase specified: " + type;
getLogger().error( message );
}
}
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/package.html
Index: package.html
===================================================================
<body>
<p>
The <code>fortress.impl</code> package contains the containment abstraction
of the Fortress system
</p>
<p>
The contents of this package are not a part of the fortress client API.
</p>
</body>
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/AbstractComponentHandler.java
Index: AbstractComponentHandler.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.handler;
import org.apache.avalon.excalibur.logger.LoggerManager;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.excalibur.instrument.AbstractInstrumentable;
import org.apache.excalibur.instrument.Instrumentable;
import org.apache.excalibur.mpool.ObjectFactory;
/**
* AbstractComponentHandler class, ensures components are initialized
* and destroyed correctly.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
* @since 4.0
*/
public abstract class AbstractComponentHandler
extends AbstractInstrumentable
implements Serviceable, Initializable, Disposable, ComponentHandler
{
/**
* The instance of the ComponentFactory that creates and disposes of the
* Component
*/
protected ObjectFactory m_factory;
/**
* State management boolean stating whether the Handler is initialized or
* not
*/
protected boolean m_prepared;
/**
* State management boolean stating whether the Handler is disposed or
* not
*/
protected boolean m_disposed;
/** Logger for factory */
protected Logger m_logger;
/** Logger Manager */
protected LoggerManager m_loggerManager;
/**
* @avalon.dependency type="LoggerManager"
*/
public void service( ServiceManager manager )
throws ServiceException
{
m_loggerManager =
(LoggerManager)manager.lookup( LoggerManager.ROLE );
m_factory =
(ObjectFactory)manager.lookup( ObjectFactory.ROLE );
}
public void initialize()
throws Exception
{
final String classname = getClass().getName();
final int index = classname.lastIndexOf( '.' );
final String name = classname.substring( index + 1 );
String loggerName = name.toLowerCase();
if( name.endsWith( "ComponentHandler" ) )
{
final int endIndex = loggerName.length() - 16;
loggerName = loggerName.substring( 0, endIndex );
}
final String categoryName = "system.handler." + loggerName;
m_logger =
m_loggerManager.getLoggerForCategory( categoryName );
if( m_factory instanceof Instrumentable )
{
addChildInstrumentable( (Instrumentable)m_factory );
}
setInstrumentableName( name );
}
/**
* Actually prepare the handler and make it ready to
* handle component access.
*
* @throws Exception if unable to prepare handler
*/
public void prepareHandler()
throws Exception
{
if( m_prepared )
{
return;
}
if( m_disposed )
{
final String message = "Attempted to prepare disposed
ComponentHandler for : " +
m_factory.getCreatedClass().getName();
m_logger.warn( message );
return;
}
doPrepare();
if( m_logger.isDebugEnabled() )
{
final String message = "ComponentHandler initialized for: " +
m_factory.getCreatedClass().getName();
m_logger.debug( message );
}
m_prepared = true;
}
/**
* Initialize the ComponentHandler.
* Subclasses should overide this to do their own initialization.
*/
protected void doPrepare()
throws Exception
{
}
/**
* Get a reference of the desired Component
* @return the component
*/
public Object get()
throws Exception
{
synchronized( this )
{
if( !m_prepared )
{
prepareHandler();
}
}
if( m_disposed )
{
final String message =
"You cannot get a component from a disposed holder";
throw new IllegalStateException( message );
}
return doGet();
}
/**
* Subclasses should actually overide this to do the work
* of retrieving a service.
*
* @return the service
* @throws Exception if unable to aquire service
*/
protected abstract Object doGet()
throws Exception;
/**
* Return a reference of the desired Component
* @param component the component
*/
public void put( final Object component )
{
if( !m_prepared )
{
final String message =
"You cannot put a component in an uninitialized holder";
throw new IllegalStateException( message );
}
doPut( component );
}
/**
* Subclasses should overide this to return component to handler.
*
* @param component the component
*/
protected void doPut( final Object component )
{
}
/**
* Create a new component for handler.
*
* @return the new component
* @throws Exception if unable to create new component
*/
protected Object newComponent()
throws Exception
{
try
{
return m_factory.newInstance();
}
catch( final Exception e )
{
if( m_logger.isErrorEnabled() )
{
final String message = "Unable to create new instance";
m_logger.error( message, e );
}
throw e;
}
}
/**
* Dispose of the specified component.
*
* @param component the component
*/
protected void disposeComponent( final Object component )
{
if( null == component )
{
return;
}
try
{
m_factory.dispose( component );
}
catch( final Exception e )
{
if( m_logger.isWarnEnabled() )
{
m_logger.warn( "Error disposing component", e );
}
}
}
/**
* Dispose of the ComponentHandler and any associated Pools and Factories.
*/
public void dispose()
{
doDispose();
try
{
ContainerUtil.dispose( m_factory );
}
catch( RuntimeException e )
{
if( m_logger.isWarnEnabled() )
{
final String message = "Error decommissioning component: " +
m_factory.getCreatedClass().getName();
m_logger.warn( message, e );
}
}
m_disposed = true;
}
/**
* Dispose handler specific resources.
* Subclasses should overide this to provide their own funcitonality.
*/
protected void doDispose()
{
}
/**
* Represents the handler as a string.
* @return the string representation of the handler
*/
public String toString()
{
return getClass().getName() + "[for: " +
m_factory.getCreatedClass().getName() + "]";
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/ComponentFactory.java
Index: ComponentFactory.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.handler;
import org.apache.avalon.excalibur.logger.LoggerManager;
import org.apache.avalon.framework.component.WrapperComponentManager;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.logger.LogEnabled;
import org.apache.avalon.framework.logger.LogKit2AvalonLoggerAdapter;
import org.apache.avalon.framework.logger.Loggable;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.parameters.Parameterizable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.avalon.fortress.impl.LifecycleExtensionManager;
import org.apache.excalibur.instrument.CounterInstrument;
import org.apache.excalibur.instrument.Instrument;
import org.apache.excalibur.instrument.InstrumentManageable;
import org.apache.excalibur.instrument.InstrumentManager;
import org.apache.excalibur.instrument.Instrumentable;
import org.apache.excalibur.mpool.ObjectFactory;
/**
* Factory for Avalon components.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Paul Russell</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
* @since 4.0
*/
public class ComponentFactory
extends AbstractLogEnabled
implements ObjectFactory, ThreadSafe, Instrumentable
{
private CounterInstrument m_newInstance;
private CounterInstrument m_dispose;
/**
* Name of the Instrumentable. Maps to the id of the component in the
* configuration.
*/
private String m_instrumentableName;
/** The class which this <code>ComponentFactory</code>
* should create.
*/
private Class m_componentClass;
/** The Context for the component
*/
private Context m_context;
/** The component manager for this component.
*/
private ServiceManager m_serviceManager;
/** The configuration for this component.
*/
private Configuration m_configuration;
/** The LogKitManager for child ComponentSelectors
*/
private LoggerManager m_loggerManager;
/** Lifecycle extensions manager
*/
private final org.apache.avalon.fortress.impl.LifecycleExtensionManager
m_extManager;
/** InstrumentManager
*/
private final InstrumentManager m_instrumentManager;
private Logger m_componentLogger;
/**
* Construct a new component factory for the specified component.
*
* @param componentClass the class to instantiate (must have a default
constructor).
* @param configuration the <code>Configuration</code> object to pass to
new instances.
* @param serviceManager the service manager to pass to
<code>Serviceable</code>s.
* @param context the <code>Context</code> to pass to
<code>Contexutalizable</code>s.
* @param loggerManager the loggerManager manager instance.
*/
public ComponentFactory( final Class componentClass,
final Configuration configuration,
final ServiceManager serviceManager,
final Context context,
final LoggerManager loggerManager,
final
org.apache.avalon.fortress.impl.LifecycleExtensionManager extManager,
final InstrumentManager instrumentManager )
{
m_componentClass = componentClass;
m_configuration = configuration;
m_serviceManager = serviceManager;
m_context = context;
m_loggerManager = loggerManager;
m_extManager = extManager;
enableLogging( m_loggerManager.getLoggerForCategory( "system.factory"
) );
m_instrumentManager = instrumentManager;
m_instrumentableName = configuration.getAttribute( "id",
componentClass.getName() );
m_componentLogger = aquireLogger();
m_newInstance = new CounterInstrument( "creates" );
m_dispose = new CounterInstrument( "destroys" );
}
/**
* Returns a new instance of a component and optionally applies a logging
channel,
* instrumentation, context, a component or service manager,
configuration, parameters,
* lifecycle extensions, initialization, and execution phases based on the
interfaces
* implemented by the component class.
*
* @return the new instance
* @exception of
*/
public Object newInstance()
throws Exception
{
final Object component = m_componentClass.newInstance();
if( getLogger().isDebugEnabled() )
{
final String message =
"ComponentFactory creating new instance of " +
m_componentClass.getName() + ".";
getLogger().debug( message );
}
if( component instanceof LogEnabled ||
component instanceof Loggable )
{
if( component instanceof LogEnabled )
{
ContainerUtil.enableLogging( component, m_componentLogger );
}
else
{
final String message = "WARNING: " +
m_componentClass.getName() +
" implements the Loggable lifecycle stage. This is " +
" a deprecated feature that will be removed in the
future. " +
" Please upgrade to using LogEnabled.";
getLogger().warn( message );
System.out.println( message );
final org.apache.log.Logger logkitLogger =
LogKit2AvalonLoggerAdapter.createLogger(
m_componentLogger );
( (Loggable)component ).setLogger( logkitLogger );
}
}
if( component instanceof InstrumentManageable )
{
( (InstrumentManageable)component ).setInstrumentManager(
m_instrumentManager );
}
ContainerUtil.contextualize( component, m_context );
ContainerUtil.compose( component, new WrapperComponentManager(
m_serviceManager ) );
ContainerUtil.service( component, m_serviceManager );
ContainerUtil.configure( component, m_configuration );
if( component instanceof Parameterizable )
{
Parameters parameters = Parameters.fromConfiguration(
m_configuration );
ContainerUtil.parameterize( component, parameters );
}
m_extManager.executeCreationExtensions( component, m_context );
ContainerUtil.initialize( component );
if( component instanceof Instrumentable )
{
final Instrumentable instrumentable = (Instrumentable)component;
instrumentable.setInstrumentableName( m_instrumentableName );
m_instrumentManager.registerInstrumentable(
instrumentable, m_instrumentableName );
}
ContainerUtil.start( component );
if( m_newInstance.isActive() )
{
m_newInstance.increment();
}
return component;
}
private Logger aquireLogger()
{
Logger logger;
final String name = ( m_configuration == null ? null :
m_configuration.getAttribute( "name", null ) );
if( null == name )
{
if( getLogger().isDebugEnabled() )
{
final String message = "no name attribute available, using
standard name";
getLogger().debug( message );
}
logger = m_loggerManager.getDefaultLogger();
}
else
{
if( getLogger().isDebugEnabled() )
{
final String message = "name attribute is " + name;
getLogger().debug( message );
}
logger = m_loggerManager.getLoggerForCategory( name );
}
return logger;
}
/**
* Returns the component class.
* @return the class
*/
public final Class getCreatedClass()
{
return m_componentClass;
}
/**
* Disposal of the supplied component instance.
* @param component the component to dispose of
* @exception Exception if a disposal error occurs
*/
public final void dispose( final Object component )
throws Exception
{
if( getLogger().isDebugEnabled() )
{
final String message = "ComponentFactory decommissioning instance
of " +
getCreatedClass().getName() + ".";
getLogger().debug( message );
}
if( getCreatedClass().equals( component.getClass() ) )
{
ContainerUtil.shutdown( component );
m_extManager.executeDestructionExtensions( component, m_context );
if( m_dispose.isActive() )
{
m_dispose.increment();
}
}
else
{
final String message = "The object given to be disposed does " +
"not come from this ObjectFactory";
throw new IllegalArgumentException( message );
}
}
/**
* Set the instrumentable name
* @param name the name
*/
public final void setInstrumentableName( String name )
{
// ignore
}
/**
* Returns the instrumentable name
* @return the name
*/
public final String getInstrumentableName()
{
return m_instrumentableName;
}
/**
* Returns the set of instruments assigned to the component factory.
* @return the instruments
*/
public final Instrument[] getInstruments()
{
return new Instrument[]
{
m_newInstance,
m_dispose
};
}
/**
* Returns the set of child instrumentables. The default implementation
* simply returns an empty instrumentable array.
* @return the instrumentables
*/
public final Instrumentable[] getChildInstrumentables()
{
return Instrumentable.EMPTY_INSTRUMENTABLE_ARRAY;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/ComponentHandler.java
Index: ComponentHandler.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.handler;
/**
* The ComponentHandler interface marks the ComponentHandler implementations.
* The desire for a ComponentHandler is to manage the instances of a
* Component.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
* @since 4.0
*/
public interface ComponentHandler
{
/**
* Actually prepare the handler and make it ready to
* handle component access.
*
* @exception Exception if unable to prepare handler
*/
void prepareHandler()
throws Exception;
/**
* Gets the current reference to a Component according to the policy of
* the implementation.
* @exception Exception if unable to ge tthe compoennt reference
*/
Object get() throws Exception;
/**
* Puts the reference back in the ComponentHandler according to the
* policy of the implementation.
* @param component the component to return to the handler
*/
void put( Object component );
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/FactoryComponentHandler.java
Index: FactoryComponentHandler.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.handler;
/**
* The FactoryComponentHandler to make sure components are initialized
* and destroyed correctly.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
* @since 4.0
*/
public final class FactoryComponentHandler
extends AbstractComponentHandler
{
/**
* Get a reference of the desired Component
* @exception Exception if arros occurs
*/
protected Object doGet()
throws Exception
{
return newComponent();
}
/**
* Return a reference of the desired Component
* @param componet the compoent to return to the handler
*/
protected void doPut( final Object component )
{
disposeComponent( component );
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/LEAwareComponentHandler.java
Index: LEAwareComponentHandler.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.handler;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.fortress.impl.LifecycleExtensionManager;
/**
* A ComponentHandler that delegates to underlying handler but also
* calls relevent Lifecycle Extension handlers at the right time.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Peter Donald</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
*/
public class LEAwareComponentHandler
implements ComponentHandler, Disposable
{
private final ComponentHandler m_componentHandler;
private final org.apache.avalon.fortress.impl.LifecycleExtensionManager
m_extManager;
private final Context m_context;
/**
* Creation of a new handler.
* @param componentHandler the handler
* @param extManager the extension manager
* @param context the context
*/
public LEAwareComponentHandler( final ComponentHandler componentHandler,
final
org.apache.avalon.fortress.impl.LifecycleExtensionManager extManager,
final Context context )
{
if( null == componentHandler )
{
throw new NullPointerException( "componentHandler" );
}
if( null == extManager )
{
throw new NullPointerException( "extManager" );
}
if( null == context )
{
throw new NullPointerException( "context" );
}
m_componentHandler = componentHandler;
m_extManager = extManager;
m_context = context;
}
/**
* Prepare the handler.
* @exception Exception if a handler preparation error occurs
*/
public void prepareHandler()
throws Exception
{
m_componentHandler.prepareHandler();
}
/**
* Retrieve the object and execute access extensions.
*
* @return the object
* @throws Exception if unable to aquire object
*/
public Object get() throws Exception
{
final Object object = m_componentHandler.get();
m_extManager.executeAccessExtensions( object, m_context );
return object;
}
/**
* Return component and execute Release extensions.
*
* @param component the component
*/
public void put( final Object component )
{
try
{
m_extManager.executeReleaseExtensions( component, m_context );
}
catch( Exception e )
{
// REVISIT(MC): we need to log this somewhere
}
m_componentHandler.put( component );
}
/**
* Disposal of the handler.
*/
public void dispose()
{
ContainerUtil.dispose( m_componentHandler );
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/PassThroughInvocationHandler.java
Index: PassThroughInvocationHandler.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.avalon.fortress.impl.handler;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* InvocationHandler that just passes on all methods to target object.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
*/
final class PassThroughInvocationHandler
implements InvocationHandler
{
/**
* The target object delegated to.
*/
private final Object m_object;
/**
* Create an Invocation handler for specified object.
*
* @param object the object to delegate to
*/
public PassThroughInvocationHandler( final Object object )
{
if( null == object )
{
throw new NullPointerException( "object" );
}
m_object = object;
}
/**
* Invoke the appropriate method on underlying object.
*
* @param proxy the proxy object
* @param meth the method
* @param args the arguments
* @return the return value of object
* @exception Throwable method throws an exception
*/
public Object invoke( final Object proxy,
final Method meth,
final Object[] args )
throws Throwable
{
try
{
return meth.invoke( m_object, args );
}
catch( final InvocationTargetException ite )
{
throw ite.getTargetException();
}
}
/**
* Retrieve the underlying object delegated to.
*
* @return the object delegated to
*/
Object getObject()
{
return m_object;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/PerThreadComponentHandler.java
Index: PerThreadComponentHandler.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.handler;
/**
* The ThreadSafeComponentHandler to make sure components are initialized
* and destroyed correctly.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
* @since 4.0
*/
public final class PerThreadComponentHandler
extends AbstractComponentHandler
{
private ThreadLocalComponent m_instance;
public void initialize()
throws Exception
{
super.initialize();
m_instance = new ThreadLocalComponent( this );
}
/**
* Get a reference of the desired Component
*/
protected Object doGet()
throws Exception
{
final Object instance = m_instance.get();
if( null == instance )
{
throw new IllegalStateException( "Instance is unavailable" );
}
return instance;
}
protected void doDispose()
{
disposeComponent( m_instance.get() );
m_instance = null;
}
private static final class ThreadLocalComponent
extends ThreadLocal
{
private final PerThreadComponentHandler m_handler;
protected ThreadLocalComponent( final PerThreadComponentHandler
handler )
{
m_handler = handler;
}
protected Object initialValue()
{
try
{
return m_handler.newComponent();
}
catch( final Exception e )
{
return null;
}
}
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/PoolableComponentHandler.java
Index: PoolableComponentHandler.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.handler;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.excalibur.mpool.Pool;
import org.apache.excalibur.mpool.PoolManager;
/**
* The PoolableComponentHandler to make sure components are initialized
* and destroyed correctly.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
* @since 4.0
*/
public final class PoolableComponentHandler
extends AbstractComponentHandler
implements Configurable
{
/** The instance of the PoolManager to create the Pool for the Handler */
private PoolManager m_poolManager;
/** The pool of components for <code>Poolable</code> Components */
private Pool m_pool;
/** The Config element for the poolable */
private int m_poolMin;
/**
* Application of suporting services to the handler.
* @param serviceManager the service manager
* @exception ServiceException if a service related error occurs
* @avalon.dependency type="PoolManager"
*/
public void service( final ServiceManager serviceManager )
throws ServiceException
{
super.service( serviceManager );
m_poolManager =
(PoolManager)serviceManager.lookup( PoolManager.ROLE );
}
/**
* Configuration of the handler under which the minimum pool size
* is established.
* @param configuration the configuration fragment
* @exception configuration exception if the supplied configuration
attribute
* for 'pool-min' cannot be resolved to an integer value
*/
public void configure( final Configuration configuration )
throws ConfigurationException
{
m_poolMin = configuration.getAttributeAsInteger( "pool-min", 10 );
}
/**
* Initialize the ComponentHandler.
* @exception Exception if an error occurs
*/
protected void doPrepare()
throws Exception
{
m_pool = m_poolManager.getManagedPool( m_factory, m_poolMin );
}
/**
* Get a reference of the desired Component
* @exception Exception if an error occurs
*/
protected Object doGet()
throws Exception
{
return m_pool.acquire();
}
/**
* Return a reference of the desired Component
* @param component the component to return to the handler
*/
protected void doPut( final Object component )
{
m_pool.release( component );
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/PrepareHandlerCommand.java
Index: PrepareHandlerCommand.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.handler;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.logger.NullLogger;
import org.apache.excalibur.event.command.Command;
import org.apache.avalon.fortress.impl.handler.ComponentHandler;
/**
* This is the command class to initialize a ComponentHandler
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
*/
public final class PrepareHandlerCommand implements Command
{
private final ComponentHandler m_handler;
private final Logger m_logger;
/**
* Creation of a new prepare handler command.
* @param handler the compoent handler
* @param logger the logging channel
*/
public PrepareHandlerCommand( final ComponentHandler handler,
final Logger logger )
{
m_handler = handler;
m_logger = ( null == logger ) ? new NullLogger() : logger;
}
/**
* Invoke execution of the handler
* @exception java.lang.Exception if a handler execution exception occurs
*/
public void execute()
throws Exception
{
try
{
m_handler.prepareHandler();
}
catch( final Exception e )
{
if( m_logger.isErrorEnabled() )
{
m_logger.error( "Could not prepare ComponentHandler", e );
}
throw e;
}
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/ProxyHelper.java
Index: ProxyHelper.java
===================================================================
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, 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 (INCLUDING, 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/>.
*/
package org.apache.avalon.fortress.impl.handler;
import java.io.Serializable;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.activity.Startable;
import org.apache.avalon.framework.activity.Suspendable;
import org.apache.avalon.framework.component.Component;
import org.apache.avalon.framework.component.Composable;
import org.apache.avalon.framework.component.Recomposable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Reconfigurable;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.context.Recontextualizable;
import org.apache.avalon.framework.logger.LogEnabled;
import org.apache.avalon.framework.logger.Loggable;
import org.apache.avalon.framework.parameters.Parameterizable;
import org.apache.avalon.framework.parameters.Reparameterizable;
import org.apache.avalon.framework.service.Serviceable;
/**
* Create a Component proxy. Requires JDK 1.3+
*
* @author <a href="mailto:[EMAIL PROTECTED]">Berin Loritsch</a>
* @author <a href="mailto:peter at apache.org">Peter Donald</a>
*/
final class ProxyHelper
{
/**
* The list interfaces that will not be proxied.
*/
private static final Class[] INVALID_INTERFACES = new Class[]
{
Loggable.class,
LogEnabled.class,
Contextualizable.class,
Recontextualizable.class,
Composable.class,
Recomposable.class,
Serviceable.class,
Configurable.class,
Reconfigurable.class,
Parameterizable.class,
Reparameterizable.class,
Initializable.class,
Startable.class,
Suspendable.class,
Disposable.class,
Serializable.class
};
/**
* Get the Component wrapped in the proxy.
* @param service the service object to proxy
* @exception Exception if a proxy establishment error occurs
*/
public static Component createProxy( Object service ) throws Exception
{
final Class clazz = service.getClass();
final Class[] workInterfaces = guessWorkInterfaces( clazz );
return (Component)Proxy.newProxyInstance( clazz.getClassLoader(),
workInterfaces,
new
PassThroughInvocationHandler( service ) );
}
/**
* Get the target object from specified proxy.
*
* @param proxy the proxy object
* @return the target object
* @throws Exception if unable to aquire target object,
* or specified object is not a proxy
*/
public static Object getObject( final Object proxy )
throws Exception
{
if( null == proxy )
{
throw new NullPointerException( "proxy" );
}
if( !Proxy.isProxyClass( proxy.getClass() ) )
{
final String message = "object is not a proxy";
throw new IllegalArgumentException( message );
}
final PassThroughInvocationHandler handler =
(PassThroughInvocationHandler)Proxy.getInvocationHandler( proxy );
return handler.getObject();
}
/**
* Get a list of interfaces to proxy by scanning through
* all interfaces a class implements and skipping invalid interfaces
* (as defined in [EMAIL PROTECTED] #INVALID_INTERFACES}).
*
* @param clazz the class
* @return the list of interfaces to proxy
*/
private static Class[] guessWorkInterfaces( final Class clazz )
{
final ArrayList list = new ArrayList();
guessWorkInterfaces( clazz, list );
list.add( Component.class );
return (Class[])list.toArray( new Class[ list.size() ] );
}
/**
* Get a list of interfaces to proxy by scanning through
* all interfaces a class implements and skipping invalid interfaces
* (as defined in [EMAIL PROTECTED] #INVALID_INTERFACES}).
*
* @param clazz the class
* @param list the list of current work interfaces
*/
private static void guessWorkInterfaces( final Class clazz,
final ArrayList list )
{
if( null != clazz )
{
final Class[] interfaces = clazz.getInterfaces();
boolean skip = false;
for( int i = 0; i < interfaces.length; i++ )
{
skip = false;
for( int j = 0; j < INVALID_INTERFACES.length; j++ )
{
if( interfaces[ i ] == INVALID_INTERFACES[ j ] )
{
skip = true;
continue;
}
}
if( !skip )
{
list.add( interfaces[ i ] );
}
}
guessWorkInterfaces( clazz.getSuperclass(), list );
}
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/ProxyObjectFactory.java
Index: ProxyObjectFactory.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.apache.avalon.fortress.impl.handler;
import org.apache.excalibur.mpool.ObjectFactory;
/**
* An ObjectFactory that delegates to another ObjectFactory
* and proxies results of that factory.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
*/
public class ProxyObjectFactory
implements ObjectFactory
{
/**
* The underlying object factory that this factory proxies.
*/
private final ObjectFactory m_objectFactory;
/**
* Create factory that delegates to specified factory.
*
* @param objectFactory the factory to delegate to
* @exception NullPointerException if the supplied object factory is null
*/
public ProxyObjectFactory( final ObjectFactory objectFactory ) throws
NullPointerException
{
if( null == objectFactory )
{
throw new NullPointerException( "objectFactory" );
}
m_objectFactory = objectFactory;
}
/**
* Create a new instance from delegated factory and proxy it.
*
* @return the proxied object
* @throws Exception if unable to create new instance
*/
public Object newInstance()
throws Exception
{
final Object object = m_objectFactory.newInstance();
return ProxyHelper.createProxy( object );
}
/**
* Return the class created by factory.
*
* @return the class created by factory.
*/
public Class getCreatedClass()
{
return m_objectFactory.getCreatedClass();
}
/**
* Dispose of objects created by this factory.
* Involves deproxying object and delegating to real ObjectFactory.
*
* @param object the proxied object
* @throws Exception if unable to dispose of object
*/
public void dispose( final Object object )
throws Exception
{
final Object target = ProxyHelper.getObject( object );
m_objectFactory.dispose( target );
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/ThreadSafeComponentHandler.java
Index: ThreadSafeComponentHandler.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.handler;
/**
* The ThreadSafeComponentHandler to make sure components are initialized
* and destroyed correctly.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:41 $
* @since 4.0
*/
public final class ThreadSafeComponentHandler
extends AbstractComponentHandler
{
private Object m_instance;
/**
* Initialize the ComponentHandler.
* @exception Exception if a handler preparation error occurs
*/
protected void doPrepare()
throws Exception
{
m_instance = newComponent();
}
/**
* Return instance for a get.
*
* @return the instance
* @exception Exception if a handler access error occurs
*/
protected Object doGet()
throws Exception
{
return m_instance;
}
/**
* Dispose of the ComponentHandler and any associated Pools and Factories.
*/
protected void doDispose()
{
disposeComponent( m_instance );
m_instance = null;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/handler/package.html
Index: package.html
===================================================================
<body>
<p>
The <code>handler</code> package includes the lifestyle support systems.
</p>
<p>
Note that although these handlers make use of the avalon lifecycle interfaces,
they are not 'real' components, and not every part of the lifecycle is
supported.
In particular, a handler doesn't start/stop or execute in any way.
</p>
<p>
The contents of this package are not a part of the fortress client API.
</p>
</body>
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/lookup/FortressServiceManager.java
Index: FortressServiceManager.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.lookup;
import java.util.Map;
import org.apache.avalon.framework.component.ComponentSelector;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.ServiceSelector;
import org.apache.avalon.framework.service.WrapperServiceSelector;
import org.apache.commons.collections.StaticBucketMap;
import org.apache.avalon.fortress.Container;
import org.apache.avalon.fortress.impl.handler.ComponentHandler;
/**
* This is the Default ServiceManager for the Container. It provides
* a very simple abstraction, and makes it easy for the Container to manage
* the references.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:42 $
*/
public class FortressServiceManager
implements ServiceManager
{
private final Container m_container;
private final Map m_used;
private final ServiceManager m_parent;
/**
* This constructor is for a ContainerComponentManager with a parent
* ComponentLocator
* @param container the impl
* @param parent the parent service manager
* @exception NullPointerException if the supplied impl is null
* @exception NullPointerException if the supplied parent is null
*/
public FortressServiceManager( final Container container,
final ServiceManager parent ) throws
NullPointerException
{
if( null == container )
{
throw new NullPointerException( "impl" );
}
if( null == parent )
{
throw new NullPointerException( "parent" );
}
m_parent = parent;
m_container = container;
m_used = new StaticBucketMap();
}
public Object lookup( final String key )
throws ServiceException
{
if( !m_container.has( key, null ) )
{
return m_parent.lookup( key );
}
final Object result = m_container.get( key, null );
if( result instanceof ServiceSelector )
{
return result;
}
if( result instanceof ComponentSelector )
{
return new WrapperServiceSelector( key, (ComponentSelector)result
);
}
if( !( result instanceof ComponentHandler ) )
{
final String message = "Invalid entry in component manager";
throw new ServiceException( key, message );
}
try
{
final ComponentHandler handler = (ComponentHandler)result;
final Object component = handler.get();
m_used.put( component, handler );
return component;
}
catch( final ServiceException ce )
{
throw ce; // rethrow
}
catch( final Exception e )
{
final String message =
"Could not return a reference to the Component";
throw new ServiceException( key, message, e );
}
}
public boolean hasService( final String key )
{
if( m_container.has( key, null ) )
{
return true;
}
else
{
return null != m_parent ? m_parent.hasService( key ) : false;
}
}
public void release( final Object component )
{
final ComponentHandler handler = (ComponentHandler)m_used.remove(
component );
if( null == handler )
{
if( null == m_parent )
{
/* This is a purplexing problem. SOmetimes the m_used hash
* returns null for the component--usually a ThreadSafe
* component. When there is no handler and no parent, that
* is an error condition--but if the component is usually
* ThreadSafe, the impact is essentially nill.
*/
//Pete: This occurs when objects are released more often than
//when they are aquired
//Pete: It also happens when a release of a ComponentSelector
occurs
}
else
{
m_parent.release( component );
}
}
else
{
handler.put( component );
}
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/lookup/FortressServiceSelector.java
Index: FortressServiceSelector.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.lookup;
import java.util.Map;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceSelector;
import org.apache.commons.collections.StaticBucketMap;
import org.apache.avalon.fortress.Container;
import org.apache.avalon.fortress.impl.handler.ComponentHandler;
/**
* This is the Default ServiceSelector for the Container. It provides
* a very simple abstraction, and makes it easy for the Container to manage
* the references.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:42 $
*/
public class FortressServiceSelector
implements ServiceSelector
{
private final String m_key;
private final Container m_container;
private final Map m_used;
/**
* Creation of new service selector.
* @param container the impl
* @param key a key
*/
public FortressServiceSelector( final Container container,
final String key )
{
if( null == container )
{
throw new NullPointerException( "impl" );
}
if( null == key )
{
throw new NullPointerException( "key" );
}
m_key = key;
m_container = container;
m_used = new StaticBucketMap();
}
public Object select( final Object hint )
throws ServiceException
{
try
{
final ComponentHandler handler = getHandler( hint );
final Object component = handler.get();
m_used.put( component, handler );
return component;
}
catch( final ServiceException ce )
{
throw ce; // rethrow
}
catch( final Exception e )
{
final String name = m_key + "/" + hint.toString();
final String message = "Could not return a reference to the
Component";
throw new ServiceException( name, message, e );
}
}
public boolean isSelectable( final Object hint )
{
return m_container.has( m_key, hint );
}
public void release( Object component )
{
final ComponentHandler handler =
(ComponentHandler)m_used.remove( component );
if( null != handler )
{
handler.put( component );
}
}
private ComponentHandler getHandler( final Object hint )
throws ServiceException
{
if( null == hint )
{
final String message = "hint cannot be null";
throw new IllegalArgumentException( message );
}
final ComponentHandler handler =
(ComponentHandler)m_container.get( m_key, hint );
if( null == handler )
{
final String message =
"The hint does not exist in the ComponentSelector";
throw new ServiceException( m_key + "/" + hint.toString(),
message );
}
return handler;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/lookup/package.html
Index: package.html
===================================================================
<body>
<p>
The <code>lookup</code> package includes a service manager and selector then
implements the ECM lookup policies.
</p>
<p>
The contents of this package are not a part of the fortress client API.
</p>
</body>
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/role/AbstractRoleManager.java
Index: AbstractRoleManager.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.role;
import java.util.Hashtable;
import java.util.Map;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.fortress.impl.handler.PerThreadComponentHandler;
/**
* The Excalibur Role Manager is used for Excalibur Role Mappings. All of
* the information is hard-coded.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:42 $
* @since 4.1
*/
public abstract class AbstractRoleManager
extends AbstractLogEnabled
implements org.apache.avalon.fortress.RoleManager
{
/**
* The classloader
*/
private final ClassLoader m_loader;
/**
* Map for shorthand to RoleEntry
*/
private java.util.Map m_shorthands = new java.util.Hashtable();
/**
* Map for classname to RoleEntry
*/
private java.util.Map m_classnames = new java.util.Hashtable();
/**
* Parent <code>RoleManager</code> for nested resolution
*/
private final org.apache.avalon.fortress.RoleManager m_parent;
/**
* Default constructor--this RoleManager has no parent.
*/
public AbstractRoleManager()
{
this( null );
}
/**
* Alternate constructor--this RoleManager has the specified
* parent.
*
* @param parent The parent <code>RoleManager</code>.
*/
public AbstractRoleManager( final org.apache.avalon.fortress.RoleManager
parent )
{
this( parent, Thread.currentThread().getContextClassLoader() );
}
/**
* Alternate constructor--this RoleManager has the specified
* parent.
*
* @param parent The parent <code>RoleManager</code>.
*/
public AbstractRoleManager( final org.apache.avalon.fortress.RoleManager
parent,
final ClassLoader loader )
{
ClassLoader thisLoader = loader;
if( null == thisLoader )
{
thisLoader = Thread.currentThread().getContextClassLoader();
}
m_loader = thisLoader;
m_parent = parent;
}
/**
* Addition of a role to the role manager.
* @param shortName the shor name for the role
* @param role the role
* @param classname the class name
* @param handlerClassName the handler classname
*/
protected void addRole( final String shortName,
final String role,
final String className,
final String handlerClassName )
{
final Class clazz;
Class handlerKlass;
if( getLogger().isDebugEnabled() )
{
getLogger().debug( "addRole role: name='" + shortName + "',
role='" + role + "', "
+ "class='" + className + "', handler='" +
handlerClassName + "'" );
}
try
{
clazz = m_loader.loadClass( className );
}
catch( final Exception e )
{
final String message =
"Unable to load class " + className + ". Skipping.";
getLogger().warn( message );
// Do not store reference if class does not exist.
return;
}
if( null != handlerClassName )
{
try
{
handlerKlass = m_loader.loadClass( handlerClassName );
}
catch( final Exception e )
{
final String message = "Unable to load handler " +
handlerClassName + " for class " + className + ".
Skipping.";
getLogger().warn( message );
return;
}
}
else
{
handlerKlass = guessHandlerFor( clazz );
}
final org.apache.avalon.fortress.RoleEntry entry = new
org.apache.avalon.fortress.RoleEntry( role, shortName, clazz, handlerKlass );
m_shorthands.put( shortName, entry );
m_classnames.put( className, entry );
}
protected Class guessHandlerFor( final Class clazz )
{
return
org.apache.avalon.fortress.impl.handler.PerThreadComponentHandler.class;
}
public org.apache.avalon.fortress.RoleEntry getRoleForClassname( final
String classname )
{
final org.apache.avalon.fortress.RoleEntry roleEntry =
(org.apache.avalon.fortress.RoleEntry)m_classnames.get( classname );
if( null != roleEntry )
{
return roleEntry;
}
else if( null != m_parent )
{
return m_parent.getRoleForClassname( classname );
}
else
{
return null;
}
}
/**
* Return a role name relative to a supplied short name
* @param shortname the short name
* @return the role entry
*/
public org.apache.avalon.fortress.RoleEntry getRoleForShortName( final
String shortname )
{
final org.apache.avalon.fortress.RoleEntry roleEntry =
(org.apache.avalon.fortress.RoleEntry)m_shorthands.get( shortname );
if( null != roleEntry )
{
return roleEntry;
}
else if( null != m_parent )
{
return m_parent.getRoleForShortName( shortname );
}
else
{
return null;
}
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/role/ConfigurableRoleManager.java
Index: ConfigurableRoleManager.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.role;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.fortress.impl.handler.PerThreadComponentHandler;
/**
* Configurable RoleManager implementation. It populates the RoleManager
* from a configuration hierarchy. This is based on the DefaultRoleManager
* in the org.apache.avalon.component package.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:42 $
* @since 4.1
*/
public class ConfigurableRoleManager
extends org.apache.avalon.fortress.impl.role.AbstractRoleManager
implements Configurable
{
/**
* Default constructor--this RoleManager has no parent.
*/
public ConfigurableRoleManager()
{
super( null );
}
/**
* Alternate constructor--this RoleManager has the specified
* parent.
*
* @param parent The parent <code>RoleManager</code>.
*/
public ConfigurableRoleManager( org.apache.avalon.fortress.RoleManager
parent )
{
super( parent, null );
}
/**
* Alternate constructor--this RoleManager has the specified
* parent and a classloader.
*
* @param parent The parent <code>RoleManager</code>.
* @param loader the classloader
*/
public ConfigurableRoleManager( org.apache.avalon.fortress.RoleManager
parent, ClassLoader loader )
{
super( parent, loader );
}
/**
* Reads a configuration object and creates the role, shorthand,
* and class name mapping.
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
public final void configure( final Configuration configuration )
throws ConfigurationException
{
final Configuration[] roles = configuration.getChildren( "role" );
for( int i = 0; i < roles.length; i++ )
{
final String role = roles[ i ].getAttribute( "name" );
Configuration[] components = roles[ i ].getChildren( "component"
);
for( int j = 0; j < components.length; j++ )
{
final String shorthand = components[ j ].getAttribute(
"shorthand" );
final String className =
components[ j ].getAttribute( "class", null );
final String handlerClassName =
components[ j ].getAttribute( "handler",
org.apache.avalon.fortress.impl.handler.PerThreadComponentHandler.class.getName()
);
addRole( shorthand, role, className, handlerClassName );
}
}
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/role/FortressRoleManager.java
Index: FortressRoleManager.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.impl.role;
import org.apache.avalon.framework.activity.Initializable;
/**
* The Excalibur Role Manager is used for Excalibur Role Mappings. All of
* the information is hard-coded.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:42 $
*/
public class FortressRoleManager
extends org.apache.avalon.fortress.impl.role.AbstractRoleManager
implements Initializable
{
/**
* Default constructor--this RoleManager has no parent.
*/
public FortressRoleManager()
{
this( null );
}
/**
* Alternate constructor--this RoleManager has the specified
* parent.
*
* @param parent The parent <code>RoleManager</code>.
*/
public FortressRoleManager( org.apache.avalon.fortress.RoleManager parent
)
{
this( parent, null );
}
/**
* Alternate constructor--this RoleManager has the specified
* parent and a classloader.
*
* @param parent The parent <code>RoleManager</code>.
* @param loader the classloader
*/
public FortressRoleManager( org.apache.avalon.fortress.RoleManager
parent, ClassLoader loader )
{
super( parent, loader );
}
/**
* Initialize the role manager.
*/
public void initialize()
{
/* Set up Cache relations */
addRole( "cache",
"org.apache.excalibur.cache.Cache",
"org.apache.excalibur.cache.impl.DefaultCache",
"org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler" );
addRole( "lru-cache",
"org.apache.excalibur.cache.Cache",
"org.apache.excalibur.cache.impl.LRUCache",
"org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler" );
/* Set up DataSource relations */
addRole( "jdbc-datasource",
"org.apache.avalon.excalibur.datasource.DataSourceComponent",
"org.apache.avalon.excalibur.datasource.JdbcDataSource",
"org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler" );
addRole( "j2ee-datasource",
"org.apache.avalon.excalibur.datasource.DataSourceComponent",
"org.apache.avalon.excalibur.datasource.J2eeDataSource",
"org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler" );
addRole( "informix-datasource",
"org.apache.avalon.excalibur.datasource.DataSourceComponent",
"org.apache.avalon.excalibur.datasource.InformixDataSource",
"org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler" );
/* Set up i18n relations */
addRole( "i18n",
"org.apache.excalibur.xmlbundle.BundleSelector",
"org.apache.excalibur.xmlbundle.BundleSelector",
"org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler" );
/* Set up Monitor relations */
addRole( "monitor",
"org.apache.avalon.excalibur.monitor.Monitor",
"org.apache.avalon.excalibur.monitor.ActiveMonitor",
"org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler" );
addRole( "passive-monitor",
"org.apache.avalon.excalibur.monitor.Monitor",
"org.apache.avalon.excalibur.monitor.PassiveMonitor",
"org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler" );
/* Set up XPath relations */
addRole( "xalan-xpath",
"org.apache.excalibur.xml.xpath.XPathProcessor",
"org.apache.excalibur.xml.xpath.XPathProcessorImpl",
"org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler" );
addRole( "jaxpath",
"org.apache.excalibur.xml.xpath.XPathProcessor",
"org.apache.excalibur.xml.xpath.JaxenProcessorImpl",
"org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler" );
/* Set up SourceResolver relations */
addRole( "resolver",
"org.apache.excalibur.source.SourceResolver",
"org.apache.excalibur.source.impl.SourceResolverImpl",
"org.apache.avalon.fortress.impl.handler.ThreadSafeComponentHandler" );
/* Set up XML parser relations */
addRole( "parser",
"org.apache.excalibur.xml.dom.DOMParser",
"org.apache.excalibur.xml.impl.JaxpParser",
"org.apache.avalon.fortress.impl.handler.PerThreadComponentHandler" );
addRole( "xerces-parser",
"org.apache.excalibur.xml.dom.DOMParser",
"org.apache.excalibur.xml.impl.XercesParser",
"org.apache.avalon.fortress.impl.handler.FactoryComponentHandler" );
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/impl/role/package.html
Index: package.html
===================================================================
<body>
<p>
The <code>role</code> package includes classes and interfaces supporting the
ECM role abstraction.
</p>
<p>
The contents of this package are not a part of the fortress client API.
</p>
</body>
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/util/CachedArrayList.java
Index: CachedArrayList.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.util;
import java.util.List;
import java.util.Collections;
import java.util.Iterator;
/**
* <code>CachedArrayList</code> class.
*
* <p>
* This class wraps a synchronized ArrayList to provide an optimized
* <code>toArray()</code> method that returns an internally cached array,
* rather than a new array generated per <code>toArray()</code>
* invocation.
* </p>
*
* <p>
* Use of the class by the Manager results in <code>toArray()</code>
* being invoked far more often than any other method. Caching the value
* <code>toArray</code> normally returns is intended to be a performance
* optimization.
* </p>
*
* <p>
* The cached array value is updated upon each write operation to the
* List.
* </p>
*
* <p>
* @todo(MC) investigate using FastArrayList from collections ?
* </p>
*/
public final class CachedArrayList
{
// Empty array constant
private final Object[] EMPTY_ARRAY = new Object[ 0 ];
// Actual list for storing elements
private final List m_proxy = Collections.synchronizedList( new
java.util.ArrayList() );
// Proxy cache, saves unnecessary conversions from List to Array
private Object[] m_cache = EMPTY_ARRAY;
/**
* Add an object to the list
*
* @param object an <code>Object</code> value
*/
public void add( final Object object )
{
m_proxy.add( object );
m_cache = m_proxy.toArray();
}
/**
* Insert an object into a particular position in the list
*
* @param position an <code>int</code> value
* @param object an <code>Object</code> value
*/
public void insert( final int position, final Object object )
{
m_proxy.add( position, object );
m_cache = m_proxy.toArray();
}
/**
* Remove an object from the list
*
* @param position an <code>int</code> value
* @return a <code>Object</code> value
*/
public Object remove( final int position )
{
final Object object = m_proxy.remove( position );
m_cache = m_proxy.toArray();
return object;
}
/**
* Obtain an iterator
*
* @return an <code>Iterator</code> value
*/
public Iterator iterator()
{
return m_proxy.iterator();
}
/**
* Obtain the size of the list
*
* @return an <code>int</code> value
*/
public int size()
{
return m_proxy.size();
}
/**
* Access an object that is in the list
*
* @param index an <code>int</code> value
* @return a <code>Object</code> value
*/
public Object get( final int index )
{
return m_proxy.get( index );
}
/**
* Find out the index of an object in the list
*
* @param object an <code>Object</code> value
* @return an <code>int</code> value
*/
public int indexOf( final Object object )
{
return m_proxy.indexOf( object );
}
/**
* Clear the list
*/
public void clear()
{
m_proxy.clear();
m_cache = EMPTY_ARRAY;
}
/**
* Obtain the list as an array. Subsequents calls to this method
* will return the same array object, until a write operation is
* performed on the list.
*
* @return an <code>Object[]</code> value
*/
public Object[] toArray()
{
return m_cache;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/util/CompositeException.java
Index: CompositeException.java
===================================================================
package org.apache.avalon.fortress.util;
/**
* This is an exception made up of one or more subexceptions.
*/
public class CompositeException extends Exception
{
private final Exception[] m_ex;
private final String m_message;
public CompositeException( Exception[] ex )
{
this( ex, null );
}
public CompositeException( Exception[] ex, String message )
{
m_ex = ex;
if( ex == null || ex.length < 1)
{
throw new IllegalArgumentException( "you must specify a contained
exception!" );
}
if( message == null )
{
final StringBuffer msg = new StringBuffer();
for( int i = 0; i < ex.length; i++ )
{
msg.append( ex[i].getMessage() );
}
m_message = msg.toString();
}
else
m_message = message;
}
public Exception[] getExceptions()
{
return m_ex;
}
public String toString()
{
return m_message;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/util/ContextBuilder.java
Index: ContextBuilder.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.util;
import java.io.File;
import org.apache.avalon.excalibur.logger.LoggerManager;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.excalibur.event.Queue;
import org.apache.avalon.fortress.RoleManager;
import org.apache.excalibur.instrument.InstrumentManager;
import org.apache.excalibur.mpool.PoolManager;
/**
* Helper class to create a context for the ContextManager.
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:42 $
*/
public class ContextBuilder
implements ContextManagerConstants
{
private final FortressConfig m_config;
/**
* Creates a context builder and initializes it with default values.
* The default values are:
*
* <ul>
* <li>CONTAINER_CLASS =
"org.apache.avalon.fortress.impl.DefaultContainer" </li>
* <li>THREADS_CPU = 2</li>
* <li>THREAD_TIMEOUT = 1000</li>
* <li>CONTEXT_DIRECTORY = "../"</li>
* <li>WORK_DIRECTORY = "/tmp"</li>
* <li>LOG_CATEGORY = "fortress"</li>
* <li>CONTEXT_CLASSLOADER = the thread context class loader</li>
* </ul>
*/
public ContextBuilder()
{
m_config = new FortressConfig();
}
/**
* Creates a context builder and initializes it with default values.
*
* @param parent parent context with default values.
*/
public ContextBuilder( final Context parent )
{
m_config = new FortressConfig( parent );
}
/**
* Creates a default context.
* @return a context
*/
public static final Context createDefaultContext()
{
return FortressConfig.createDefaultConfig();
}
/**
* Creates a default context.
* @return a context
*/
public static final Context createDefaultContext( ClassLoader classLoader
)
{
return FortressConfig.createDefaultConfig( classLoader );
}
/**
* Finalizes the context and returns it.
* @return a context
*/
public Context getContext()
{
return m_config.getContext();
}
public ContextBuilder setCommandQueue( Queue commandQueue )
{
m_config.setCommandQueue( commandQueue );
return this;
}
public ContextBuilder setServiceManagerParent( ServiceManager
serviceManager )
{
m_config.setServiceManagerParent( serviceManager );
return this;
}
public ContextBuilder setServiceManager( ServiceManager serviceManager )
{
m_config.setServiceManager( serviceManager );
return this;
}
public ContextBuilder setContainerClass( String containerClass )
throws ClassNotFoundException
{
m_config.setContainerClass( containerClass );
return this;
}
public ContextBuilder setContainerClass( Class containerClass )
{
m_config.setContainerClass( containerClass );
return this;
}
public ContextBuilder setContainerConfiguration( Configuration config )
{
m_config.setContainerConfiguration( config );
return this;
}
public ContextBuilder setContainerConfiguration( String location )
{
m_config.setContainerConfiguration( location );
return this;
}
public ContextBuilder setAssemblyConfiguration( Configuration config )
{
m_config.setAssemblyConfiguration( config );
return this;
}
public ContextBuilder setAssemblyConfiguration( String location )
{
m_config.setAssemblyConfiguration( location );
return this;
}
public ContextBuilder setContextClassLoader( ClassLoader loader )
{
m_config.setContextClassLoader( loader );
return this;
}
public ContextBuilder setContextDirectory( File file )
{
m_config.setContextDirectory( file );
return this;
}
public ContextBuilder setContextDirectory( String directory )
{
m_config.setContextDirectory( directory );
return this;
}
public ContextBuilder setLoggerCategory( String category )
{
m_config.setLoggerCategory( category );
return this;
}
public ContextBuilder setLoggerManager( LoggerManager logManager )
{
m_config.setLoggerManager( logManager );
return this;
}
public ContextBuilder setLoggerManagerConfiguration( Configuration config
)
{
m_config.setLoggerManagerConfiguration( config );
return this;
}
public ContextBuilder setLoggerManagerConfiguration( String location )
{
m_config.setLoggerManagerConfiguration( location );
return this;
}
public ContextBuilder setInstrumentManager( InstrumentManager profiler )
{
m_config.setInstrumentManager( profiler );
return this;
}
public ContextBuilder setInstrumentManagerConfiguration( Configuration
config )
{
m_config.setInstrumentManagerConfiguration( config );
return this;
}
public ContextBuilder setInstrumentManagerConfiguration( String location )
{
m_config.setInstrumentManagerConfiguration( location );
return this;
}
public ContextBuilder setNumberOfThreadsPerCPU( int numberOfThreads )
{
m_config.setNumberOfThreadsPerCPU( numberOfThreads );
return this;
}
public ContextBuilder setPoolManager( PoolManager poolManager )
{
m_config.setPoolManager( poolManager );
return this;
}
public ContextBuilder setRoleManager(
org.apache.avalon.fortress.RoleManager roleManager )
{
m_config.setRoleManager( roleManager );
return this;
}
public ContextBuilder setRoleManagerConfiguration( Configuration config )
{
m_config.setRoleManagerConfiguration( config );
return this;
}
public ContextBuilder setRoleManagerConfiguration( String location )
{
m_config.setRoleManagerConfiguration( location );
return this;
}
public ContextBuilder setThreadTimeout( long timeout )
{
m_config.setThreadTimeout( timeout );
return this;
}
public ContextBuilder setWorkDirectory( File file )
{
m_config.setWorkDirectory( file );
return this;
}
public ContextBuilder setWorkDirectory( String directory )
{
m_config.setWorkDirectory( directory );
return this;
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/util/ContextManager.java
Index: ContextManager.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import org.apache.avalon.excalibur.logger.LogKitLoggerManager;
import org.apache.avalon.excalibur.logger.LoggerManager;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.DefaultContext;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.LogKitLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.service.DefaultServiceManager;
import org.apache.avalon.framework.service.DefaultServiceSelector;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.excalibur.event.Queue;
import org.apache.excalibur.event.Sink;
import org.apache.excalibur.event.command.CommandManager;
import org.apache.excalibur.event.command.TPCThreadManager;
import org.apache.excalibur.event.command.ThreadManager;
import org.apache.avalon.fortress.impl.role.ConfigurableRoleManager;
import org.apache.avalon.fortress.impl.role.FortressRoleManager;
import org.apache.avalon.fortress.RoleManager;
import org.apache.excalibur.instrument.InstrumentManager;
import org.apache.excalibur.instrument.manager.DefaultInstrumentManager;
import org.apache.excalibur.mpool.DefaultPoolManager;
import org.apache.excalibur.mpool.PoolManager;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceResolver;
import org.apache.excalibur.source.impl.ResourceSourceFactory;
import org.apache.excalibur.source.impl.SourceResolverImpl;
import org.apache.log.Hierarchy;
import org.apache.log.Priority;
/**
* <p>The ContextManager is used to manage the values in a Container's
* Context. The ContainerManager uses this helper class to create the
* initial context for the Container. Its purpose is to add the default
* values, and give convenient methods to override those defaults. Once you
* get an instance of the Context, it is made read-only and returned. No
* further operations will be possible on it.</p>
*
* <p>You can get two different contexts from the ContextManager: the child
* context and the impl m_manager context. The former contains all
* managers, such as the pool m_manager etc. necessary for a child impl to
* create additional child containers. The impl m_manager context contains
* all of the child context, but also initialization parameters for the
* impl, such as a Configuration object, a ComponentLocator, etc., that
* the impl wants, but does not want to pass on to its children.</p>
*
* <p>You would typically use the impl m_manager context to initialize
* the impl m_manager, and let it pass the child context on to the
* impl.</p>
*
* <p>The ContextManager will sometimes create new components, such as a
* component m_manager, a pool m_manager, etc. It will manage these components
* and dispose of them properly when it itself is disposed .</p>
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:42 $
* @since 4.1
*/
public class ContextManager
implements ContextManagerConstants, Initializable, Disposable
{
private static final Configuration EMPTY_CONFIG;
static
{
DefaultConfiguration config =
new DefaultConfiguration( "", "", "", "" );
config.makeReadOnly();
EMPTY_CONFIG = config;
}
/**
* The root context.
*/
private final Context m_rootContext;
/**
* The context of the new impl. This context has the rootContext
* as its parent. Put everything here that you want the new impl
* to have in its own context.
*/
private final DefaultContext m_childContext;
/**
* Container m_manager's context. This context has the child context
* as parent. Put things here that you want the impl m_manager
* to see, but do not wish to expose to the impl.
*/
private final DefaultContext m_containerManagerContext;
/**
* New context passed in, maybe from a FortressConfig.
* This context may not have objects, but rather URI's or
* other pointers. The ContextManager inspects it for
* elements it can use to create component managers etc.
*/
private Logger m_logger;
private final Logger m_primordialLogger;
private ServiceManager m_manager;
/**
* The components that are "owned" by this context and should
* be disposed by it. Any m_manager that is created as a result
* of it not being in the rootContext, or having been created
* by the ContextManager should go in here.
*/
private final ArrayList ownedComponents = new ArrayList();
/**
* The ConfigurationBuilder is instantiated lazilly in getConfiguration
* to avoid LinkageErrors in some environments.
*/
private DefaultConfigurationBuilder configBuilder;
/**
* Create a new ContextManager.
*
* @param rootContext the default values.
* @param logger logger to use when creating new components.
*/
public ContextManager( Context rootContext, Logger logger )
{
m_rootContext = rootContext;
m_childContext = new OverridableContext( m_rootContext );
m_containerManagerContext = new OverridableContext( m_childContext );
m_logger = logger;
// The primordial logger is used for all output up until the point
where
// the logger m_manager has been initialized. However it is set into
// two objects used to load the configuration resource files within
// the ContextManager. Any problems loading these files will result
in
// warning or error messages. However in most cases, the debug
// information should not be displayed, so turn it off by default.
// Unfortunately, there is not a very good place to make this
settable.
m_primordialLogger = new ConsoleLogger( ConsoleLogger.LEVEL_INFO );
}
/**
* Method to assume ownership of one of the managers the
* <code>ContextManager</code> created. Ownership means that the
* <code>ContextManager</code> is responsible for destroying the
* m_manager when the <code>ContextManager</code> is destroyed.
*
* FIXME: We should throw a NullPointerException instead.
*
* @param o The object being claimed
*
* @throws IllegalArgumentException if the object is null.
*/
private void assumeOwnership( Object o )
{
if( o == null )
{
throw new IllegalArgumentException( "Can not assume ownership of
a null!" );
}
ownedComponents.add( o );
}
/**
* Initialize the <code>ContextManager</code>. This will cause the
* <code>ContextManager</code> to create any managers it needs.
*
* @throws Exception if there is a problem at any point in the
* initialization.
*/
public void initialize() throws Exception
{
initializeOwnComponentManager();
initializeLoggerManager();
initializeRoleManager();
initializeServiceManager();
initializeCommandQueue();
initializePoolManager();
initializeContext();
initializeInstrumentManager();
initializeConfiguration();
m_childContext.makeReadOnly();
m_containerManagerContext.makeReadOnly();
}
/**
* Load the configuration file that the Container will need to operate.
*
* @throws Exception if the configuration cannot be loaded
*/
protected void initializeConfiguration() throws Exception
{
try
{
m_containerManagerContext.put( CONFIGURATION, m_rootContext.get(
CONFIGURATION ) );
}
catch( ContextException ce )
{
Configuration containerConfig = getConfiguration( CONFIGURATION,
CONFIGURATION_URI );
if( containerConfig == null )
{
// No config.
// Does the parent supply a logger m_manager?
try
{
m_containerManagerContext.get( CONFIGURATION );
// OK, done.
return;
}
catch( ContextException cex )
{
// Guess there is none.
return;
}
}
else
{
m_containerManagerContext.put( CONFIGURATION, containerConfig
);
}
}
}
/**
* Initialize the context that will be passed into the impl.
*
* @throws Exception if any of the parameters cannot be copied properly.
*/
protected void initializeContext() throws Exception
{
copyEntry( CONTAINER_CLASS );
try
{
copyEntry( PARAMETERS );
}
catch( ContextException ce )
{/* ignore this exception */
}
}
/**
* Copies the specified entry from the <code>rootContext</code> to the
* <code>containerManagerContext</code>.
*
* @throws ContextException if the parameter does not exist
*/
protected void copyEntry( String key ) throws ContextException
{
m_containerManagerContext.put( key, m_rootContext.get( key ) );
}
/**
* Disposes all items that this ContextManager has created.
*/
public void dispose()
{
Collections.sort( ownedComponents, new DestroyOrderComparator() );
// Dispose owned components
Iterator ownedComponentsIter = ownedComponents.iterator();
while( ownedComponentsIter.hasNext() )
{
Object o = ownedComponentsIter.next();
try
{
if (getLogger().isDebugEnabled()) getLogger().debug("Shutting
down: " + o);
ContainerUtil.shutdown( o );
if (getLogger().isDebugEnabled()) getLogger().debug("Done.");
}
catch( Exception e )
{
getLogger().warn( "Unable to dispose of owned component "
+ o.getClass().getName(), e );
}
ownedComponentsIter.remove();
}
}
/**
* Convenience method to obtain a value, or defer to a default if it does
* not exist.
*
* @param context The context object we intend to get a value from.
* @param key The key we want to use to get the value.
* @param defaultValue The default value we return if the key does not
* exist.
*/
protected Object get( Context context, String key, Object defaultValue )
{
try
{
return context.get( key );
}
catch( ContextException ce )
{
return defaultValue;
}
}
/**
* Will set up a ServiceLocator if none is supplied.
*
* <p>The postcondition is that
* <code>childContext.get( Container.SERVICE_MANAGER )</code> should
* return a valid logger m_manager.</p>
*
* @throws Exception if the ServiceManager could not be instantiated.
*/
protected void initializeServiceManager() throws Exception
{
try
{
m_childContext.put( SERVICE_MANAGER, m_rootContext.get(
SERVICE_MANAGER ) );
return;
}
catch( ContextException ce )
{
}
// See if we can inherit from the parent...
try
{
m_childContext.get( SERVICE_MANAGER );
// OK, done.
return;
}
catch( ContextException ce )
{
// No ComponentLocator available anywhere. (Set one up.)
}
final ServiceManager parent = (ServiceManager)get( m_rootContext,
SERVICE_MANAGER_PARENT, null );
if( null != parent )
{
ServiceManager sm = new DefaultServiceManager( parent );
assumeOwnership( sm );
m_containerManagerContext.put( SERVICE_MANAGER, sm );
}
}
/**
* Set up the CommandQueue to enable asynchronous management.
*
* @throws Exception if the <code>CommandQueue</code> could not be
* created.
*/
protected void initializeCommandQueue() throws Exception
{
try
{
m_childContext.put( Queue.ROLE, m_rootContext.get( Queue.ROLE ) );
return;
}
catch( ContextException ce )
{
}
try
{
m_childContext.get( Queue.ROLE );
return;
}
catch( ContextException ce )
{
}
// No CommandQueue specified, create a default one
m_childContext.put( Queue.ROLE, createCommandSink() );
}
/**
* Helper method for creating a default CommandQueue
*
* @return a default <code>CommandQueue</code>
* @throws Exception if an error occurs
*/
private Sink createCommandSink() throws Exception
{
final CommandManager cm = new CommandManager();
final ThreadManager tm = new TPCThreadManager();
assumeOwnership( cm );
assumeOwnership( tm );
// Get the context Logger Manager
LoggerManager loggerManager = (LoggerManager)m_childContext.get(
LoggerManager.ROLE );
// Get the logger for the thread m_manager
Logger tmLogger = loggerManager.getLoggerForCategory(
"system.threadmgr" );
ContainerUtil.enableLogging( tm, tmLogger );
ContainerUtil.parameterize( tm, buildCommandQueueConfig() );
ContainerUtil.initialize( tm );
tm.register( cm );
return cm.getCommandSink();
}
/**
* Helper method for creating ThreadManager configuration.
*
* @return ThreadManager configuration as a <code>Parameters</code>
* instance
*/
private Parameters buildCommandQueueConfig()
{
final Parameters p = new Parameters();
Integer threadsPerProcessor;
Long threadBlockTimeout;
try
{
Integer processors = (Integer)m_rootContext.get( "processors" );
p.setParameter( "processors", processors.toString() );
}
catch( ContextException e )
{
}
try
{
threadsPerProcessor = (Integer)m_rootContext.get( THREADS_CPU );
}
catch( ContextException e )
{
threadsPerProcessor = new Integer( 2 );
}
p.setParameter( "threads-per-processor",
threadsPerProcessor.toString() );
try
{
threadBlockTimeout = (Long)m_rootContext.get( THREAD_TIMEOUT );
}
catch( ContextException e )
{
threadBlockTimeout = new Long( 1000 );
}
p.setParameter( "block-timeout", threadBlockTimeout.toString() );
return p;
}
/**
* Set up the Pool Manager for the managed pool.
*
* @throws Exception if there is an error.
*/
protected void initializePoolManager() throws Exception
{
try
{
m_childContext.put( PoolManager.ROLE, m_rootContext.get(
PoolManager.ROLE ) );
return;
}
catch( ContextException ce )
{
}
PoolManager pm = new DefaultPoolManager( (Sink)m_childContext.get(
Queue.ROLE ) );
assumeOwnership( pm );
m_childContext.put( PoolManager.ROLE, pm );
}
/**
* Set up the RoleManager for the Container.
*
* @throws Exception if there is an error.
*/
protected void initializeRoleManager() throws Exception
{
try
{
m_childContext.put( org.apache.avalon.fortress.RoleManager.ROLE,
m_rootContext.get( org.apache.avalon.fortress.RoleManager.ROLE ) );
return;
}
catch( ContextException ce )
{
}
Configuration roleConfig =
getConfiguration( ROLE_MANAGER_CONFIGURATION,
ROLE_MANAGER_CONFIGURATION_URI );
if( roleConfig == null )
{
// See if we can inherit from the parent...
try
{
m_childContext.get(
org.apache.avalon.fortress.RoleManager.ROLE );
// OK, done.
return;
}
catch( ContextException ce )
{
// No RoleManager available anywhere.
roleConfig = EMPTY_CONFIG;
}
}
// Get the context Logger Manager
LoggerManager loggerManager = (LoggerManager)m_childContext.get(
LoggerManager.ROLE );
// Create a logger for the role m_manager
Logger rmLogger = loggerManager.getLoggerForCategory(
roleConfig.getAttribute( "logger", "system.roles" ) );
// Lookup the context class loader
ClassLoader classLoader = (ClassLoader)m_containerManagerContext.get(
ClassLoader.class.getName() );
// Create a parent role m_manager with all the default roles
org.apache.avalon.fortress.impl.role.FortressRoleManager erm = new
org.apache.avalon.fortress.impl.role.FortressRoleManager( null, classLoader );
erm.enableLogging( rmLogger.getChildLogger( "defaults" ) );
erm.initialize();
// Create a role m_manager with the configured roles
org.apache.avalon.fortress.impl.role.ConfigurableRoleManager rm = new
org.apache.avalon.fortress.impl.role.ConfigurableRoleManager( erm, classLoader
);
rm.enableLogging( rmLogger );
rm.configure( roleConfig );
assumeOwnership( rm );
m_childContext.put( org.apache.avalon.fortress.RoleManager.ROLE, rm );
}
/**
* Get a reference to the initial ComponentLocator used by the
* ContainerManager to hold the Components used for parsing the config
* files and setting up the environment.
*
* @throws Exception when there is an error.
*/
protected void initializeOwnComponentManager() throws Exception
{
final DefaultServiceManager manager = new DefaultServiceManager();
final DefaultServiceSelector selector = new DefaultServiceSelector();
final ResourceSourceFactory resource = new ResourceSourceFactory();
resource.enableLogging( getLogger() );
selector.put( "resource", resource );
manager.put( resource.ROLE + "Selector", selector );
final SourceResolverImpl resolver = new SourceResolverImpl();
ContainerUtil.enableLogging( resolver, getLogger() );
ContainerUtil.contextualize( resolver, m_childContext );
ContainerUtil.service( resolver, manager );
ContainerUtil.parameterize( resolver, new Parameters() );
manager.put( resolver.ROLE, resolver );
manager.makeReadOnly();
assumeOwnership( manager );
m_manager = manager;
}
/**
* Get a configuration based on a config and URI key.
*
* @param configKey Get the <code>Configuration</code> object directly
* from the context.
* @param uriKey Get the uri from the context.
*/
protected Configuration getConfiguration( String configKey, String uriKey
)
{
try
{
return (Configuration)m_rootContext.get( configKey );
}
catch( ContextException ce )
{
}
String configUri = null;
try
{
configUri = (String)m_rootContext.get( uriKey );
}
catch( ContextException ce )
{
return null;
}
SourceResolver resolver = null;
Source src = null;
try
{
resolver = (SourceResolver)m_manager.lookup( SourceResolver.ROLE
);
src = resolver.resolveURI( configUri );
if( configBuilder == null )
{
configBuilder = new DefaultConfigurationBuilder();
}
return configBuilder.build( src.getInputStream() );
}
catch( Exception e )
{
if( getLogger().isWarnEnabled() )
{
getLogger().warn( "Could not read configuration file: " +
configUri, e );
}
return null;
}
finally
{
resolver.release( src );
m_manager.release( resolver );
}
}
/**
* Finalizes and returns the context.
*
* @return a <code>Context</code>
*/
public Context getContainerManagerContext()
{
return m_containerManagerContext;
}
/**
* Finalizes and returns the context.
*
* @return a <code>Context</code>
*/
public Context getChildContext()
{
return m_childContext;
}
/**
* Get a reference the Logger.
*
* @return a <code>Logger</code>
*/
protected Logger getLogger()
{
if( m_logger == null )
{
return m_primordialLogger;
}
else
{
return m_logger;
}
}
/**
* Will set up a LogKitLoggerManager if none is supplied. This can be
* overridden if you don't want a LogKitLoggerManager.
*
* <p>The postcondition is that
* <code>childContext.get( LoggerManager.ROLE )</code> should
* return a valid logger m_manager.</p>
*
* @throws Exception if it cannot instantiate the LoggerManager
*/
protected void initializeLoggerManager() throws Exception
{
try
{
// Try copying an already existing logger m_manager from the
override context.
m_childContext.put( LoggerManager.ROLE, m_rootContext.get(
LoggerManager.ROLE ) );
}
catch( ContextException ce )
{
// Should we set one up?
// Try to get a configuration for it...
Configuration loggerManagerConfig =
getConfiguration( LOGGER_MANAGER_CONFIGURATION,
LOGGER_MANAGER_CONFIGURATION_URI );
if( loggerManagerConfig == null )
{
// No config specified.
// Does the parent supply a logger m_manager?
try
{
m_childContext.get( LoggerManager.ROLE );
// OK, done.
return;
}
catch( ContextException cex )
{
// The parent did not supply a Logger Manager, so create
an empty
// configuration so that a default logger can be created.
loggerManagerConfig = EMPTY_CONFIG;
}
}
// Resolve the prefix to use for this Logger Manager
String logPrefix = (String)get( m_rootContext, LOG_CATEGORY,
get( m_childContext,
LOG_CATEGORY, null ) );
// Resolve a name for the logger, taking the logPrefix into
account
String lmDefaultLoggerName;
String lmLoggerName;
if( logPrefix == null )
{
lmDefaultLoggerName = "";
lmLoggerName = loggerManagerConfig.getAttribute( "logger",
"system.logkit" );
}
else
{
lmDefaultLoggerName = logPrefix;
lmLoggerName = logPrefix +
org.apache.log.Logger.CATEGORY_SEPARATOR
+ loggerManagerConfig.getAttribute( "logger",
"system.logkit" );
}
// Create the default logger for the Logger Manager.
org.apache.log.Logger lmDefaultLogger =
Hierarchy.getDefaultHierarchy().getLoggerFor(
lmDefaultLoggerName );
// The default logger is not used until after the logger conf has
been loaded
// so it is possible to configure the priority there.
lmDefaultLogger.setPriority( Priority.DEBUG );
// Create the logger for use internally by the Logger Manager.
org.apache.log.Logger lmLogger =
Hierarchy.getDefaultHierarchy().getLoggerFor( lmLoggerName );
lmLogger.setPriority( Priority.getPriorityForName(
loggerManagerConfig.getAttribute( "log-level", "DEBUG" ) ) );
// Setup the Logger Manager
LoggerManager logManager = new LogKitLoggerManager(
logPrefix, Hierarchy.getDefaultHierarchy(),
new LogKitLogger( lmDefaultLogger ), new LogKitLogger(
lmLogger ) );
ContainerUtil.contextualize( logManager, m_rootContext );
ContainerUtil.configure( logManager, loggerManagerConfig );
assumeOwnership( logManager );
m_childContext.put( LoggerManager.ROLE, logManager );
}
// Since we now have a LoggerManager, we can update the this.logger
field
// if it is null and start logging to the "right" logger.
if( m_logger == null )
{
getLogger().debug( "Switching to default Logger provided by
LoggerManager." );
LoggerManager loggerManager = (LoggerManager)m_childContext.get(
LoggerManager.ROLE );
m_logger = loggerManager.getDefaultLogger();
}
}
/**
* Will set up a LogKitLoggerManager if none is supplied. This can be
* overridden if you don't want a LogKitLoggerManager.
*
* <p>The postcondition is that
* <code>childContext.get( LoggerManager.ROLE )</code> should
* return a valid logger m_manager.</p>
*
* @throws Exception if it cannot instantiate the LoggerManager
*/
protected void initializeInstrumentManager() throws Exception
{
try
{
// Try copying an already existing instrument m_manager from the
override context.
m_childContext.put( InstrumentManager.ROLE, m_rootContext.get(
InstrumentManager.ROLE ) );
}
catch( ContextException ce )
{
// Should we set one up?
// Try to get a configuration for it...
Configuration instrumentConfig = getConfiguration(
INSTRUMENT_MANAGER_CONFIGURATION, INSTRUMENT_MANAGER_CONFIGURATION_URI );
if( instrumentConfig == null )
{
// No config.
// Does the parent supply a logger m_manager?
try
{
m_childContext.get( InstrumentManager.ROLE );
// OK, done.
return;
}
catch( ContextException cex )
{
}
instrumentConfig = EMPTY_CONFIG;
}
// Get the context Logger Manager
LoggerManager loggerManager = (LoggerManager)m_childContext.get(
LoggerManager.ROLE );
// Get the logger for the instrument m_manager
Logger imLogger = loggerManager.getLoggerForCategory(
instrumentConfig.getAttribute( "logger", "system.instrument"
) );
// Set up the Instrument Manager
DefaultInstrumentManager instrumentManager = new
DefaultInstrumentManager();
instrumentManager.enableLogging( imLogger );
instrumentManager.configure( instrumentConfig );
instrumentManager.initialize();
assumeOwnership( instrumentManager );
m_childContext.put( InstrumentManager.ROLE, instrumentManager );
}
}
/**
* Will set up a Assembly Descriptor if none is supplied.
*
* <p>The postcondition is that
* <code>childContext.get( LoggerManager.ROLE )</code> should
* return a valid logger m_manager.</p>
*
* @throws Exception if it cannot instantiate the LoggerManager
*/
protected void initializeAssemblyConfig() throws Exception
{
try
{
m_containerManagerContext.put( ASSEMBLY_CONFIGURATION,
m_rootContext.get( ASSEMBLY_CONFIGURATION ) );
}
catch( ContextException ce )
{
Configuration containerConfig = getConfiguration(
ASSEMBLY_CONFIGURATION, ASSEMBLY_CONFIGURATION_URI );
if( containerConfig == null )
{
// No config.
// Does the parent supply a logger m_manager?
try
{
m_containerManagerContext.get( ASSEMBLY_CONFIGURATION );
// OK, done.
return;
}
catch( ContextException cex )
{
// Guess there is none.
return;
}
}
else
{
m_containerManagerContext.put( ASSEMBLY_CONFIGURATION,
containerConfig );
}
}
}
private final class DestroyOrderComparator implements Comparator
{
public boolean equals( Object other )
{
return other instanceof DestroyOrderComparator;
}
public int compare( Object a, Object b )
{
int typeA = typeOf(a);
int typeB = typeOf(b);
if (typeA < typeB) return -1;
if (typeA > typeB) return 1;
return 0;
}
private int typeOf(Object obj)
{
int retVal = 1; // Doesn't matter the type
if (obj instanceof CommandManager) retVal = 0;
if (obj instanceof ThreadManager) retVal = 2;
return retVal;
}
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/util/ContextManagerConstants.java
Index: ContextManagerConstants.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.util;
import org.apache.avalon.fortress.ContainerManagerConstants;
/**
* Provides constants used to access the Context object for containers.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Leo Sutic</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:42 $
*/
public interface ContextManagerConstants extends ContainerManagerConstants
{
String LOG_CATEGORY = "impl.logcategory";
String LOGGER_MANAGER_CONFIGURATION = "impl.logManager.config";
String LOGGER_MANAGER_CONFIGURATION_URI = "impl.logManager.config.uri";
String INSTRUMENT_MANAGER_CONFIGURATION = "impl.instrumentManager.config";
String INSTRUMENT_MANAGER_CONFIGURATION_URI =
"impl.instrumentManager.config.uri";
String ROLE_MANAGER_CONFIGURATION = "impl.roleManager.config";
String ROLE_MANAGER_CONFIGURATION_URI = "impl.roleManager.config.uri";
String ASSEMBLY_CONFIGURATION_URI = "impl.assembly.config.uri";
String CONFIGURATION_URI = "impl.configuration.uri";
String SERVICE_MANAGER_PARENT = "impl.serviceManager.parent";
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/util/FortressConfig.java
Index: FortressConfig.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.util;
import java.io.File;
import org.apache.avalon.excalibur.logger.LoggerManager;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.DefaultContext;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.excalibur.event.Queue;
import org.apache.avalon.fortress.impl.DefaultContainer;
import org.apache.avalon.fortress.RoleManager;
import org.apache.excalibur.instrument.InstrumentManager;
import org.apache.excalibur.mpool.PoolManager;
/**
* Helper class to create a m_context for the ContextManager.
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:43 $
*/
public class FortressConfig
{
private final DefaultContext m_context;
/**
* Creates a m_context builder and initializes it with default values.
* The default values are:
*
* <ul>
* <li>CONTAINER_CLASS =
"org.apache.avalon.fortress.impl.DefaultContainer" </li>
* <li>THREADS_CPU = 2</li>
* <li>THREAD_TIMEOUT = 1000</li>
* <li>CONTEXT_DIRECTORY = "../"</li>
* <li>WORK_DIRECTORY = "/tmp"</li>
* <li>LOG_CATEGORY = "fortress"</li>
* <li>CONTEXT_CLASSLOADER = the thread m_context class loader</li>
* </ul>
*/
public FortressConfig()
{
this( createDefaultConfig() );
}
/**
* Creates a m_context builder and initializes it with default values.
*
* @param parent parent m_context with default values.
*/
public FortressConfig( Context parent )
{
m_context = new OverridableContext( parent );
}
/**
* Creates a default m_context.
*/
public static final Context createDefaultConfig()
{
return createDefaultConfig(
Thread.currentThread().getContextClassLoader() );
}
/**
* Creates a default m_context.
*/
public static final Context createDefaultConfig( ClassLoader classLoader )
{
DefaultContext defaultContext = new DefaultContext();
try
{
defaultContext.put( ContextManagerConstants.CONTAINER_CLASS,
DefaultContainer.class );
}
catch( Exception e )
{
// ignore
}
defaultContext.put( ContextManagerConstants.THREADS_CPU, new Integer(
2 ) );
defaultContext.put( ContextManagerConstants.THREAD_TIMEOUT, new Long(
1000 ) );
defaultContext.put( ContextManagerConstants.CONTEXT_DIRECTORY, new
File( "../" ) );
defaultContext.put( ContextManagerConstants.WORK_DIRECTORY, new File(
"/tmp" ) );
defaultContext.put( ContextManagerConstants.LOG_CATEGORY, "fortress"
);
defaultContext.put( ClassLoader.class.getName(), classLoader );
defaultContext.put( ContextManagerConstants.CONFIGURATION_URI,
"conf/system.xconf" );
defaultContext.put(
ContextManagerConstants.LOGGER_MANAGER_CONFIGURATION_URI, "conf/logkit.xconf" );
defaultContext.put(
ContextManagerConstants.ROLE_MANAGER_CONFIGURATION_URI,
"resource://ext/system.roles" );
defaultContext.put(
ContextManagerConstants.ASSEMBLY_CONFIGURATION_URI,
"resource://ext/assembly.xml" );
defaultContext.makeReadOnly();
return defaultContext;
}
/**
* Finalizes the m_context and returns it.
*/
public Context getContext()
{
m_context.makeReadOnly();
return m_context;
}
public void setCommandQueue( final Queue commandQueue )
{
m_context.put( Queue.ROLE, commandQueue );
}
public void setServiceManagerParent( final ServiceManager serviceManager )
{
m_context.put( ContextManagerConstants.SERVICE_MANAGER_PARENT,
serviceManager );
}
public void setServiceManager( final ServiceManager componentManager )
{
m_context.put( ContextManagerConstants.SERVICE_MANAGER,
componentManager );
}
public void setContainerClass( final String containerClass )
throws ClassNotFoundException
{
ClassLoader classLoader = null;
try
{
classLoader = (ClassLoader)m_context.get(
ClassLoader.class.getName() );
}
catch( ContextException ce )
{
classLoader = Thread.currentThread().getContextClassLoader();
}
m_context.put( ContextManagerConstants.CONTAINER_CLASS,
classLoader.loadClass( containerClass ) );
}
public void setContainerClass( final Class containerClass )
{
m_context.put( ContextManagerConstants.CONTAINER_CLASS,
containerClass );
}
public void setContainerConfiguration( final Configuration config )
{
m_context.put( ContextManagerConstants.CONFIGURATION, config );
m_context.put( ContextManagerConstants.CONFIGURATION_URI, null );
}
public void setContainerConfiguration( final String location )
{
m_context.put( ContextManagerConstants.CONFIGURATION_URI, location );
}
public void setAssemblyConfiguration( final Configuration config )
{
m_context.put( ContextManagerConstants.ASSEMBLY_CONFIGURATION, config
);
m_context.put( ContextManagerConstants.ASSEMBLY_CONFIGURATION_URI,
null );
}
public void setAssemblyConfiguration( final String location )
{
m_context.put( ContextManagerConstants.ASSEMBLY_CONFIGURATION_URI,
location );
}
public void setContextClassLoader( final ClassLoader loader )
{
m_context.put( ClassLoader.class.getName(), loader );
}
public void setContextDirectory( final File file )
{
m_context.put( ContextManagerConstants.CONTEXT_DIRECTORY, file );
}
public void setContextDirectory( final String directory )
{
m_context.put( ContextManagerConstants.CONTEXT_DIRECTORY, new File(
directory ) );
}
public void setLoggerCategory( final String category )
{
m_context.put( ContextManagerConstants.LOG_CATEGORY, category );
}
public void setLoggerManager( final LoggerManager logManager )
{
m_context.put( LoggerManager.ROLE, logManager );
m_context.put( ContextManagerConstants.LOGGER_MANAGER_CONFIGURATION,
null );
m_context.put(
ContextManagerConstants.LOGGER_MANAGER_CONFIGURATION_URI, null );
}
public void setLoggerManagerConfiguration( final Configuration config )
{
m_context.put( ContextManagerConstants.LOGGER_MANAGER_CONFIGURATION,
config );
m_context.put(
ContextManagerConstants.LOGGER_MANAGER_CONFIGURATION_URI, null );
}
public void setLoggerManagerConfiguration( final String location )
{
m_context.put(
ContextManagerConstants.LOGGER_MANAGER_CONFIGURATION_URI, location );
}
public void setInstrumentManager( final InstrumentManager profiler )
{
m_context.put( InstrumentManager.ROLE, profiler );
m_context.put(
ContextManagerConstants.INSTRUMENT_MANAGER_CONFIGURATION, null );
m_context.put(
ContextManagerConstants.INSTRUMENT_MANAGER_CONFIGURATION_URI, null );
}
public void setInstrumentManagerConfiguration( final Configuration config
)
{
m_context.put(
ContextManagerConstants.INSTRUMENT_MANAGER_CONFIGURATION, config );
m_context.put(
ContextManagerConstants.INSTRUMENT_MANAGER_CONFIGURATION_URI, null );
}
public void setInstrumentManagerConfiguration( final String location )
{
m_context.put(
ContextManagerConstants.INSTRUMENT_MANAGER_CONFIGURATION_URI, location );
}
public void setNumberOfThreadsPerCPU( final int numberOfThreads )
{
m_context.put( ContextManagerConstants.THREADS_CPU, new Integer(
numberOfThreads ) );
}
public void setPoolManager( final PoolManager poolManager )
{
m_context.put( PoolManager.ROLE, poolManager );
}
public void setRoleManager( final org.apache.avalon.fortress.RoleManager
roleManager )
{
m_context.put( org.apache.avalon.fortress.RoleManager.ROLE,
roleManager );
}
public void setRoleManagerConfiguration( final Configuration config )
{
m_context.put( ContextManagerConstants.ROLE_MANAGER_CONFIGURATION,
config );
m_context.put(
ContextManagerConstants.ROLE_MANAGER_CONFIGURATION_URI, null );
}
public void setRoleManagerConfiguration( final String location )
{
m_context.put(
ContextManagerConstants.ROLE_MANAGER_CONFIGURATION_URI, location );
}
public void setThreadTimeout( final long timeout )
{
m_context.put( ContextManagerConstants.THREAD_TIMEOUT, new Long(
timeout ) );
}
public void setWorkDirectory( final File file )
{
m_context.put( ContextManagerConstants.WORK_DIRECTORY, file );
}
public void setWorkDirectory( final String directory )
{
setWorkDirectory( new File( directory ) );
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/util/OverridableContext.java
Index: OverridableContext.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) @year@ 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", "Excalibur" 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/>.
*/
package org.apache.avalon.fortress.util;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.DefaultContext;
/**
* The OverridableContext allows you to "null" out entries, even if they are
* in a parent context.
*
* @author <a href="mailto:[email protected]">Avalon Development
Team</a>
* @version CVS $Revision: 1.1 $ $Date: 2003/01/27 16:55:43 $
*/
public final class OverridableContext
extends DefaultContext
{
/**
* Creation of a new overridable context.
* @param parent the parent context
*/
public OverridableContext( Context parent )
{
super( parent );
}
/**
* Add a context entry to the context.
* @param key the context key
* @param value the context value
*/
public void put( final Object key, final Object value )
{
if( null == value )
{
hide( key );
}
else
{
super.put( key, value );
}
}
}
1.1
jakarta-avalon-excalibur/fortress/src/java/org/apache/avalon/fortress/util/package.html
Index: package.html
===================================================================
<body>
<p>
The <code>util</code> package includes general unities supporting
configuration and context management.
</p>
<p>
The contents of this package are not a part of the fortress client API.
</p>
</body>
--
To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>