avalon-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dona...@apache.org
Subject cvs commit: jakarta-avalon-excalibur/fortress/src/java/org/apache/excalibur/fortress/container AbstractContainer.java
Date Fri, 08 Nov 2002 03:31:36 GMT
donaldp     2002/11/07 19:31:36

  Added:       fortress/src/java/org/apache/excalibur/fortress/container
                        AbstractContainer.java
  Removed:     fortress/src/java/org/apache/excalibur/fortress
                        AbstractContainer.java
  Log:
  Move AbstractContainer into the container package
  
  Revision  Changes    Path
  1.1                  jakarta-avalon-excalibur/fortress/src/java/org/apache/excalibur/fortress/container/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
      apache@apache.org.
  
   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.excalibur.fortress.container;
  
  import java.lang.reflect.Constructor;
  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.component.ComponentManager;
  import org.apache.avalon.framework.configuration.Configuration;
  import org.apache.avalon.framework.configuration.ConfigurationException;
  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.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.container.legacy.LegacyComponentManager;
  import org.apache.excalibur.event.Queue;
  import org.apache.excalibur.fortress.container.commands.DisposeComponentHandlerCommand;
  import org.apache.excalibur.fortress.container.commands.InitializeComponentHandlerCommand;
  import org.apache.excalibur.fortress.handler.ComponentHandler;
  import org.apache.excalibur.fortress.lifecycle.LifecycleExtensionManager;
  import org.apache.excalibur.fortress.lookup.FortressServiceManager;
  import org.apache.excalibur.fortress.lookup.FortressServiceSelector;
  import org.apache.excalibur.fortress.util.ExcaliburRoleManager;
  import org.apache.excalibur.fortress.util.RoleManager;
  import org.apache.excalibur.fortress.Container;
  import org.apache.excalibur.fortress.ContainerConstants;
  import org.apache.excalibur.instrument.InstrumentManager;
  import org.apache.excalibur.instrument.Instrumentable;
  import org.apache.excalibur.mpool.PoolManager;
  
  /**
   * The Container is an interface used to mark the Containers in your system.
   * It exposes a protected getServiceManager() method so that the
   * Container's Manager can expose that to the instantiating class.
   *
   * @author <a href="mailto:bloritsch@apache.org">Berin Loritsch</a>
   * @author <a href="mailto:proyal@apache.org">Peter Royal</a>
   * @author <a href="mailto:crafterm@apache.org">Marcus Crafter</a>
   * @version CVS $Revision: 1.1 $ $Date: 2002/11/08 03:31:36 $
   */
  public abstract class AbstractContainer
      extends AbstractLogEnabled
      implements Contextualizable, Serviceable, Initializable, Disposable, Container
  {
      protected Context m_context;
      protected ServiceManager m_serviceManager;
      protected LoggerManager m_logManager;
      protected PoolManager m_poolManager;
      protected Queue m_commandQueue;
      protected ClassLoader m_classLoader;
      protected RoleManager m_roleManager;
      protected InstrumentManager m_instrumentManager;
      protected Configuration m_configuration;
      protected Map m_configs = new StaticBucketMap();
      protected Map m_mapper = new StaticBucketMap();
      protected List m_components = new ArrayList( 10 );
      protected LifecycleExtensionManager m_extManager;
  
      /**
       * Pull the manager items from the context so we can use them to set up
       * the system.
       */
      public void contextualize( Context containerContext )
          throws ContextException
      {
          m_context = containerContext;
  
          m_logManager = (LoggerManager)m_context.get( ContainerConstants.LOGGER_MANAGER );
          m_poolManager = (PoolManager)m_context.get( ContainerConstants.POOL_MANAGER );
  
          try
          {
              m_extManager = (LifecycleExtensionManager)m_context.get( ContainerConstants.EXTENSION_MANAGER
);
          }
          catch( ContextException ce )
          {
              m_extManager = new LifecycleExtensionManager();
  
              if( getLogger().isDebugEnabled() )
              {
                  getLogger().debug( "No Container.EXTENSION_MANAGER is given, installing
default "
                                     + "lifecycle extension manager with 0 extensions" );
              }
          }
  
          m_extManager.enableLogging( getLogger() );
  
          try
          {
              m_classLoader = (ClassLoader)m_context.get( ContainerConstants.CONTEXT_CLASSLOADER
);
          }
          catch( ContextException ce )
          {
              m_classLoader = Thread.currentThread().getContextClassLoader();
          }
  
          try
          {
              m_commandQueue = (Queue)m_context.get( ContainerConstants.COMMAND_QUEUE );
          }
          catch( ContextException ce )
          {
              m_commandQueue = null;
              getLogger().warn( "No Container.COMMAND_QUEUE is given, all management will
be "
                                + "performed synchronously" );
          }
  
          try
          {
              m_roleManager = (RoleManager)m_context.get( ContainerConstants.ROLE_MANAGER
);
          }
          catch( ContextException ce )
          {
              try
              {
                  m_roleManager = new ExcaliburRoleManager( null, m_classLoader );
                  ContainerUtil.enableLogging( m_roleManager, getLogger().getChildLogger(
"roles" ) );
                  ContainerUtil.initialize( m_roleManager );
              }
              catch( Exception e )
              {
                  throw new ContextException( "Unable to create default role manager", e );
              }
          }
  
          m_instrumentManager = (InstrumentManager)m_context.get( ContainerConstants.INSTRUMENT_MANAGER
);
      }
  
      /**
       * Handles when a configuration name is used that is not "component", so
       * it makes it easier to handle ComponentSelector hierarchies.  It is
       * meant to either return a ComponentHandler or a ComponentSelector.
       * Override this so that your container can translate the container's
       * config to the default standard config.
       */
      protected abstract Configuration rewriteConfiguration( final Configuration configItem
)
          throws ConfigurationException;
  
      /**
       * Add a Component.
       */
      protected void addComponent( final Configuration component, Object hint )
      {
          if( null == hint )
          {
              throw new IllegalArgumentException( "Hint must not be null" );
          }
  
          String role = component.getAttribute( "role", null );
          String klass = component.getAttribute( "class", null );
          boolean isLazy = isLazyComponentHandler( component );
          ComponentHandler handler = getComponentHandler(
              component.getAttribute( "handler", null ), klass, component, isLazy
          );
  
          if( null != role && null != klass && null != handler )
          {
              Map hintMap = (StaticBucketMap)m_mapper.get( role );
  
              if( null == hintMap )
              {
                  hintMap = new StaticBucketMap();
              }
  
              hintMap.put( hint, handler );
  
              if( hintMap.containsKey( "default" ) )
              {
                  if( !hintMap.containsKey( "selector" ) )
                  {
                      hintMap.put( "selector",
                                   new FortressServiceSelector( this, role ) );
                  }
              }
              else
              {
                  hintMap.put( "default", handler );
              }
  
              // FIXME(MC) is this always needed ? should only need to be done if
              // hintMap is not yet in m_mapper ? or is it here due to threading issues ?
              m_mapper.put( role, hintMap );
          }
      }
  
      /**
       * 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", null );
  
          boolean policyUnspecified = policy == null;
          boolean isLazy = "request".equalsIgnoreCase( policy );
          boolean isNonLazy = "startup".equalsIgnoreCase( policy );
  
          if( policyUnspecified || isNonLazy )
              return false;
          else if( isLazy )
              return true;
  
          // policy was not null, but didn't match anything above
          String klass = component.getAttribute( "class", null );
  
          throw new IllegalArgumentException(
              "Unknown activation policy for class " + klass + ": " + policy
          );
      }
  
      /**
       * Get a ComponentHandler with the standard
       * <code>HANDLER_CONSTRUCTOR</code>  for the component class passed in.
       */
      private ComponentHandler getComponentHandler( final String handlerClassName,
                                                    final String className,
                                                    final Configuration configuration,
                                                    final boolean isLazy )
      {
          Constructor constructor;
          ComponentHandler handler = null;
  
          try
          {
              Class klass = m_classLoader.loadClass( className );
              Class handlerKlass = m_classLoader.loadClass( handlerClassName );
              constructor = handlerKlass.getConstructor( ComponentHandler.HANDLER_CONSTRUCTOR
);
              handler = (ComponentHandler)constructor.newInstance( new Object[]{
                  klass,
                  configuration,
                  getServiceManager(),
                  m_context,
                  m_extManager,
                  new Boolean( isLazy )
              } );
  
              if( handler instanceof Instrumentable )
              {
                  Instrumentable instrumentable = (Instrumentable)handler;
                  m_instrumentManager.registerInstrumentable(
                      instrumentable, instrumentable.getInstrumentableName() );
              }
          }
          catch( final Exception e )
          {
              if( getLogger().isDebugEnabled() )
              {
                  getLogger().debug( "Could not create the '" + handlerClassName +
                                     "' handler for the '" + className +
                                     "' component.", e );
              }
          }
  
          if( getLogger().isDebugEnabled() )
          {
              getLogger().debug( "Component " + className +
                                 " uses handler " + handlerClassName );
          }
  
          m_configs.put( handler, configuration );
          m_components.add( handler );
  
          return handler;
      }
  
      /**
       * 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 )
          {
              throw new ServiceException( role + "/" + hint, "Component does not exist" );
          }
  
          if( null == hint )
          {
              value = hintMap.get( "selector" );
  
              if( null == value )
              {
                  value = hintMap.get( "default" );
              }
  
              return value;
          }
  
          value = hintMap.get( hint );
  
          if( null == value )
          {
              throw new ServiceException( role + "/" + hint, "Component does not exist" );
          }
  
          return value;
      }
  
      /**
       * 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 )
              {
                  hasComponent = hintMap.containsKey( "selector" );
  
                  if( !hasComponent )
                  {
                      hasComponent = hintMap.containsKey( "default" );
                  }
              }
              else
              {
                  hasComponent = hintMap.containsKey( hint );
              }
          }
  
          return hasComponent;
      }
  
      /**
       * 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.
       */
      public void service( final ServiceManager parent )
          throws ServiceException
      {
          m_serviceManager = new FortressServiceManager( this, parent );
      }
  
      /**
       * Initializes all components so that the system is ready to be used.
       */
      public void initialize()
          throws Exception
      {
          Iterator i = m_components.iterator();
          BoundedFifoBuffer buffer = new BoundedFifoBuffer( m_components.size() );
  
          while( i.hasNext() )
          {
              try
              {
                  final ComponentHandler handler = (ComponentHandler)i.next();
  
                  if( !handler.isLazy() )
                  {
                      if( null != m_commandQueue )
                      {
                          m_commandQueue.enqueue(
                              new InitializeComponentHandlerCommand( handler, getLogger()
)
                          );
                      }
                      else
                      {
                          ContainerUtil.initialize( handler );
                      }
                  }
                  else
                  {
                      if( getLogger().isDebugEnabled() )
                      {
                          getLogger().debug(
                              "ComponentHandler (" + handler +
                              ") has specified request time initialization policy, " +
                              "initialization deferred till first use"
                          );
                      }
                  }
              }
              catch( Exception e )
              {
                  if( getLogger().isWarnEnabled() )
                  {
                      getLogger().warn( "Could not initialize component", e );
                  }
                  buffer.add( e );
              }
          }
  
          if( buffer.size() > 0 )
          {
              final StringBuffer message = new StringBuffer();
  
              while( !buffer.isEmpty() )
              {
                  message.append( ( (Exception)buffer.remove() ).getMessage() );
              }
  
              throw new Exception( message.toString() );
          }
      }
  
      /**
       * Disposes of all components and frees resources that they consume.
       */
      public void dispose()
      {
          final Iterator i = m_components.iterator();
  
          while( i.hasNext() )
          {
              final ComponentHandler handler = (ComponentHandler)i.next();
              if( null != m_commandQueue )
              {
                  try
                  {
                      m_commandQueue.enqueue(
                          new DisposeComponentHandlerCommand( handler,
                                                              getLogger() )
                      );
  
                      i.remove();
                  }
                  catch( final Exception e )
                  {
                      if( getLogger().isWarnEnabled() )
                      {
                          getLogger().warn( "Could not dispose component", e );
                      }
                  }
              }
              else
              {
                  ContainerUtil.dispose( handler );
              }
          }
      }
  
      /**
       * Exposes to subclasses the service manager which this container
       * uses to manage its child components.
       *
       * @return the child component manager
       */
      protected ServiceManager getServiceManager()
      {
          return m_serviceManager;
      }
  }
  
  
  
  

--
To unsubscribe, e-mail:   <mailto:avalon-cvs-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:avalon-cvs-help@jakarta.apache.org>


Mime
View raw message