avalon-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From akaras...@apache.org
Subject cvs commit: avalon-sandbox/kernel/unit/src/test/org/apache/avalon/merlin/unit Hello.java HelloComponent.java HelloComponent.xinfo StandardTestCase.java
Date Wed, 12 Nov 2003 07:55:11 GMT
akarasulu    2003/11/11 23:55:11

  Added:       kernel/unit .cvsignore maven.xml project.xml
                        snapshot.properties
               kernel/unit/conf block.xml config.xml
               kernel/unit/src/etc merlin.properties
               kernel/unit/src/java/org/apache/avalon/merlin/unit
                        AbstractMerlinTestCase.java
                        DefaultEmbeddedKernel.java UnitException.java
                        UnitHelper.java UnitRuntimeException.java
                        package.html
               kernel/unit/src/test/org/apache/avalon/merlin/unit
                        Hello.java HelloComponent.java HelloComponent.xinfo
                        StandardTestCase.java
  Log:
  
  
  Revision  Changes    Path
  1.1                  avalon-sandbox/kernel/unit/.cvsignore
  
  Index: .cvsignore
  ===================================================================
  maven.log
  velocity.log
  build.properties
  target
  snapshot.properties
  .classpath
  .project
  
  
  
  1.1                  avalon-sandbox/kernel/unit/maven.xml
  
  Index: maven.xml
  ===================================================================
  <project default="jar:install" xmlns:maven="jelly:maven" xmlns:j="jelly:core" xmlns:util="jelly:util" xmlns:ant="jelly:ant">
  
    <ant:property name="maven.jar.manifest.extensions.add" value="false"/>
  
    <preGoal name="jar:jar">
      <maven:snapshot project="${pom}"/>
      <j:set var="timestamp" value="${snapshotSignature.substring(pom.artifactId.length)}"/>
      <ant:property name="merlin.timestamp" value="${timestamp}"/>
      <ant:echo file="${basedir}/snapshot.properties">
  build.signature = ${snapshotSignature}
      </ant:echo>
      <j:forEach var="dep" items="${pom.dependencies}">
        <j:if test="${dep.getId() != 'junit:junit'}">
          <unzip src="${pom.getDependencyPath( dep.getId() )}" 
            dest="${maven.build.dir}/classes"/>
        </j:if>
      </j:forEach>
    </preGoal>
  
  </project>
  
  
  
  1.1                  avalon-sandbox/kernel/unit/project.xml
  
  Index: project.xml
  ===================================================================
  <?xml version="1.0" encoding="UTF-8"?>
  
  <project>
  
    <extend>${basedir}/../../project.xml</extend>
    <groupId>merlin</groupId>
    <id>merlin-unit</id>
    <name>Merlin Unit</name>
    <currentVersion>3.2.3-dev</currentVersion>
    <package>org.apache.avalon.merlin.unit</package>
  
    <inceptionYear>2003</inceptionYear>
    <shortDescription>Merlin Unit.</shortDescription>
  
    <description>
    Utility package that loads a merlin kernel based on a local 
    repository.
    </description>
    
    <dependencies>
  
      <dependency>
        <groupId>avalon-repository</groupId>
        <artifactId>avalon-repository-spi</artifactId>
        <version>1.1-dev</version>
      </dependency>
      <dependency>
        <groupId>avalon-repository</groupId>
        <artifactId>avalon-repository-impl</artifactId>
        <version>1.1-dev</version>
      </dependency>
  
      <dependency>
        <groupId>avalon-extension</groupId>
        <artifactId>avalon-extension-spi</artifactId>
        <version>1.0</version>
      </dependency>
  
      <dependency>
        <groupId>avalon-framework</groupId>
        <artifactId>avalon-framework-api</artifactId>
        <version>4.1.5</version>
      </dependency>
  
      <dependency>
        <groupId>avalon-meta</groupId>
        <artifactId>avalon-meta-api</artifactId>
        <version>1.2.1-dev</version>
      </dependency>
  
      <dependency>
        <groupId>avalon-composition</groupId>
        <artifactId>avalon-composition-api</artifactId>
        <version>1.2-dev</version>
      </dependency>
  
      <dependency>
        <groupId>avalon-activation</groupId>
        <artifactId>avalon-activation-api</artifactId>
        <version>1.2-dev</version>
      </dependency>
  
      <dependency>
        <groupId>merlin</groupId>
        <artifactId>merlin-kernel-spi</artifactId>
        <version>3.2-dev</version>
      </dependency>
  
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
      </dependency>
  
    </dependencies>
    
    <build>
  
      <sourceDirectory>${basedir}/src/java/</sourceDirectory>
      <unitTestSourceDirectory>${basedir}/src/test/</unitTestSourceDirectory>
  
      <unitTest>
        <includes>
          <include>**/*Test.*</include>
          <include>**/*TestCase.*</include>
        </includes>
        <excludes>
          <exclude>**/Abstract*.*</exclude>
        </excludes>
        <resources>
          <resource>
            <directory>${basedir}/src/test</directory>
            <includes>
              <include>**/*.x*</include>
            </includes>
          </resource>
          <resource>
            <directory>${basedir}/conf</directory>
            <targetPath>BLOCK-INF</targetPath>
            <includes>
              <include>block.xml</include>
            </includes>
          </resource>
        </resources>
      </unitTest>
  
      <resources>
        <resource>
          <directory>${basedir}/src/etc</directory>
          <includes> 
            <include>merlin.properties</include>
          </includes>
        </resource>
        <resource>
          <directory>${basedir}</directory>
          <includes> 
            <include>snapshot.properties</include>
          </includes>
        </resource>
      </resources>
  
      <jars></jars>
  
    </build>
  
  </project>
  
  
  
  1.1                  avalon-sandbox/kernel/unit/snapshot.properties
  
  Index: snapshot.properties
  ===================================================================
  
  build.signature = merlin-unit-20031105.083935
      
  
  
  1.1                  avalon-sandbox/kernel/unit/conf/block.xml
  
  Index: block.xml
  ===================================================================
  
  <container name="tutorial">
  
     <classloader>
       <classpath>
         <repository>
           <resource id="avalon-framework:avalon-framework-impl" version="4.1.5"/>
         </repository>
       </classpath>
     </classloader>
  
     <services>
       <service type="org.apache.avalon.merlin.unit.Hello">
         <source>hello</source>
       </service>
     </services>
  
     <component name="hello" class="org.apache.avalon.merlin.unit.HelloComponent"/>
  
  </container>
  
  
  
  1.1                  avalon-sandbox/kernel/unit/conf/config.xml
  
  Index: config.xml
  ===================================================================
  
  <targets>
  
    <target name="tutorial/hello">
      <configuration>
        <message>Hello!!</message>
      </configuration>
    </target>
  
  </targets>
  
  
  
  1.1                  avalon-sandbox/kernel/unit/src/etc/merlin.properties
  
  Index: merlin.properties
  ===================================================================
  
  #
  # the bootstrap kernel loader class
  #
  merlin.bootstrap.class=org.apache.avalon.merlin.kernel.impl.CLIKernelLoader
  
  #
  # the api classpath
  #
  merlin.api.classpath.0=avalon-framework:avalon-framework-api;4.1.5
  merlin.api.classpath.1=avalon-meta:avalon-meta-api;1.2.1-dev
  merlin.api.classpath.2=avalon-composition:avalon-composition-api;1.2-dev
  merlin.api.classpath.3=avalon-activation:avalon-activation-api;1.2-dev
  merlin.api.classpath.4=excalibur-lifecycle:excalibur-lifecycle-api;1.0
  merlin.api.classpath.5=avalon-extension:avalon-extension-spi;1.0
  merlin.api.classpath.6=merlin:merlin-kernel-spi;3.2-dev
  
  #
  # the spi classpath
  #
  merlin.spi.classpath.0=avalon-meta:avalon-meta-spi;1.2.1-dev
  merlin.spi.classpath.1=avalon-composition:avalon-composition-spi;1.2-dev
  merlin.spi.classpath.2=avalon-activation:avalon-activation-spi;1.2.1-dev
  merlin.spi.classpath.3=avalon-repository:avalon-repository-spi;1.1-dev
  
  #
  # the bootstrap classpath
  #
  merlin.impl.classpath.0=avalon-framework:avalon-framework-impl;4.1.5
  merlin.impl.classpath.1=avalon-meta:avalon-meta-impl;1.2.1-dev
  merlin.impl.classpath.2=avalon-extension:avalon-extension-impl;1.0
  merlin.impl.classpath.3=avalon-composition:avalon-composition-impl;1.2-dev
  merlin.impl.classpath.4=avalon-activation:avalon-activation-impl;1.2.2-dev
  merlin.impl.classpath.5=excalibur-i18n:excalibur-i18n;1.1
  merlin.impl.classpath.6=avalon-repository:avalon-repository-impl;1.1-dev
  merlin.impl.classpath.7=commons-cli:commons-cli;1.0
  merlin.impl.classpath.8=merlin:merlin-kernel-impl;3.2.1-dev
  merlin.impl.classpath.9=logkit:logkit;1.2
  merlin.impl.classpath.10=excalibur-event:excalibur-event;1.0.3
  merlin.impl.classpath.11=excalibur-configuration:excalibur-configuration;1.1
  merlin.impl.classpath.12=mx4j:mx4j-jmx;1.1.1
  merlin.impl.classpath.13=mx4j:mx4j-tools;1.1.1
  
  
  
  
  1.1                  avalon-sandbox/kernel/unit/src/java/org/apache/avalon/merlin/unit/AbstractMerlinTestCase.java
  
  Index: AbstractMerlinTestCase.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 2002-2003 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", "Apache Avalon", "Avalon Framework" 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.avalon.merlin.unit;
  
  import java.io.File;
  import java.util.Map;
  import java.util.Hashtable;
  import java.net.URL;
  
  import org.apache.avalon.activation.appliance.Appliance;
  import org.apache.avalon.activation.appliance.Block;
  import org.apache.avalon.composition.model.ContainmentModel;
  import org.apache.avalon.framework.logger.Logger;
  import org.apache.avalon.merlin.unit.DefaultEmbeddedKernel;
  
  import junit.framework.TestCase;
  
  /**
   * Abstract test case suitable for execution under Maven. 
   *
   * @author mcconnell@apache.org
   */
  public class AbstractMerlinTestCase extends TestCase
  {
      //-------------------------------------------------------------------
      // static
      //-------------------------------------------------------------------
  
      public static boolean MERLIN_DEBUG_OFF = false;
      public static boolean MERLIN_DEBUG_ON = true;
      public static boolean MERLIN_INFO_OFF = false;
      public static boolean MERLIN_INFO_ON = true;
  
      public static final File MAVEN_TARGET_CLASSES_DIR = 
        getProjectFile( "target/classes" );
  
      public static final File MAVEN_TARGET_TEST_CLASSES_DIR = 
        getProjectFile( "target/test-classes" );
  
      public static final File MERLIN_DEFAULT_CONFIG_FILE = 
        getProjectFile( "conf/config.xml" );
  
  
      //-------------------------------------------------------------------
      // state
      //-------------------------------------------------------------------
  
      private final DefaultEmbeddedKernel m_kernel;
  
      private final ContainmentModel m_test;
  
      private final Thread m_thread;
  
      private Logger m_logger;
  
      private Block m_block;
  
      //-------------------------------------------------------------------
      // constructors
      //-------------------------------------------------------------------
  
     /**
      * Creation of a new test case instance using the default info and debug
      * policies and a test container path of ${basedir}/target/classes
      */
      public AbstractMerlinTestCase()
      {
          this( "testcase" );
      }
  
     /**
      * Creation of a new test case instance using the default info and debug
      * policies and a test container path of ${basedir}/target/classes
      *
      * @param name the name of the test case
      */
      public AbstractMerlinTestCase( String name )
      {
          this( MAVEN_TARGET_CLASSES_DIR, null, MERLIN_INFO_OFF, MERLIN_DEBUG_OFF, name );
      }
  
     /**
      * Creation of a new test case instance using the test container 
      * path of ${basedir}/target/classes
      *
      * @param info information summary display policy
      * @param debug internal container debug policy
      * @param name the name of the test case
      */
      public AbstractMerlinTestCase( boolean info, boolean debug, String name )
      {
          this( MAVEN_TARGET_CLASSES_DIR, null, info, debug, name );
      }
  
     /**
      * Creation of a new test case instance using a supplied test container 
      * path, info and debug policies and unit test name.
      *
      * @param block the test container deployment path
      * @param targets the test container deployment path
      * @param info information summary display policy
      * @param debug internal container debug policy
      * @param name the name of the test case
      */
      public AbstractMerlinTestCase(
        File block, File targets, boolean info, boolean debug, String name )
      {
          super( name );
  
          //
          // validate arguments
          //
  
          if( block == null )
          {
              throw new NullPointerException( "block" );
          }
  
          if( !block.exists() )
          {
              final String error = 
                "Containment block [" + block + "] does not exist.";
              throw new IllegalStateException( error );
          }
  
          if( ( targets != null ) && !targets.exists() )
          {
              final String error = 
                "Configuration targets [" + targets + "] does not exist.";
              throw new IllegalStateException( error );
          }
  
          //
          // build the kernel
          //
  
          Map map = new Hashtable();
          map.put( "merlin.policy.info", new Boolean( info ) );
          map.put( "merlin.policy.debug", new Boolean( debug ) );
          map.put( "merlin.repository.dir", getMavenRepositoryDirectory() );
          map.put( "merlin.base.dir", getBaseDirectory() );
  
          try
          {
              m_kernel = new DefaultEmbeddedKernel( map );
              m_thread = new Thread( m_kernel );
              m_thread.start();
          }
          catch( Throwable e )
          {
              final String error = 
                "Runnable kernel establishment failure.";
              final String msg = UnitHelper.packException( error, e, true );
              throw new UnitRuntimeException( msg, null );
          }
  
          //
          // wait for the kernel to initialize
          //
  
  
          while( !m_kernel.established() )
          {
              try
              {
                  Thread.sleep( 100 );
              }
              catch( Throwable e )
              {
                  // wakeup
              }
          }
  
          //
          // check for kernel errors
          //
  
          if( m_kernel.getError() != null )
          {
              final String message = 
                "Internal error while attempting to establish the kernel.";
              final String error = 
                UnitHelper.packException( message, m_kernel.getError(), true );
              throw new UnitRuntimeException( error, null );
          }
  
          //
          // setup a logger for the testcase
          //
  
          m_logger = m_kernel.getLoggerForCategory( "testcase" );
  
          //
          // add a container holding the components that will
          // be used as services in the testcase
          //
  
          try
          {
              URL url = convertToURL( block );
              URL conf = convertToURL( targets );
              ContainmentModel root = m_kernel.getContainmentModel();
              m_test = root.addContainmentModel( url, conf );
          }
          catch( Throwable e )
          {
              final String message = 
                "Internal error while attempting to establish the test container.";
              final String error = UnitHelper.packException( message, e, true );
              throw new UnitRuntimeException( error, null );
          }
      }
  
      //--------------------------------------------------------
      // TestCase
      //--------------------------------------------------------
  
     /**
      * Startup the kernel based on the meta model established 
      * under the constructor.  The implementation will locate 
      * the test container and establish it as the reference for 
      * relative service lookups.
      */
      protected void setUp() throws Exception
      {
          m_kernel.startup();
  
          try
          {
              m_block = m_kernel.getBlock( m_test );
          }
          catch( Throwable e )
          {
              final String message = 
                "Internal error while attempting to resolve test block: " 
                + m_test;
              final String error = UnitHelper.packException( message, e, true );
              getLogger().error( error );
              throw new UnitException( error );
          }
      }
  
     /**
      * Shutdown the Merlin Kernel.
      */
      public void tearDown()
      {
          m_kernel.shutdown();
      }
  
      //--------------------------------------------------------
      // utilities
      //--------------------------------------------------------
  
     /**
      * Return the assigned logging channel for the test case.
      * @return the logging channel
      */
      protected Logger getLogger()
      {
          return m_logger;
      }
  
     /**
      * Resolve a service relative to the test container.  The supplied
      * path may be relative or absolute.  Relative paths will be resolved
      * relative to the test container wheras absolute paths will be resolved 
      * relative to the root container.
      *
      * @param path the absolute or relative path to a component type
      * @return the object resolved from an appliance defined by the supplied path
      * @exception UnitException if a resolution error occurs
      */
      protected Object resolve( String path ) throws Exception
      {
          if( path == null ) throw new NullPointerException( "path" );
  
          try
          {
              Appliance appliance = m_block.locate( path );
              if( appliance == null )
              {
                  final String problem = 
                    "Unknown appliance: " + path;
                  throw new IllegalArgumentException( problem );
              }
              return appliance.resolve();
          }
          catch( Throwable e )
          {
              final String error = 
                "Service resolution error from path: " + path;
              final String msg = UnitHelper.packException( error, e, false );
              throw new UnitException( msg, e );
          }
      }
  
      //--------------------------------------------------------
      // implementation
      //--------------------------------------------------------
  
     /**
      * Convert a supplied file to a url.  If the file argument is
      * null return null else return file.toURL().  
      * @param file the file to convert
      * @return the equivalent url
      */
      private URL convertToURL( File file )
      {
          if( file == null ) return null;
          try
          {
              return file.toURL();
          }
          catch( Throwable e )
          {
              final String error = 
                "Unable to convert file [" + file + "] to a url.";
              throw new UnitRuntimeException( error, e );
          }
      }
  
     /**
      * Convinience method to get the ${basedir}/[path] directory.
      * @return the deployment url
      */
      public static File getProjectFile( String path )
      {
          File base = getBaseDirectory();
          return new File( base, path );
      }
  
      private static File getBaseDirectory()
      {
          String basedir = System.getProperty( "basedir" );
          if( basedir != null ) return new File( basedir );
          return new File( "." );
      }
  
     /**
      * Return the maven system repository directory.
      * @return the system repository directory
      */
      private File getMavenRepositoryDirectory()
      {
          //
          // get ${maven.home.local} system property - this may 
          // be null in which case to fallback to ${user.home}/.maven
          //
  
          final String local = System.getProperty( "maven.home.local" );
          if( local != null )
          {
              try
              {
                  File sys = getDirectory( new File( local ) );
                  return getDirectory( new File( sys, "repository" ) );
              }
              catch( Throwable e )
              {
                  final String error = 
                    "Unable to resolve repository from ${maven.home.local}.";
                  throw new UnitRuntimeException( error, e );
              }
          }
          else
          {
              //
              // try to establish the repository relative to 
              // ${user.home}/.maven/repository
              //
  
              final String userHome = System.getProperty( "user.home" );
              if( userHome != null )
              {
                  try
                  {
                      File home = getDirectory( new File( userHome ) );
                      File maven = getDirectory( new File( home, ".maven" ) );
                      return getDirectory( new File( maven, "repository" ) );
                  }
                  catch( Throwable e )
                  {
                      final String error = 
                        "Unable to resolve the maven repository relative to ${user.home}.";
                      throw new UnitRuntimeException( error, e );
                  }
              }
              else
              {
                  //
                  // should never happen
                  //
  
                  final String error = 
                    "Unable to resolve maven repository.";
                  throw new IllegalStateException( error );
              }
          }
      }
  
      private File getDirectory( File file )
      {
          if( file == null ) throw new NullPointerException( "file" );
          if( file.exists() )
          {
              return file;
          }
          else
          {
              final String error =
                "Directory [" + file + "] does not exist.";
              throw new IllegalArgumentException( error );
          }
      }
  }
  
  
  
  
  1.1                  avalon-sandbox/kernel/unit/src/java/org/apache/avalon/merlin/unit/DefaultEmbeddedKernel.java
  
  Index: DefaultEmbeddedKernel.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 2002-2003 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", "Apache Avalon", "Avalon Framework" 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.avalon.merlin.unit;
  
  import java.io.File;
  import java.io.InputStream;
  import java.net.URL;
  import java.net.URLClassLoader;
  import java.util.ArrayList;
  import java.util.StringTokenizer;
  import java.util.Properties;
  import java.util.Map;
  import java.lang.reflect.Constructor;
  import java.lang.reflect.Method;
  
  import org.apache.avalon.activation.appliance.Block;
  import org.apache.avalon.composition.model.ContainmentModel;
  import org.apache.avalon.framework.logger.Logger;
  import org.apache.avalon.merlin.kernel.Kernel;
  import org.apache.avalon.merlin.kernel.KernelException;
  import org.apache.avalon.repository.Repository;
  import org.apache.avalon.repository.ProxyContext;
  import org.apache.avalon.repository.impl.DefaultFileRepository;
  import org.apache.avalon.repository.impl.DefaultAuthenticator;
  
  /**
   * Embedded kernel implementation.
   *
   * @author mcconnell@apache.org
   */
  public class DefaultEmbeddedKernel implements Runnable, Kernel
  {
      //--------------------------------------------------------
      // static
      //--------------------------------------------------------
  
      private static final String MERLIN_PROPERTIES_NAME = 
        "merlin.properties";
  
      private static final String MERLIN_API_CLASSPATH_KEY = 
        "merlin.api.classpath";
  
      private static final String MERLIN_SPI_CLASSPATH_KEY = 
        "merlin.spi.classpath";
  
      private static final String MERLIN_IMPL_CLASSPATH_KEY = 
        "merlin.impl.classpath";
  
      private static final String MERLIN_LOADER_CLASS =
        "org.apache.avalon.merlin.kernel.impl.DefaultLoader";
  
      private static final String STARTUP = "startup";
      private static final String SHUTDOWN = "shutdown";
      private static final String CONTINUE = "continue";
      private static final String EXIT = "exit";
  
      private static final URL DPML = createURL( "http://dpml.net/" );
      private static final URL IBIBLIO = createURL( "http://www.ibiblio.org/maven/" );
      private static final URL[] DEFAULT_REMOTE_URLS = new URL[]{ DPML, IBIBLIO };
  
      private static URL createURL( String path )
      {
          try
          {
              return new URL( path );
          }
          catch( Throwable e )
          {
              // will not happen
              final String error =  
                "Unexpect error while building url: " + path;
              throw new UnitRuntimeException( error, e );
          }
      }
  
      //--------------------------------------------------------
      // state
      //--------------------------------------------------------
  
      private final URLClassLoader m_classloader;
      private final Map m_map;
      private Repository m_repository;
      private Object m_loader;
      private String m_command = CONTINUE;
      private Throwable m_error;
      private Kernel m_kernel;
  
      private boolean m_started = false;
  
      //--------------------------------------------------------
      // constructors
      //--------------------------------------------------------
  
     /**
      * Creation of a new kernel loader using a set of supplied arguments.  
      * The supplied arguments are used to construct an embedded kernel
      * during thread iniitialization. The implementation established
      * a classloader containing the full merlin implementation in preparation
      * for execution under a seperate thread.  During thread execution the 
      * classloader is bound as the threads context classloader.
      * 
      * @param map the embedded kernel loader arguments
      * @see org.apache.avalon.merlin.kernel.impl.DefaultLoader
      */
      public DefaultEmbeddedKernel( Map map )
      {
          m_map = map;
  
          try
          {
              m_repository = createBootstrapRepository();
              Properties properties = loadBootstrapProperties();
              ClassLoader current = Thread.currentThread().getContextClassLoader();
              m_classloader = createClassLoader( current, m_repository, properties );
          }
          catch( Throwable e )
          {
              final String error = 
                "Internal error while attempting to build the loader.";
              throw new UnitRuntimeException( error, e );
          }
      }
  
     /**
      * Thread initialization during which a classloader holding the 
      * Merlin set of classes is assigned as the context classloader.  Using
      * this classloader a merlin kernel loader is created and the thread
      * listens for startup and shutdown requests.
      */
      public void run()
      {
          Thread.currentThread().setContextClassLoader( m_classloader );
  
          //
          // bootstrap the kernel loader
          //
  
          try
          {
              Class clazz = getLoaderClass();
              Constructor constructor = 
                clazz.getConstructor( new Class[]{ Repository.class, Map.class } );
              m_loader = constructor.newInstance( new Object[] { m_repository, m_map } );
  
              Method method = 
                clazz.getMethod( "getKernel", new Class[0] );
              m_kernel = (Kernel) method.invoke( m_loader, new Object[0] );
              setShutdownHook( this );
              m_started = true;
          }
          catch( Throwable e )
          {
              m_error = e;
              m_started = true;
          }
  
          while( m_command != EXIT )
          {
              if( m_error != null ) break;
              if( m_command == STARTUP )
              {
                  handleStartup();
              }
              else if( m_command == SHUTDOWN )
              {
                  handleShutdown();
              }
              else
              {
                  try
                  {
                      Thread.sleep( 100 );
                  }
                  catch( Throwable e )
                  {
                      // wakeup
                  }
              }
          }
      }
  
     /**
      * Utility method to test is the thread is fully established.
      * @return true if the thread has completed establishment
      */
      public boolean established()
      {
          return m_started;
      }
  
     /**
      * Utility method to return a throwable instance that may be established
      * during kernel startup as a result of a invlid block definition.
      * @return the error condition or null no error has occured
      */
      public Throwable getError()
      {
          return m_error;
      }
  
      //--------------------------------------------------------
      // Kernel
      //--------------------------------------------------------
  
     /**
      * Return the root containment model.
      * @return the containment model
      */
      public ContainmentModel getContainmentModel()
      {
          return m_kernel.getContainmentModel();
      }
  
     /**
      * Return the block matching the supplied model.
      * @return the containment block
      */
      public Block getBlock( ContainmentModel model ) throws KernelException
      {
          return m_kernel.getBlock( model );
      }
  
     /**
      * Return the root block.
      * @return the containment block
      */
      public Block getRootBlock()
      {
          return m_kernel.getRootBlock();
      }
  
     /**
      * Initiate the establishment of the root container.
      */
      public void startup()
      {
          if( m_command == EXIT ) throw new IllegalStateException("trminated");
          synchronized( m_command )
          {
              m_command = STARTUP;
              while( m_command.equals( STARTUP ) )
              {
                  try
                  {
                      Thread.sleep( 100 );
                  }
                  catch( Throwable e )
                  {
                      // wakeup
                  }
              }
              if( m_error != null )
              {
                  final String error = 
                    "Startup failure due to kernel error.";
                  throw new UnitRuntimeException( error, m_error );
              }
          }
      }
  
     /**
      * Initiate an orderly shutdown of the kernel.
      */
      public void shutdown()
      {
          if( m_error != null ) return;
          if( m_command == EXIT ) throw new IllegalStateException("trminated");
          synchronized( m_command )
          {
              m_command = SHUTDOWN;
              while( m_command.equals( SHUTDOWN ) )
              {
                  try
                  {
                      Thread.sleep( 100 );
                  }
                  catch( Throwable e )
                  {
                      // wakeup
                  }
              }
          }
      }
  
     /**
      * Return the Logger for the specified category.
      * @param category the category path
      * @return the logging channel
      */
      public Logger getLoggerForCategory( final String category )
      {
          return m_kernel.getLoggerForCategory( category );
      }
  
      //--------------------------------------------------------
      // implementation
      //--------------------------------------------------------
  
      private void handleStartup()
      {
          try
          {
              Class clazz = getLoaderClass();
              Method method = 
                clazz.getMethod( STARTUP, new Class[0] );
              method.invoke( m_loader, new Object[0] );
              m_command = CONTINUE;
          }
          catch( Throwable e )
          {
              final String error = 
                "Internal error while attempting to start the kernel.";
              m_error = new UnitRuntimeException( error, e );
              m_command = EXIT;
          }
      }
  
      private void handleShutdown()
      {
          try
          {
              Class clazz = getLoaderClass();
              Method method = 
                clazz.getMethod( SHUTDOWN, new Class[]{} );
              method.invoke( m_loader, new Class[0] );
              m_command = EXIT;
          }
          catch( Throwable e )
          {
              final String error = 
                "Internal error while attempting to shutdown the kernel.";
              m_error = new UnitRuntimeException( error, e );
              m_command = EXIT;
          }
      }
  
      private Class getLoaderClass()
      {
          try
          {
              return m_classloader.loadClass( MERLIN_LOADER_CLASS );
          }
          catch( Throwable e )
          {
              final String error = 
                "Internal error while attempting to load the kernel loader class.";
              throw new UnitRuntimeException( error, e );
          }
      }
  
     /**
      * Create the classloader holding the kernel.
      */
      private URLClassLoader createClassLoader( 
         ClassLoader loader, Repository repository, Properties properties ) throws Exception
      {
          URL[] api = getURLs( repository, properties, MERLIN_API_CLASSPATH_KEY );
          URL[] spi = getURLs( repository, properties, MERLIN_SPI_CLASSPATH_KEY );
          URL[] impl = getURLs( repository, properties, MERLIN_IMPL_CLASSPATH_KEY );
  
          URLClassLoader apiLoader = new URLClassLoader( api, loader );
          URLClassLoader spiLoader = new URLClassLoader( spi, apiLoader );
          URLClassLoader implLoader = new URLClassLoader( impl, spiLoader );
          return implLoader;
      }
  
     /**
      * Load the bootstrap properties.
      */
      private Properties loadBootstrapProperties()
      {
          try
          {
              ClassLoader classloader = Thread.currentThread().getContextClassLoader();
              InputStream input = 
                classloader.getResourceAsStream( MERLIN_PROPERTIES_NAME  );
              Properties properties = new Properties();
              properties.load( input );
              return properties;
          }
          catch( Throwable e )
          {
              final String error = 
                "Internal error while attempting to create the load bootstrap properties.";
              throw new UnitRuntimeException( error, e );
          }
      }
  
     /**
      * Return the repository from which we will build the kernel classloader.
      *
      * @return the repository
      */
      private Repository createBootstrapRepository() 
      {
          try
          {
              File repo = getSystemRepositoryDirectory();
              ProxyContext proxy = createProxyContext();
              URL[] hosts = createHostsSequence();
              return new DefaultFileRepository( repo, proxy, hosts );
          }
          catch( Throwable e )
          {
              final String error = 
                "Internal error while attempting to create the bootstrap repository.";
              throw new UnitRuntimeException( error, e );
          }
      }
  
     /**
      * Return an array of hosts based on the maven.repo.remote property value.
      * @return the array of remote hosts
      */
      private URL[] createHostsSequence() throws Exception
      {
          ArrayList list = new ArrayList();
          String path = System.getProperty( "maven.repo.remote" );
          if( path == null ) 
          {
              return DEFAULT_REMOTE_URLS;
          }
  
          StringTokenizer tokenizer = new StringTokenizer( path, "," );
          while( tokenizer.hasMoreElements() )
          {
              String token = tokenizer.nextToken();
              list.add( new URL( token ) );
          }
          return (URL[]) list.toArray( new URL[0] );
      }
  
     /**
      * Create of the proxy context.  If no proxy properties are declared a null
      * value is returned.  Proxy values are based assessment of  
      * properties maven.proxy.host, maven.proxy.port, maven.proxy.username and 
      * maven.proxy.password.
      *
      * @return the proxy context or null if not required
      */
      private ProxyContext createProxyContext()
      {
          String host = System.getProperty( "maven.proxy.host" );
          if( host != null )
          {
              String proxyPort = System.getProperty( "maven.proxy.port" );
              if( proxyPort == null ) throw new IllegalStateException( "maven.proxy.port" );
              int port = new Integer( proxyPort ).intValue();
              String username = System.getProperty( "maven.proxy.username" );
              DefaultAuthenticator authenticator = null;
              if( username != null )
              {
                  String password = System.getProperty( "maven.proxy.password" );
                  authenticator = new DefaultAuthenticator( username, password );
              }
              return new ProxyContext( host, port, authenticator );
          }
          else
          {
              return null;
          }
      }
  
     /**
      * Return the file corresponding  to the merlin system repository.
      * Currently hardwired to use the maven repository until we get the 
      * Merlin environment stuff in place.
      *
      * @return the system repository directory
      */
      public static File getSystemRepositoryDirectory()
      {
          final String system = System.getProperty( "maven.repo.local" );
          if( system != null )
          {
              return new File( new File( system ), "repository" );
          }
          else
          {
              final String home = System.getProperty( "maven.home" );
              if( home != null )
              {
                  return new File( new File( home ), "repository" );
              }
              else
              {
                  File user = new File( System.getProperty( "user.dir" ) );
                  return new File( user, ".merlin/system" );
              }
          }
      }
  
     /**
      * Consruct an array of URLs based on the declarations provided
      * in the supplied properties object.  Each URL is specified 
      * as a property value is mapped to a numbered property key in 
      * the form [key].n.  Each value is expressed as a repository
      * entry in the form [group]:[artifact];[version]. 
      * 
      * @param repository the repository from which artifacts shall be
      *   cached
      * @param properties the properties holding the keyed artifact ids
      * @param key the property name key
      * @return the array of urls
      */ 
      private static URL[] getURLs( 
         Repository repository, Properties properties, String key )
      {
          int i = 0;
          ArrayList list = new ArrayList();
          String label = getProperty( properties, key, i );
          while( label != null )
          {
              i++;
              list.add( getURL( repository, label ) );
              label = getProperty( properties, key, i );
          }
          return (URL[]) list.toArray( new URL[0] );
      }
  
     /**
      * Return a property key by concatonation of the supplied
      * key, the period character and an integer.
      * @param prioperties the properties set containing the keyed entry
      * @param key the partial key
      * @param i the key index
      * @return the value of the property [key].[i]
      */
      private static String getProperty( Properties properties, String key, int i )
      {
           final String label = key + "." + i;
           return properties.getProperty( label );
      }
  
     /**
      * Return a URL a a local repository cached resource replative to 
      * a suplied property value in the form [group]:[artifact];[version].
      * @param repository the repository under whcih resources are cached
      * @param item the encoded artifact identifier
      * @return the URL to the locally cached artifact
      */ 
      private static URL getURL( Repository repository, String item )
      {
           try
           {
               int n = item.indexOf( ":" );
               final String group = item.substring( 0, n );
              
               String artifact = null;
               String version = null;
               int m = item.indexOf( ";" );
               if( m > -1 )
               {
                   artifact = item.substring( n+1, m );
                   version = item.substring( m+1, item.length() );
               }
               else
               {
                   artifact = item.substring( n+1, item.length() );
               }
              
               return repository.getArtifact( group, artifact, version, "jar" );
           }
           catch( Throwable e )
           {
               final String error = 
                "Internal bootstrap error.  Unable to load item: " + item;
               throw new UnitRuntimeException( error, e );
           }
      }
  
     /**
      * Debug utility to dump a classloader url set to system.out.
      * The implementation will print url from the supplied loader 
      * following which it will print the parent recursively if the 
      * parent is a URLClassLoader.
      * 
      * @param loader the classloader to dump
      */
      private static void printClassLoader( URLClassLoader loader )
      {
          URL[] urls = loader.getURLs();
          for( int i=0; i<urls.length; i++ )
          {
              System.out.println( urls[i] );
          }
          if( loader.getParent() instanceof URLClassLoader )
          {
              System.out.println( "" );
              printClassLoader( (URLClassLoader) loader.getParent() );
          }
      }
  
     /**
      * Create a shutdown hook that will trigger shutdown of the supplied kernel.
      * @param kernel the kernel to be shutdown
      */
      private void setShutdownHook( final DefaultEmbeddedKernel kernel )
      {
          //
          // Create a shutdown hook to trigger clean disposal of the
          // Merlin kernel
          //
  
          Runtime.getRuntime().addShutdownHook(
            new Thread()
            {
                public void run()
                {
                    try
                    {
                        kernel.shutdown();
                    }
                    catch( Throwable e )
                    {
                        // ignore it
                    }
                }
            }
          );
      }
  }
  
  
  
  
  1.1                  avalon-sandbox/kernel/unit/src/java/org/apache/avalon/merlin/unit/UnitException.java
  
  Index: UnitException.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1997-2003 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 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 (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.merlin.unit;
  
  /**
   * Exception thrown in response to a load failure.
   *
   * @author <a href="mailto:dev@avalon.apache.org">Avalon Development Team</a>
   * @version CVS $Revision: 1.1 $ $Date: 2003/11/12 07:55:11 $
   */
  public class UnitException
      extends Exception
  {
      /**
       * The Throwable that caused this exception to be thrown.
       */
      private final Throwable m_throwable;
  
      /**
       * Construct a new <code>UnitException</code> instance.
       *
       * @param message The detail message for this exception.
       */
      public UnitException( final String message )
      {
          this( message, null );
      }
  
      /**
       * Construct a new <code>UnitException</code> instance.
       *
       * @param message The detail message for this exception.
       * @param throwable the root cause of the exception
       */
      public UnitException( final String message, final Throwable throwable )
      {
          super( message );
          m_throwable = throwable;
      }
  
      /**
       * Retrieve root cause of the exception.
       *
       * @return the root cause
       */
      public final Throwable getCause()
      {
          return m_throwable;
      }
  }
  
  
  
  1.1                  avalon-sandbox/kernel/unit/src/java/org/apache/avalon/merlin/unit/UnitHelper.java
  
  Index: UnitHelper.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 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", "Apache Avalon", "Avalon Framework" 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.avalon.merlin.unit;
  
  import java.io.PrintWriter;
  import java.io.StringWriter;
  import java.lang.reflect.Method;
  import java.util.StringTokenizer;
  
  /**
   * General utilities supporting the packaging of exception messages.
   * @author <a href="mailto:mcconnell@osm.net">Stephen McConnell</a>
   */
  public class UnitHelper
  {
      private static final String LINE_SEPARATOR = System.getProperty( "line.separator" );
  
      /**
       * Returns the exception and causal exceptions as a formatted string.
       * @param message the header message
       * @param e the exception
       * @return String the formatting string
       */
      public static String packException( final String message, final Throwable e )
      {
          return packException( message, e, true );
      }
  
      /**
       * Returns the exception and causal exceptions as a formatted string.
       * @param message the header message
       * @param e the exception
       * @return String the formatting string
       */
      public static String packException( 
         final String message, final Throwable e, boolean stack )
      {
          StringBuffer buffer = new StringBuffer();
          buffer.append( message );
          if( e == null )
          {
              return buffer.toString();
          } else
          {
              buffer.append( "\n" );
              buffer.append( 
  "-------------------------------------------------------------------" );
              buffer.append( "\nException: " + e.getClass().getName() );
              buffer.append( "\nMessage: " + e.getMessage() );
              packCause( buffer, getCause( e ) ).toString();
          }
          Throwable root = getLastThrowable( e );
          if( (root != null) && stack )
          {
              buffer.append( 
  "\n\n---- stack trace --------------------------------------------------" );
              String[] trace = captureStackTrace( root );
              for( int i = 0; i < trace.length; i++ )
              {
                  buffer.append( "\n" + trace[i] );
              }
          }
          buffer.append( 
  "\n-------------------------------------------------------------------" );
          return buffer.toString();
      }
  
      private static StringBuffer packCause( StringBuffer buffer, Throwable cause )
      {
          if( cause == null )
          {
              return buffer;
          }
          buffer.append( "\n\nCause: " + cause.getClass().getName() );
          buffer.append( "\nMessage: " + cause.getMessage() );
          return packCause( buffer, getCause( cause ) );
      }
  
      private static Throwable getLastThrowable( Throwable exception )
      {
          Throwable cause = getCause( exception );
          if( cause != null )
          {
              return getLastThrowable( cause );
          }
          return exception;
      }
  
      private static Throwable getCause( Throwable exception )
      {
          if( exception == null )
          {
              throw new NullPointerException( "exception" );
          }
  
          try
          {
              Method method = exception.getClass().getMethod( "getCause", new Class[0] );
              return (Throwable) method.invoke( exception, new Object[0] );
          } catch( Throwable e )
          {
              return null;
          }
      }
  
      /**
       * Captures the stack trace associated with this exception.
       *
       * @param throwable a <code>Throwable</code>
       * @return an array of Strings describing stack frames.
       */
      private static String[] captureStackTrace( final Throwable throwable )
      {
          final StringWriter sw = new StringWriter();
          throwable.printStackTrace( new PrintWriter( sw, true ) );
          return splitString( sw.toString(), LINE_SEPARATOR );
      }
  
      /**
       * Splits the string on every token into an array of stack frames.
       *
       * @param string the string to split
       * @param onToken the token to split on
       * @return the resultant array
       */
      private static String[] splitString( final String string, final String onToken )
      {
          final StringTokenizer tokenizer = new StringTokenizer( string, onToken );
          final String[] result = new String[tokenizer.countTokens()];
  
          for( int i = 0; i < result.length; i++ )
          {
              result[i] = tokenizer.nextToken();
          }
  
          return result;
      }
  
      private static void printCause( java.io.PrintStream out, Throwable e )
      {
          Throwable cause = getCause( e );
          out.println( "Cause: " + cause.toString() );
          if( getCause( cause ) != null )
          {
              printCause( out, cause );
          }
      }
  }
  
  
  
  1.1                  avalon-sandbox/kernel/unit/src/java/org/apache/avalon/merlin/unit/UnitRuntimeException.java
  
  Index: UnitRuntimeException.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1997-2003 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 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 (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.merlin.unit;
  
  /**
   * Class from which all exceptions should inherit.
   * Allows recording of nested exceptions.
   *
   * @author <a href="mailto:dev@avalon.apache.org">Avalon Development Team</a>
   * @version CVS $Revision: 1.1 $ $Date: 2003/11/12 07:55:11 $
   */
  public class UnitRuntimeException
      extends RuntimeException
  {
      private final Throwable m_throwable;
  
      /**
       * Construct a new <code>UnitRuntimeException</code> instance.
       *
       * @param message The detail message for this exception.
       * @param throwable the root cause of the exception
       */
      public UnitRuntimeException( final String message, final Throwable throwable )
      {
          super( message );
          m_throwable = throwable;
      }
  
      /**
       * Retrieve root cause of the exception.
       *
       * @return the root cause
       */
      public final Throwable getCause()
      {
          return m_throwable;
      }
  }
  
  
  
  1.1                  avalon-sandbox/kernel/unit/src/java/org/apache/avalon/merlin/unit/package.html
  
  Index: package.html
  ===================================================================
  
  <body>
  <p>
  Pending.
  </p>
  </body>
  
  
  
  
  1.1                  avalon-sandbox/kernel/unit/src/test/org/apache/avalon/merlin/unit/Hello.java
  
  Index: Hello.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 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", "Apache Avalon", "Avalon Framework" 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.avalon.merlin.unit;
  
  public interface Hello 
  {
     /**
      * Return the hello message.
      * @return the message
      */
      public String getMessage();
  }
  
  
  
  1.1                  avalon-sandbox/kernel/unit/src/test/org/apache/avalon/merlin/unit/HelloComponent.java
  
  Index: HelloComponent.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 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", "Apache Avalon", "Avalon Framework" 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.avalon.merlin.unit;
  
  import org.apache.avalon.framework.logger.Logger;
  import org.apache.avalon.framework.logger.LogEnabled;
  import org.apache.avalon.framework.activity.Disposable;
  import org.apache.avalon.framework.activity.Initializable;
  import org.apache.avalon.framework.configuration.Configurable;
  import org.apache.avalon.framework.configuration.ConfigurationException;
  import org.apache.avalon.framework.configuration.Configuration;
  
  /**
   * A sample component.  This component implements a number 
   * of lifecycle interface.  Each lifecycle interface is a stage
   * that is processed by a container during the deployment of 
   * the component.  The lifecycle stages demonstrated here include
   * LogEnabled (association of a logging channel), Initializable
   * (initialization of the component), Executable (component
   * execution), and Disposable (componet disposal).  PLease note 
   * that all lifecycle stages are optional.
   *
   * @avalon.component version="1.0" name="hello"
   */
  public class HelloComponent 
    implements LogEnabled, Configurable, Initializable, Disposable, Hello
  {
  
     //------------------------------------------------------------
     // state
     //------------------------------------------------------------
  
     /**
      * Internal reference to the logging channel supplied to us 
      * by the container. 
      */
      private Logger m_logger;
  
      private String m_message;
  
     //------------------------------------------------------------
     // Hello
     //------------------------------------------------------------
  
     /**
      * Return the hello message.
      * @return the message
      */
      public String getMessage()
      {
          return m_message;
      }
  
     //------------------------------------------------------------
     // lifecycle
     //------------------------------------------------------------
  
     /**
      * Supply of a logging channel by the container.
      *
      * @param logger the logging channel for this component
      */
      public void enableLogging( final Logger logger )
      {
          m_logger = logger;
          getLogger().info( "logging" );
      }
  
     /**
      * Configuration of the component by the container.
      * @exception Exception if a configuration error occurs
      */
      public void configure( Configuration config ) throws ConfigurationException
      {
          getLogger().info( "configuration" );
          m_message = config.getChild( "message" ).getValue( "unknown" );
      }
  
     /**
      * Initialization of the component by the container.
      * @exception Exception if an initialization error occurs
      */
      public void initialize() throws Exception
      {
          getLogger().info( "initialization" );
      }
  
     /**
      * Component disposal trigger by the container during which
      * the component will release consumed resources.
      */
      public void dispose()
      {
          getLogger().info( "disposal" );
          m_logger = null;
      }
  
     /**
      * Return the logging channel assigned to us by the container.
      * @return the logging channel
      */
      private Logger getLogger()
      {
          return m_logger;
      }
  
  }
  
  
  
  1.1                  avalon-sandbox/kernel/unit/src/test/org/apache/avalon/merlin/unit/HelloComponent.xinfo
  
  Index: HelloComponent.xinfo
  ===================================================================
  <?xml version="1.0" encoding="ISO-8859-1"?>
  <!DOCTYPE type PUBLIC "-//AVALON/Type DTD Version 1.0//EN" "http://avalon.apache.org/dtds/meta/type_1_1.dtd" >
  
  <type>
    <info>
      <name>hello</name>
      <version>1.0.0</version>
      <lifestyle>singleton</lifestyle>
    </info>
    <services>
      <service type="org.apache.avalon.merlin.unit.Hello"/>
    </services>
  </type>
  
  
  1.1                  avalon-sandbox/kernel/unit/src/test/org/apache/avalon/merlin/unit/StandardTestCase.java
  
  Index: StandardTestCase.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 2002-2003 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", "Apache Avalon", "Avalon Framework" 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.avalon.merlin.unit;
  
  import org.apache.avalon.merlin.unit.AbstractMerlinTestCase;
  
  /**
   * Abstract Merlin Test Case.
   *
   * @author mcconnell@apache.org
   */
  public class StandardTestCase extends AbstractMerlinTestCase
  {
  
      //--------------------------------------------------------
      // constructors
      //--------------------------------------------------------
  
     /**
      * @param name the name of the test case
      * @param root the merlin system install directory
      */
      public StandardTestCase( String name )
      {
          super( 
            MAVEN_TARGET_TEST_CLASSES_DIR, 
            MERLIN_DEFAULT_CONFIG_FILE, 
            MERLIN_DEBUG_OFF, 
            MERLIN_INFO_OFF, 
            name );
      }
  
      //--------------------------------------------------------
      // testcase
      //--------------------------------------------------------
  
      public void testServiceResolution() throws Exception
      {
          Hello hello = (Hello) resolve( "hello" );
          assertTrue( hello != null );
          getLogger().info( "Message from hello service: " + hello.getMessage() );
      }
  }
  
  
  
  

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


Mime
View raw message