avalon-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mcconn...@apache.org
Subject cvs commit: jakarta-avalon-excalibur/all/src/scratchpad/org/apache/avalon/excalibur/service ServiceLoader.java
Date Fri, 03 May 2002 05:01:15 GMT
mcconnell    02/05/02 22:01:15

  Modified:    all/src/scratchpad/org/apache/avalon/excalibur/service
                        ServiceLoader.java
  Log:
  no message
  
  Revision  Changes    Path
  1.9       +391 -304  jakarta-avalon-excalibur/all/src/scratchpad/org/apache/avalon/excalibur/service/ServiceLoader.java
  
  Index: ServiceLoader.java
  ===================================================================
  RCS file: /home/cvs/jakarta-avalon-excalibur/all/src/scratchpad/org/apache/avalon/excalibur/service/ServiceLoader.java,v
  retrieving revision 1.8
  retrieving revision 1.9
  diff -u -r1.8 -r1.9
  --- ServiceLoader.java	24 Mar 2002 09:56:41 -0000	1.8
  +++ ServiceLoader.java	3 May 2002 05:01:15 -0000	1.9
  @@ -8,35 +8,56 @@
   package org.apache.avalon.excalibur.service;
   
   import java.io.File;
  -import java.io.FileInputStream;
  -import java.io.InputStream;
  -import java.io.OutputStream;
   import java.net.URL;
   import java.net.URLClassLoader;
  -import java.util.Enumeration;
  -import java.util.Hashtable;
  +import java.net.MalformedURLException;
  +import java.util.jar.JarFile;
  +import java.util.jar.Attributes;
  +import java.util.jar.Attributes.Name;
   import java.util.Vector;
  -import org.apache.avalon.framework.CascadingException;
  +import java.util.Hashtable;
  +import java.util.Enumeration;
  +import java.io.InputStream;
  +import java.io.OutputStream;
  +import java.io.FileInputStream;
  +
  +import org.apache.log.Hierarchy;
  +import org.apache.log.Priority;
  +import org.apache.log.output.io.StreamTarget;
  +import org.apache.log.format.ExtendedPatternFormatter;
  +import org.apache.avalon.framework.logger.Logger;
   import org.apache.avalon.framework.CascadingRuntimeException;
  -import org.apache.avalon.framework.ExceptionUtil;
  -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.CascadingException;
  +import org.apache.avalon.framework.logger.LogKitLogger;
  +import org.apache.avalon.framework.logger.AvalonFormatter;
  +import org.apache.avalon.framework.logger.AbstractLogEnabled;
  +import org.apache.avalon.framework.logger.LogEnabled;
   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.configuration.DefaultConfiguration;
   import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
   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.context.Contextualizable;
  -import org.apache.avalon.framework.logger.AbstractLogEnabled;
  -import org.apache.avalon.framework.logger.AvalonFormatter;
  -import org.apache.avalon.framework.logger.LogKitLogger;
  -import org.apache.avalon.framework.logger.Logger;
  -import org.apache.log.Hierarchy;
  -import org.apache.log.Priority;
  -import org.apache.log.output.io.StreamTarget;
  +import org.apache.avalon.framework.context.ContextException;
  +import org.apache.avalon.framework.component.Component;
  +import org.apache.avalon.framework.component.Composable;
  +import org.apache.avalon.framework.component.ComponentManager;
  +import org.apache.avalon.framework.component.DefaultComponentManager;
  +import org.apache.avalon.framework.component.ComponentException;
  +import org.apache.avalon.framework.service.Serviceable;
  +import org.apache.avalon.framework.service.ServiceManager;
  +import org.apache.avalon.framework.service.ServiceException;
  +import org.apache.avalon.framework.service.DefaultServiceManager;
  +import org.apache.avalon.framework.activity.Initializable;
  +import org.apache.avalon.framework.activity.Startable;
  +import org.apache.avalon.framework.activity.Disposable;
  +import org.apache.avalon.framework.activity.Executable;
  +import org.apache.avalon.framework.ExceptionUtil;
  +import org.apache.avalon.framework.CascadingThrowable;
  +
  +import org.apache.avalon.excalibur.configuration.CascadingConfiguration;
   
   /**
    * A service loader that loads a target class, manages full component lifecycle
  @@ -69,51 +90,51 @@
    * <td width="20%" valign="top">Contextualizable</td>
    * <td>
    * The contextualization phase hadles the capture of runtime context information
  - * needed by the pipeline processor.  This information must be provided in the
  + * needed by the pipeline processor.  This information must be provided in the 
    * for of a <code>ServiceLoaderContext</code> otherwise the contextualize method
will
  - * throw an exception.  The following information is provided by the
  + * throw an exception.  The following information is provided by the 
    * <code>ServiceLoaderContext</code>:
    * <p><table border="0" cellpadding="3" cellspacing="0" width="100%">
    * <tr>
    * <td width="30%" valign="top"><code>ARGS_KEY</code></td>
    * <td>
  - * Contains the command line arguments as a <code>String[]</code>.
  + * Contains the command line arguments as a <code>String[]</code>. 
    * </td></tr>
    * <tr>
    * <td valign="top"><code>BASE_DIRECTORY_KEY</code></td>
    * <td>
  - * Contains the application base directory <code>File</code>.
  + * Contains the application base directory <code>File</code>. 
    * </td></tr>
    * <tr>
    * <td valign="top"><code>TARGET_KEY</code></td>
    * <td>
  - * Contains the name of the target class to be instantiated.
  + * Contains the name of the target class to be instantiated. 
    * </td></tr>
    * <tr>
    * <td valign="top"><code>INCLUDES_KEY</code></td>
    * <td>
    * Contains an array of jar files that will be added to the pipeline classloader.
  - * Jar files included in the array will be checked for block manifest entries.  If
  + * Jar files included in the array will be checked for block manifest entries.  If 
    * block entries exist that will be registered as potetentially available services
  - * that may be instantiated during the recursive dependecy resolution process.
  + * that may be instantiated during the recursive dependecy resolution process. 
    * </td></tr>
    * <tr>
    * <td valign="top"><code>DISPOSAL_POLICY_KEY</code></td>
    * <td>
  - * A <code>Boolean</code> value that is applied on completionof the startup
of a
  - * <code>Startable</code> component.  If the value TRUE, the component is stopped
  + * A <code>Boolean</code> value that is applied on completionof the startup
of a 
  + * <code>Startable</code> component.  If the value TRUE, the component is stopped

    * and disposed of (including termination of all dependencies) immediately following
    * startup.  This policy only applies to <code>Startable</code> components.
 Setting
    * policy value to FALSE ensures that the component can respond as a server.  Non
  - * <code>Startable</code> target component are immediately terminated (providing
a
  + * <code>Startable</code> target component are immediately terminated (providing
a 
    * useful for component testing during development cycles).
    * </td></tr>
    * <tr>
    * <td valign="top"><code>VERBOSE_POLICY_KEY</code></td>
    * <td>
  - * If this value is TRUE, debug logging entries from the pipeline processor will be
  - * if the overall logging priority permits this. If FALSE (the default), the logging
  - * entires generated by the pipeline processor will be limited to WARN, ERROR,
  + * If this value is TRUE, debug logging entries from the pipeline processor will be 
  + * if the overall logging priority permits this. If FALSE (the default), the logging 
  + * entires generated by the pipeline processor will be limited to WARN, ERROR, 
    * and FATAL_ERROR.
    * </td></tr>
    * </table>
  @@ -122,18 +143,17 @@
    * <tr><td width="20%">Initalizable</td>
    * <td>
    * The initilization phase handles the creation of a new instance of the supplied
  - * target class, resolves any service dependencies, and runs the instance through
  - * the lifecycle pipeline.
  + * target class, resolves any service dependencies, and runs the instance through 
  + * the lifecycle pipeline. 
    * </td></tr>
    * <tr><td width="20%" valign="top">Disposable</td>
    * <td>
  - * Cleanup and disposal of state members following termination and diposal of
  + * Cleanup and disposal of state members following termination and diposal of 
    * all current components.
    * </td></tr>
    * </table>
    */
  -public class ServiceLoader extends AbstractLogEnabled
  -    implements Configurable, Contextualizable, Initializable, Disposable
  +public class ServiceLoader extends AbstractLogEnabled implements PipelineService
   {
       private static final String DEFAULT_FORMAT = "[%7.7{priority}] (%{category}): %{message}\\n%{throwable}";
       private static OutputStream m_out = System.out;
  @@ -141,6 +161,7 @@
       private String[] m_args;
       private PipelineClassLoader m_classloader;
   
  +    private File m_root;
       private String m_target;
       private Object m_object;
       private File[] m_includes;
  @@ -152,92 +173,95 @@
   
       private ServiceFactory m_factory;
       private Configuration m_config;
  +    private ServiceManager m_manager;
   
  -    /**
  -     * Command line entry point supporting establishment and initalization of a service
  -     * loader instance with a supplied target component and supporting services.
  -     *
  -     *   <p><strong>java -jar form</strong></p>
  -     *   <p>Execution using java -jar pattern requires the presence
  -     *   of the following files under the same directory:</p>
  -     *       <ul>
  -     *         <li><code>merlin.jar</code>
  -     *         <li><code>avalon-framework.jar</code>
  -     *         <li><code>logkit.jar</code>
  -     *       </ul>
  -     *   <p>An example command line is shown below:</p>
  -     *   <pre>
  -     * $ java -jar <strong>merlin.jar</strong> &lt;supporting-jar-files&gt;
  -     *     -target &lt;class-name&gt;
  -     *   </pre>
  -     *   <p><strong>java -classpath form</strong></p>
  -     *   <p>Execution using java -classpath pattern requires the inclusions
  -     *   of the pipeline, framework and logkit jar files in the classpath
  -     *   statement.</p>
  -     *   <p>An example command line is shown below:</p>
  -     *   <pre>
  -     * $ java -classpath merlin.jar;avalon-framework.jar;logkit.jar
  -     *     <strong>org.apache.avalon.excalibur.service.ServiceLoader</strong>
  -     *      &lt;supporting-jar-files&gt; -target &lt;class-name&gt;
  -     *   </pre>
  -     * </ul>
  -     *
  -     * <p><table border="1" cellpadding="3" cellspacing="0" width="100%">
  -     * <tr bgcolor="#ccccff">
  -     * <td colspan="2"><b>Command Line Parameters and Arguments</b></td>
  -     * <tr><td width="30%"><b>Parameter</b></td><td><b>Description</b></td></tr>
  -     * <tr>
  -     * <td valign="top"><code>-target &lt;class-name&gt;</code></td>
  -     * <td>
  -     * <p>The class to instantiate.  If the class exposes any Avalon lifecycle interface
  -     * (such as <code>Configurable</code>, <code>Contextualizable</code>,
<code>Serviceable</code>,
  -     * <code>Initializable</code>, <code>Startable</code>, or <code>Disposable</code>,
the
  -     * pipeline will automate lifecycle processing and termination.
  -     * </p>
  -     * </td></tr>
  -     * <tr>
  -     * <td valign="top"><code>&lt;supporting-jar-files&gt;</code></td>
  -     * <td>
  -     * <p>A list of space seperated jar files that will be added to the pipeline
  -     * as supporting classes and components.  Any jar file included in the list
  -     * that contains an Avalon <code>Block</code> manifest will be registered
as
  -     * an available service when resolving component dependecies.</p>
  -     * </td></tr>
  -     * <tr><td valign="top"><code>-verbose &lt;boolean&gt;</code></td>
  -     * <td>
  -     * <p>A value of <code>true</code> will force debug level logging
of the actual pipeline
  -     * processor.  A value of <code>false</code> will disable pipeline debug
priority logging.
  -     * Visibility of logging infomration is dependent on the level supplied under the
  -     * <code>priority</code parameter.</p>
  -     * </td></tr>
  -     * <tr><td valign="top"><code>-priority &lt;priority&gt;</code></td>
  -     * <td>
  -     * <p>Declaration of the logging priority to use during pipeline execution. 
Valid values
  -     * include FATAL_ERROR, ERROR, WARN, INFO, and DEBUG. </p>
  -     * </td></tr>
  -     * <tr><td valign="top"><code>-dispose &lt;boolean&gt;</code></td>
  -     * <td>
  -     * If the target component is <code>Startable</code>, and the dispose argument
is <code>FALSE</code> the
  -     * component will be treated as a server and will continue to run following initialization.
  -     * Otherwise, the component will be disposed of.
  -     * </td></tr>
  -     * <tr><td valign="top"><code>-configuration &lt;file-path&gt;</code></td>
  -     * <td>
  -     * Optional parameter naming a file to be used as the configuration source.
  -     * </td></tr>
  -     * </table>
  -     *
  -     * @param args a array of <code>String</code> argument values passed under
the command line.
  -     */
  +    
  +   /**
  +    * Command line entry point supporting establishment and initalization of a service

  +    * loader instance with a supplied target component and supporting services.
  +    *
  +    *   <p><strong>java -jar form</strong></p>
  +    *   <p>Execution using java -jar pattern requires the presence 
  +    *   of the following files under the same directory:</p>
  +    *       <ul>
  +    *         <li><code>merlin.jar</code>
  +    *         <li><code>avalon-framework.jar</code>
  +    *         <li><code>logkit.jar</code>
  +    *       </ul>
  +    *   <p>An example command line is shown below:</p>
  +    *   <pre>
  +    * $ java -jar <strong>merlin.jar</strong> &lt;supporting-jar-files&gt;

  +    *     -target &lt;class-name&gt; 
  +    *   </pre>
  +    *   <p><strong>java -classpath form</strong></p>
  +    *   <p>Execution using java -classpath pattern requires the inclusions 
  +    *   of the pipeline, framework and logkit jar files in the classpath 
  +    *   statement.</p>
  +    *   <p>An example command line is shown below:</p>
  +    *   <pre>
  +    * $ java -classpath merlin.jar;avalon-framework.jar;logkit.jar 
  +    *     <strong>org.apache.avalon.excalibur.service.ServiceLoader</strong>
  +    *      &lt;supporting-jar-files&gt; -target &lt;class-name&gt; 
  +    *   </pre>
  +    * </ul>
  +    * 
  +    * <p><table border="1" cellpadding="3" cellspacing="0" width="100%">
  +    * <tr bgcolor="#ccccff">
  +    * <td colspan="2"><b>Command Line Parameters and Arguments</b></td>
  +    * <tr><td width="30%"><b>Parameter</b></td><td><b>Description</b></td></tr>
  +    * <tr>
  +    * <td valign="top"><code>-target &lt;class-name&gt;</code></td>
  +    * <td>
  +    * <p>The class to instantiate.  If the class exposes any Avalon lifecycle interface
  +    * (such as <code>Configurable</code>, <code>Contextualizable</code>,
<code>Serviceable</code>,  
  +    * <code>Initializable</code>, <code>Startable</code>, or <code>Disposable</code>,
the 
  +    * pipeline will automate lifecycle processing and termination.
  +    * </p>
  +    * </td></tr>
  +    * <tr>
  +    * <td valign="top"><code>&lt;supporting-jar-files&gt;</code></td>
  +    * <td>
  +    * <p>A list of space seperated jar files that will be added to the pipeline
  +    * as supporting classes and components.  Any jar file included in the list
  +    * that contains an Avalon <code>Block</code> manifest will be registered
as
  +    * an available service when resolving component dependecies.</p>
  +    * </td></tr>
  +    * <tr><td valign="top"><code>-verbose &lt;boolean&gt;</code></td>
  +    * <td>
  +    * <p>A value of <code>true</code> will force debug level logging
of the actual pipeline
  +    * processor.  A value of <code>false</code> will disable pipeline debug
priority logging.
  +    * Visibility of logging infomration is dependent on the level supplied under the 
  +    * <code>priority</code parameter.</p>
  +    * </td></tr>
  +    * <tr><td valign="top"><code>-priority &lt;priority&gt;</code></td>
  +    * <td>
  +    * <p>Declaration of the logging priority to use during pipeline execution.  Valid
values
  +    * include FATAL_ERROR, ERROR, WARN, INFO, and DEBUG. </p>
  +    * </td></tr>
  +    * <tr><td valign="top"><code>-dispose &lt;boolean&gt;</code></td>
  +    * <td>
  +    * If the target component is <code>Startable</code>, and the dispose argument
is <code>FALSE</code> the
  +    * component will be treated as a server and will continue to run following initialization.
  +    * Otherwise, the component will be disposed of.
  +    * </td></tr>
  +    * <tr><td valign="top"><code>-configuration &lt;file-path&gt;</code></td>
  +    * <td>
  +    * Optional parameter naming a file to be used as the configuration source.
  +    * </td></tr>
  +    * </table>
  +    *
  +    * @param args a array of <code>String</code> argument values passed under
the command line. 
  +    */
       public static void main( String[] args )
       {
           ServiceLoader pipeline = null;
  +        Logger logger = null;
           try
           {
  -
               CLI cli = new CLI( args );
               Hierarchy hierarchy = createBootstrapLogger( cli.getLoggingPriority() );
  -            Logger logger = new LogKitLogger( hierarchy.getLoggerFor( "" ) );
  +            logger = new LogKitLogger( hierarchy.getLoggerFor( "" ) );
  +            Logger merlin = logger.getChildLogger("merlin");
   
               File path = cli.getConfigurationPath();
               Configuration config = null;
  @@ -245,36 +269,35 @@
               {
                   config = getRuntimeConfiguration( path );
               }
  -            if( config == null ) config = new DefaultConfiguration( "profile", null );
  +            if( config == null ) config = new DefaultConfiguration("profile", null );
   
               pipeline = new ServiceLoader();
               pipeline.enableLogging( logger );
               pipeline.configure( config );
               pipeline.contextualize( cli.getContext() );
               pipeline.initialize();
  +
  +            pipeline.internalPipeline( cli.getTarget() );
  +
           }
           catch( IllegalParameterException ipe )
           {
  -            System.err.println( ipe.getMessage() );
  -        }
  +            logger.error( ipe.getMessage() );
  +        }        
           catch( PipelineException e )
           {
  -            System.err.println( e );
  +            logger.error( e.getMessage() + e.toString() );
  +            if( pipeline != null ) pipeline.dispose();
           }
           catch( PipelineRuntimeException e )
           {
  -            System.err.println( e );
  +            logger.error( e.getMessage() + e.toString() );
  +            if( pipeline != null ) pipeline.dispose();
           }
           catch( Throwable e )
           {
  -            ExceptionUtil.printStackTrace( e, true );
  -        }
  -        finally
  -        {
  -            if( pipeline != null )
  -            {
  -                pipeline.dispose();
  -            }
  +            e.printStackTrace();
  +            if( pipeline != null ) pipeline.dispose();
           }
       }
   
  @@ -283,28 +306,36 @@
           return m_verbose;
       }
   
  -    /**
  -     * Configuration of the pipeline.
  -     */
  +    //=======================================================================
  +    // Configurable
  +    //=======================================================================
  +
  +   /**
  +    * Configuration of the pipeline.
  +    */
       public void configure( Configuration config ) throws ConfigurationException
       {
           m_config = config;
       }
   
  -    /**
  -     * Contextualization of the pipeline including the supply of command-line
  -     * arguments, include files, target class, and related execution policies.
  -     * @see ServiceLoaderContext
  -     * @param context the pipeline context
  -     * @exception ContextException if the supplied context is not an instance
  -     *   of ServiceLoaderContext, or if an internal error occurs while resolving
  -     *   context information.
  -     */
  +    //=======================================================================
  +    // Contextualizable
  +    //=======================================================================
  +
  +   /**
  +    * Contextualization of the pipeline including the supply of command-line
  +    * arguments, include files, target class, and related execution policies.
  +    * @see ServiceLoaderContext
  +    * @param context the pipeline context
  +    * @exception ContextException if the supplied context is not an instance
  +    *   of ServiceLoaderContext, or if an internal error occurs while resolving 
  +    *   context information.
  +    */
       public void contextualize( Context context ) throws ContextException
       {
  -        try
  -        {
  -            ServiceLoaderContext c = (ServiceLoaderContext)context;
  +        if( context instanceof ServiceLoaderContext ) try
  +        { 
  +            ServiceLoaderContext c = (ServiceLoaderContext) context;
               m_includes = c.getIncludes();
               m_verbose = c.getVerbose();
               m_policy = c.getDisposalPolicy();
  @@ -312,19 +343,51 @@
           }
           catch( Throwable e )
           {
  -            final String error = "Unexpected error while reslving pipeline context.";
  +            final String error = "Unexpected error while resolving pipeline context.";
               throw new ContextException( error, e );
           }
  +        else
  +        {
  +            try
  +            {
  +                m_includes = (File[]) context.get( ServiceLoaderContext.INCLUDES_KEY );
  +            }
  +            catch( ContextException e )
  +            {
  +                m_includes = new File[0];
  +            }
  +
  +            try
  +            {
  +                m_verbose = ((Boolean)context.get( ServiceLoaderContext.VERBOSE_POLICY_KEY
)).booleanValue();
  +            }
  +            catch( ContextException e )
  +            {
  +                m_verbose = false;
  +            }
  +
  +            try
  +            {
  +                m_policy = ((Boolean)context.get( ServiceLoaderContext.DISPOSAL_POLICY_KEY
)).booleanValue();
  +            }
  +            catch( ContextException e )
  +            {
  +                m_policy = false;
  +            }
  +        }
       }
   
  -    /**
  -     * Start the pipeline and handle any errors arrising from loader execution.
  -     */
  +    //=======================================================================
  +    // Initializable
  +    //=======================================================================
  +
  +   /**
  +    * Start the pipeline and handle any errors arrising from loader execution.
  +    */
       public void initialize() throws PipelineException
       {
  -        if( m_target == null )
  -            throw new PipelineException(
  -                "The pipeline task required attribute 'target' has not been not supplied."
);
  +        //if( m_target == null ) throw new PipelineException(
  +        //  "The pipeline task required attribute 'target' has not been not supplied.");
   
           //
           // setup the factory
  @@ -333,12 +396,12 @@
           try
           {
               if( m_classloader == null ) m_classloader = createClassloader();
  -            m_factory = new ServiceFactory(
  -                new File( System.getProperty( "user.dir" ) ), getVerbose() );
  +            m_root = new File( System.getProperty("user.dir") );
  +            m_factory = new ServiceFactory( m_root, getVerbose() );
               m_factory.enableLogging( getLogger() );
               m_factory.configure( m_config );
               m_factory.initialize();
  -            enableLogging( getLogger().getChildLogger( "loader" ) );
  +            enableLogging( getLogger().getChildLogger("loader") );
           }
           catch( Throwable e )
           {
  @@ -347,41 +410,15 @@
               return;
           }
   
  -        try
  -        {
  -            process();
  -        }
  -        catch( Throwable e )
  -        {
  -            final String error = "Service processing error.";
  -            throw new PipelineException( error, e );
  -        }
  -        finally
  -        {
  -            if( m_policy )
  -            {
  -                if( m_object != null ) terminate();
  -                dispose();
  -                return;
  -            }
  -        }
  -    }
  -
  -    /**
  -     * Initates execution of the loading of supporting services derived from a
  -     * target.
  -     */
  -    private void process() throws PipelineException
  -    {
           //
  -        // add the included jar files to the classloader
  +        // preprocess the components in the classpath
           //
   
           Vector list = new Vector();
           Vector stack = new Vector();
  -        for( int i = 0; i < m_includes.length; i++ )
  +        for (int i=0; i<m_includes.length; i++) 
           {
  -            File target = m_includes[ i ];
  +            File target = m_includes[i];
               stack.add( target );
               list.add( target );
           }
  @@ -395,21 +432,32 @@
           }
           catch( Throwable e )
           {
  -            final String error = "Coould not complete service registration.";
  -            throw new PipelineException( error, e );
  +            final String error = "Unable to complete service registration.";
  +            throw new PipelineException( error, e ); 
           }
  +    }
  +
  +    //=======================================================================
  +    // PipelineService
  +    //=======================================================================
  +
  +    /**
  +     * Initates execution of the loading of supporting services derived from a 
  +     * target.
  +     */
  +    public Object pipeline( String target ) throws PipelineException
  +    {
   
           //
  -        // create an instance of the target and if verify that we can in fact build a
  -        // service manager if needed
  +        // create an instance of the target and verify that dependencies are resolvable
           //
   
           UnitInfo info;
           try
           {
  -            info = new UnitInfo( new UnitInfo( m_target.replace( '.', '/' ) ), m_config
);
  -            if( getVerbose() && getLogger().isDebugEnabled() )
  -                getLogger().debug( "validating target" );
  +            info = new UnitInfo( target.replace('.','/'), m_config, m_root );
  +            if( getVerbose() && getLogger().isDebugEnabled() ) 
  +              getLogger().debug( "validating target");
               try
               {
                   m_factory.validate( info );
  @@ -423,7 +471,7 @@
           catch( Throwable e )
           {
               final String error = "Service loader exception encounter while preparing services.";
  -            throw new PipelineException( error, e );
  +            throw new PipelineException( error, e ); 
           }
   
           //
  @@ -432,47 +480,84 @@
   
           try
           {
  -            m_object = m_factory.pipeline( info );
  +            return m_factory.pipeline( info );
           }
           catch( Throwable e )
           {
               final String error = "Service loader exception encounter during target execution.";
  -            throw new PipelineException( error, e );
  +            throw new PipelineException( error, e ); 
           }
   
  +    }
  +
  +    //=======================================================================
  +    // ServiceLoader
  +    //=======================================================================
  +
  +    private void internalPipeline( String target ) throws PipelineException
  +    {
  +        final Object object = pipeline( target );
  +
           //
           // add a shutdown hook so we can stop services and target and invoke disposal
           //
   
  -        Runtime.getRuntime().addShutdownHook(
  -            new Thread()
  +        Runtime.getRuntime().addShutdownHook( 
  +          new Thread()
  +          {
  +              public void run()
  +              {
  +                  if( getVerbose() && (getLogger() != null) && getLogger().isDebugEnabled()
) 
  +                    getLogger().debug("shutdown hook");
  +                  terminate( object );
  +                  dispose();
  +              }
  +          }
  +        );
  +
  +        if( m_policy )
  +        {
  +            if( object != null )
               {
  -                public void run()
  +                if( object instanceof Executable )
                   {
  -                    terminate();
  -                    dispose();
  +                    try
  +                    {
  +                        ((Executable)object).execute();
  +                    }
  +                    catch( Throwable e )
  +                    {
  +                        throw new PipelineException("Target execution error.", e );
  +                    }
                   }
  +                terminate( object );
  +                dispose();
  +                return;
               }
  -        );
  +        }
  +        else
  +        {
  +            getLogger().info( "target established: " + object.getClass().getName());
  +        }
       }
   
  -    /**
  -     * Run the termination lifecycle actions on the primary object.
  -     */
  -    private void terminate()
  +   /**
  +    * Run the termination lifecycle actions on the primary object.
  +    */
  +    private void terminate( Object object )
       {
           if( m_terminated ) return;
           m_terminated = true;
  -        if( m_object == null ) return;
  -        if( getVerbose() && getLogger().isDebugEnabled() )
  -            getLogger().debug(
  -                "terminating " + m_object.getClass().getName() );
  +        if( object == null ) return;
  +
  +        if( getVerbose() && getLogger().isDebugEnabled() ) getLogger().debug( 
  +           "terminating " + object.getClass().getName() );
   
  -        if( m_object instanceof Startable )
  +        if( object instanceof Startable )
           {
               try
               {
  -                ( (Startable)m_object ).stop();
  +                ((Startable)object).stop();
               }
               catch( Throwable e )
               {
  @@ -481,11 +566,11 @@
               }
           }
   
  -        if( m_object instanceof Disposable )
  +        if( object instanceof Disposable )
           {
               try
               {
  -                ( (Disposable)m_object ).dispose();
  +                ((Disposable)object).dispose();
               }
               catch( Throwable e )
               {
  @@ -495,23 +580,12 @@
           }
       }
   
  -    /**
  -     * Disposal of the pipeline and release of all resources.
  -     */
  +   /**
  +    * Disposal of the pipeline and release of all resources.
  +    */
       public void dispose()
       {
           if( m_disposed ) return;
  -
  -        if( !m_terminated )
  -            try
  -            {
  -                terminate();
  -            }
  -            catch( Throwable e )
  -            {
  -                // ignore and continue
  -            }
  -
           m_disposed = true;
   
           if( getVerbose() && getLogger().isDebugEnabled() ) getLogger().debug( "loader
disposal" );
  @@ -519,7 +593,7 @@
           {
               try
               {
  -                ( (Disposable)m_factory ).dispose();
  +                ((Disposable)m_factory).dispose();
               }
               catch( Throwable e )
               {
  @@ -532,7 +606,7 @@
       //==========================================================
       // classloader
       //==========================================================
  -
  +    
       private PipelineClassLoader createClassloader()
       {
           try
  @@ -543,47 +617,46 @@
           }
           catch( Throwable e )
           {
  -            final String error = "Failed to instantial a classloader.";
  -            throw new CascadingRuntimeException( error, e );
  +             final String error = "Failed to instantial a classloader.";
  +             throw new CascadingRuntimeException( error, e );
           }
       }
   
       class PipelineClassLoader extends URLClassLoader
       {
  -        PipelineClassLoader()
  +        PipelineClassLoader( )
           {
  -            super( new URL[ 0 ], Thread.currentThread().getContextClassLoader() );
  +            super( new URL[0], Thread.currentThread().getContextClassLoader() );
           }
   
  -        protected void addURL( URL url )
  +        protected void addURL( URL url ) 
           {
               try
               {
  -                URL jarURL = new URL( "jar:" + url.toString() + "!/" );
  +                URL jarURL = new URL("jar:" + url.toString() + "!/");
                   super.addURL( jarURL );
               }
               catch( Throwable e )
               {
                   throw new CascadingRuntimeException(
  -                    "Unexpected error while attempting to add classloader URL: " + url,
e );
  +                  "Unexpected error while attempting to add classloader URL: " + url, e
);
               }
           }
  -
           protected Class loadClass( String name, boolean resolve ) throws ClassNotFoundException
           {
               return super.loadClass( name, resolve );
  -        }
  +        } 
       }
   
  -    /**
  -     * Load the supplied jar files under the pipeline classloader.
  -     * For each entry in the stack, try to load it and
  -     * if sucessfull, remove it from the stack - on completion
  -     * the stack should be less than its original size - recursivly
  -     * invoke load until the stack is empty.
  -     * @param stack a <code>Vector</code> containing a sequence of jar files
  -     *   to be added to the classloader.
  -     */
  +   /**
  +    * Load the supplied jar files under the pipeline classloader.
  +    * For each entry in the stack, try to load it and 
  +    * if sucessfull, remove it from the stack - on completion
  +    * the stack should be less than its original size - recursivly
  +    * invoke load until the stack is empty.
  +    * @param stack a <code>Vector</code> containing a sequence of jar files
  +    *   to be added to the classloader.
  +    */
       private void load( Vector stack )
       {
           int size = stack.size();
  @@ -591,7 +664,7 @@
           Enumeration enum = stack.elements();
           while( enum.hasMoreElements() )
           {
  -            File target = (File)enum.nextElement();
  +            File target = (File) enum.nextElement();
               try
               {
                   m_classloader.addURL( target.toURL() );
  @@ -612,15 +685,15 @@
           else
           {
               Enumeration keys = errors.keys();
  -            getLogger().error( "Load error count = " + errors.size() );
  +            getLogger().error("Load error count = " + errors.size() );
               while( keys.hasMoreElements() )
               {
  -                File key = (File)keys.nextElement();
  -                getLogger().error(
  -                    "Error while loading file."
  -                    + "\n\tfile: " + key.toString(), (Throwable)errors.get( key ) );
  +                File key = (File) keys.nextElement();
  +                getLogger().error( 
  +                   "Error while loading file."
  +                   + "\n\tfile: " + key.toString(), (Throwable) errors.get( key ) );
               }
  -            throw new RuntimeException( "Unable to load file stack - see trace for details."
);
  +            throw new RuntimeException("Unable to load file stack - see trace for details.");
           }
       }
   
  @@ -628,24 +701,23 @@
       // configuration
       //==========================================================
   
  -    /**
  -     * Get client configuration from a file.
  -     */
  -    private static Configuration getRuntimeConfiguration( final File file )
  +   /**
  +    * Get client configuration from a file. 
  +    */ 
  +    private static Configuration getRuntimeConfiguration( final File file ) 
       {
           try
           {
  -            DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
  +            DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder( ); 
               InputStream is = new FileInputStream( file );
  -            if( is == null )
  -                throw new Exception(
  -                    "Could not load the configuration resource \"" + file + "\"" );
  -            return builder.build( is );
  +            if( is == null ) throw new Exception( 
  +              "Could not load the configuration resource \"" + file + "\"" ); 
  +            return builder.build( is ); 
           }
           catch( Throwable e )
           {
               final String error = "Unable to create configuration from file: " + file;
  -            throw new CascadingRuntimeException( error, e );
  +            throw new CascadingRuntimeException( error, e ); 
           }
       }
   
  @@ -658,8 +730,8 @@
           try
           {
               Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
  -            hierarchy.setDefaultLogTarget(
  -                new StreamTarget( m_out, new AvalonFormatter( DEFAULT_FORMAT ) ) );
  +            hierarchy.setDefaultLogTarget( 
  +               new StreamTarget( m_out, new AvalonFormatter( DEFAULT_FORMAT ) ) );
               hierarchy.setDefaultPriority( priority );
               return hierarchy;
           }
  @@ -673,41 +745,41 @@
       // command-line
       //==========================================================
   
  -    private static class IllegalParameterException extends Exception
  +    private static class IllegalParameterException extends Exception 
       {
  -        /**
  -         * Construct a new <code>IllegalParameterException</code> instance
with the
  -         * supplied message parameter.
  -         * @param message Message summarising the exception.
  -         */
  -        public IllegalParameterException( final String message )
  +       /**
  +        * Construct a new <code>IllegalParameterException</code> instance with
the 
  +        * supplied message parameter.
  +        * @param message Message summarising the exception.
  +        */
  +        public IllegalParameterException( final String message ) 
           {
  -            super( message );
  +           super( message );
           }
       }
   
       private static class CLI
       {
  -        private String[] m_args = new String[ 0 ];
  +        private String[] m_args = new String[0];
           private Priority m_priority = Priority.INFO;
           private String m_target = "";
           private boolean m_policy = true;
           private boolean m_verbose = false;
  -        private File[] m_files = new File[ 0 ];
  +        private File[] m_files = new File[0];
           private File m_path = null;
   
           public CLI( String[] args ) throws IllegalParameterException
           {
               m_args = args;
               Vector vector = new Vector();
  -            for( int i = 0; i < m_args.length; i++ )
  +            for( int i=0; i < m_args.length; i++ )
               {
  -                if( m_args[ i ].toLowerCase().startsWith( "-tar" ) )
  +                if( m_args[i].toLowerCase().startsWith("-tar") )
                   {
  -                    if( i + 1 < m_args.length )
  +                    if( i+1 < m_args.length ) 
                       {
  -                        m_target = m_args[ i + 1 ];
  -                        i = i + 1;
  +                        m_target = m_args[i+1];
  +                        i = i+1;
                       }
                       else
                       {
  @@ -715,12 +787,12 @@
                           throw new RuntimeException( error );
                       }
                   }
  -                else if( m_args[ i ].toLowerCase().startsWith( "-conf" ) )
  +                else if( m_args[i].toLowerCase().startsWith("-conf") )
                   {
  -                    if( i + 1 < m_args.length )
  +                    if( i+1 < m_args.length ) 
                       {
  -                        m_path = new File( m_args[ i + 1 ] );
  -                        i = i + 1;
  +                        m_path = new File( m_args[i+1] );
  +                        i = i+1;
                       }
                       else
                       {
  @@ -728,12 +800,12 @@
                           throw new RuntimeException( error );
                       }
                   }
  -                else if( m_args[ i ].toLowerCase().startsWith( "-pri" ) )
  +                else if( m_args[i].toLowerCase().startsWith("-pri") )
                   {
  -                    if( i + 1 < m_args.length )
  +                    if( i+1 < m_args.length ) 
                       {
  -                        m_priority = Priority.getPriorityForName( m_args[ i + 1 ].toUpperCase()
);
  -                        i = i + 1;
  +                        m_priority = Priority.getPriorityForName( m_args[i+1].toUpperCase()
);
  +                        i = i+1;
                       }
                       else
                       {
  @@ -741,12 +813,12 @@
                           throw new RuntimeException( error );
                       }
                   }
  -                else if( m_args[ i ].toLowerCase().startsWith( "-dis" ) )
  +                else if( m_args[i].toLowerCase().startsWith("-dis") )
                   {
  -                    if( i + 1 < m_args.length )
  +                    if( i+1 < m_args.length ) 
                       {
  -                        m_policy = ( m_args[ i + 1 ].toUpperCase().equals( "TRUE" ) );
  -                        i = i + 1;
  +                        m_policy = (m_args[i+1].toUpperCase().equals("TRUE"));
  +                        i = i+1;
                       }
                       else
                       {
  @@ -754,12 +826,12 @@
                           throw new RuntimeException( error );
                       }
                   }
  -                else if( m_args[ i ].toLowerCase().startsWith( "-ver" ) )
  +                else if( m_args[i].toLowerCase().startsWith("-ver") )
                   {
  -                    if( i + 1 < m_args.length )
  +                    if( i+1 < m_args.length ) 
                       {
  -                        m_verbose = ( m_args[ i + 1 ].toUpperCase().equals( "TRUE" ) );
  -                        i = i + 1;
  +                        m_verbose = (m_args[i+1].toUpperCase().equals("TRUE"));
  +                        i = i+1;
                       }
                       else
                       {
  @@ -767,38 +839,53 @@
                           throw new RuntimeException( error );
                       }
                   }
  -                else if( m_args[ i ].startsWith( "-" ) )
  +                else if( m_args[i].startsWith("-") )
                   {
  -                    final String error = "Unrecognized parameter: " + m_args[ i ];
  +                    final String error = "Unrecognized parameter: " + m_args[i];
                       throw new IllegalParameterException( error );
                   }
                   else
  -                {
  -                    final File file = new File( m_args[ i ] );
  +                {    
  +                    final File file = new File( m_args[i] );
                       if( file.exists() ) vector.add( file );
                   }
               }
  -            m_files = (File[])vector.toArray( new File[ 0 ] );
  +            m_files = (File[]) vector.toArray( new File[0] );
  +        }
  +
  +        public String getTarget()
  +        {
  +             return m_target;
           }
   
           public ServiceLoaderContext getContext()
           {
  -            return new ServiceLoaderContext( m_args, m_target, m_files, m_policy, m_verbose
);
  +             return new ServiceLoaderContext( m_args, m_target, m_files, m_policy, m_verbose
);
           }
   
           public File getConfigurationPath()
           {
  -            return m_path;
  +             return m_path;
           }
   
  -        /**
  -         * Returns the logging priority.
  -         * @return Priority the logging priority to apply.
  -         */
  +       /**
  +        * Returns the logging priority.
  +        * @return Priority the logging priority to apply.
  +        */
           public Priority getLoggingPriority()
           {
               return m_priority;
           }
  +
  +       /**
  +        * Returns the disposal policy.
  +        * @return boolean the disposal policy.
  +        */
  +        public boolean getDisposalPolicy()
  +        {
  +            return m_policy;
  +        }
       }
   }
  +
   
  
  
  

--
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