sgoeschl    2005/04/26 05:28:58

  Modified:    yaafi/src/java/org/apache/fulcrum/yaafi/cli Main.java
  Added:       yaafi/src/java/org/apache/fulcrum/yaafi/cli Getopt.java
  Log:
  Using this version now in production but is not stable yet
  
  Revision  Changes    Path
  1.5       +325 -49   
jakarta-turbine-fulcrum/yaafi/src/java/org/apache/fulcrum/yaafi/cli/Main.java
  
  Index: Main.java
  ===================================================================
  RCS file: 
/home/cvs/jakarta-turbine-fulcrum/yaafi/src/java/org/apache/fulcrum/yaafi/cli/Main.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- Main.java 31 Mar 2005 12:12:25 -0000      1.4
  +++ Main.java 26 Apr 2005 12:28:58 -0000      1.5
  @@ -22,19 +22,37 @@
   import org.apache.avalon.framework.activity.Disposable;
   import org.apache.avalon.framework.logger.ConsoleLogger;
   import org.apache.avalon.framework.logger.Logger;
  +import org.apache.avalon.framework.service.ServiceManager;
   import org.apache.fulcrum.yaafi.framework.container.ServiceContainer;
   import 
org.apache.fulcrum.yaafi.framework.factory.ServiceContainerConfiguration;
   import org.apache.fulcrum.yaafi.framework.factory.ServiceContainerFactory;
   
   
   /**
  - * An example of the embedding of a merlin kernel inside a main
  - * method.  The objective of the example is to demonstrate a
  - * simple embedded scenario.
  + * An example of the embedding of a YAAFI kernel inside an
  + * arbitrary application. 
    */
   
   public class Main implements Runnable, Disposable
   {
  +    /** parameter for the application name */
  +    public static final String APPLICATION_NAME = 
"yaafi.cli.applicationName";
  +    
  +    /** parameter for the application home directory */
  +    public static final String APPLICATION_HOME = 
"yaafi.cli.applicationHome";
  +    
  +    /** parameter for the application temporary directory */
  +    public static final String APPLICATION_TEMP = "yaafi.cli.tempHome";
  +    
  +    /** parameter for the application container configuration file */    
  +    public static final String APPLICATION_CONFIG = "yaafi.cli.config";
  +    
  +    /** parameter for setting a shutdown hook */
  +    public static final String APPLICATION_HASSHUTDOWNHOOK = 
"yaafi.cli.hasShutdownHook";
  +    
  +    /** parameter for blocking the main thread in Main.run() */
  +    public static final String APPLICATION_ISBLOCKING = 
"yaafi.cli.isBlocking";
  +    
       /** The service manager */
       private ServiceContainer container;
       
  @@ -44,50 +62,135 @@
        /** Thread for processing the shutdown notification of the JVM */
        private Thread shutdownThread;
        
  -     /** Do we terminate the main thread ?! */
  -     private boolean isServerMode;
  -     
  +     /** Do we block the invoking thread until the JVM terminates ?! */
  +     private boolean isBlocking;
  +
  +     /** Do we install a shutdown hook for the JVM ?! */
  +     private boolean hasShutdownHook;
  +
        /** The logger being used */
        private Logger logger;
        
        /** the interval to check for termination */
  -     private int sleepTime = 100; 
  +     private static int SLEEP_TIME = 100; 
       
        /** the name of the application */
        private String applicationName;
        
        /** the working directory */
  -     private File applicationHome;
  +     private String applicationHome;
   
        /** the temp directory */
  -     private File tempHome;   
  +     private String tempHome;         
  +     
  +     /** the command line arguments */
  +     private String[] args;
        
        /** is the instance properly initialized */
  -     private boolean isInitialized;
  +     private volatile boolean isInitialized;
  +
        
        /**
         * Constructor
         */
       public Main()
       {
  +        // default initialization
  +        
           this.containerConfigValue   = "./conf/containerConfiguration.xml";
  -        this.isServerMode                    = true;   
           this.logger                          = new ConsoleLogger();
  -        this.applicationHome                 = new File( new 
File("").getAbsolutePath() );
  -        this.tempHome                                = new File( 
System.getProperty("java.io.tmpdir",".") );
  -        this.applicationName         = "yaafi.cli";
  +        this.applicationHome                 = ".";
  +        this.tempHome                                = 
System.getProperty("java.io.tmpdir",".");
  +        this.applicationName         = "main";
  +        this.args                                    = ( args != null ? args 
: new String[0] );
  +        this.isBlocking                              = false;   
  +        this.hasShutdownHook         = true;
  +        this.isInitialized                   = false;
  +        
  +        // query the system properties
  +        
  +        this.containerConfigValue = System.getProperty( 
  +                 APPLICATION_CONFIG,
  +                 this.containerConfigValue
  +                 );
  +
  +        this.applicationName = System.getProperty( 
  +                 APPLICATION_NAME,
  +                 this.applicationName
  +                 );
  +
  +        this.applicationHome = System.getProperty( 
  +            APPLICATION_HOME, 
  +            this.applicationHome
  +            );
  +
  +        this.tempHome = System.getProperty( 
  +            APPLICATION_TEMP, 
  +            this.tempHome
  +            );        
  +    }
  +
  +     /**
  +      * Constructor
  +      * 
  +      * The following command line parameters are supported
  +      * <ul>
  +      *   <li>--yaafi.cli.applicationName name</li>
  +      *   <li>--yaafi.cli.applicationHome dir</li>
  +      *   <li>--yaafi.cli.tempHome dir</li>
  +      *   <li>--yaafi.cli.isBlocking [true|false]</li>
  +      *   <li>--yaafi.cli.hasShutdownHook [true|false]</li>
  +      *   <li>--yaafi.cli.config file</li>
  +      * </ul>
  +      * 
  +      * @param args the command line arguments
  +      */
  +    public Main( String[] args )
  +    {
  +        this();
  +        
  +        this.args = args;
  +                
  +        // parse the command line
  +
  +        Getopt getopt = new Getopt(this.args);
  +
  +        this.setApplicationName(
  +            getopt.getStringValue( APPLICATION_NAME, 
this.getApplicationName() )
  +            );
  +
  +        this.setApplicationHome( 
  +            getopt.getStringValue( APPLICATION_HOME, 
this.getApplicationHome() )
  +            );
  +
  +        this.setTempHome( 
  +            getopt.getStringValue( APPLICATION_TEMP, this.getTempHome() )
  +            );
  +
  +        this.setContainerConfigValue(
  +            getopt.getStringValue( APPLICATION_CONFIG, 
this.getContainerConfigValue() )
  +            );
  +
  +        this.setIsBlocking(
  +            getopt.getBooleanValue( APPLICATION_ISBLOCKING, this.isBlocking )
  +            );
  +
  +        this.setHasShutdownHook( 
  +            getopt.getBooleanValue( APPLICATION_HASSHUTDOWNHOOK, 
this.hasShutdownHook )
  +            );
       }
   
       /**
  -     * The main method
  +     * The main method.
  +     * 
        * @param args Command line arguments
  -     * @throws Exception
  +     * @throws Exception the execution failed
        */
       public static void main( String[] args ) throws Exception
       {
          int exitCode = 0;
          
  -       Main impl = new Main();
  +       Main impl = new Main(args);
          
          try
           {
  @@ -102,6 +205,27 @@
               System.exit(exitCode);
           }
       }
  +    
  +    /**
  +     * Determines the file location of the given name. If the name denotes
  +     * a relative file location it will be rsolved using the application
  +     * home directory.
  +     *  
  +     * @param baseDir the base directory 
  +     * @param fileName the filename 
  +     * @return the file
  +     */
  +    public static File makeAbsoluteFile( File baseDir, String name )
  +    {
  +        File result = new File(name);       
  +        
  +        if( result.isAbsolute() == false )
  +        {
  +            result = new File( baseDir, name ); 
  +        }
  +        
  +        return result;
  +    }    
           
       /**
        * Dispose the YAAFI container
  @@ -113,18 +237,17 @@
       }        
      
       /**
  +     * Runs the instance by initializing it and potentially blocking
  +     * the invoking thread depending on the configuration.
  +     *   
        * @see java.lang.Runnable#run()
        */
       public void run()
       {
           try
           {
  -            this.initialize();             
  -
  -            if( this.isServerMode() == false )
  -            {
  -                this.shutdown();
  -            }                                                
  +            this.initialize();
  +            this.onWait();
           }        
           catch (Throwable t)
           {
  @@ -133,35 +256,78 @@
               throw new RuntimeException(t.getMessage());
           }        
       }
  +
  +    /**
  +     * Depending on the configuration this method might block
  +     * the calling thread or return immediatly. We currently
  +     * poll a volatile variable which is not the most elegant
  +     * solution.
  +     */
  +    public void onWait()
  +    {
  +        while( this.isBlocking() && this.isInitialized() )
  +        {
  +            try
  +            {
  +                Thread.sleep(Main.SLEEP_TIME);
  +            }
  +            catch (InterruptedException e)
  +            {
  +                // ignore
  +            }
  +        }        
  +    }
       
  +    /**
  +     * Locates the file for the given file name.
  +     * @param baseDir the base directory 
  +     * @param fileName the filename 
  +     * @return the absolute path
  +     */
  +    public File makeAbsoluteFile( String fileName )
  +    {
  +        return Main.makeAbsoluteFile( 
  +            new File(this.getApplicationHome()),
  +            fileName 
  +            );
  +    }    
  +
       /////////////////////////////////////////////////////////////////////////
       // Generated getters & setters
       /////////////////////////////////////////////////////////////////////////
       
       /**
  -     * @return Returns the manager.
  +     * @return Returns the ServiceContainer interface
        */
       public ServiceContainer getServiceContainer()
       {
           return this.container;
       }
  -        
  +
  +    /**
  +     * @return Returns the ServiceManager interface
  +     */
  +    public ServiceManager getServiceManager()
  +    {
  +        return this.container;
  +    }
  +
       /**
        * @return Returns the applicationHome.
        */
  -    public File getApplicationHome()
  +    public String getApplicationHome()
       {
  -        return applicationHome;
  +        return this.applicationHome;
       }
       
       /**
        * @param applicationHome The applicationHome to set.
        */
  -    public void setApplicationHome(File applicationHome)
  +    public void setApplicationHome(String applicationHome)
       {
           this.applicationHome = applicationHome;
       }
  -    
  +
       /**
        * @return Returns the containerConfigValue.
        */
  @@ -179,37 +345,53 @@
       }
       
       /**
  -     * @return Returns the isServerMode.
  +     * @return Returns the isBlocking.
        */
  -    public boolean isServerMode()
  +    public boolean isBlocking()
       {
  -        return isServerMode;
  +        return isBlocking;
       }
       
       /**
  -     * @param isServerMode The isServerMode to set.
  +     * @param isBlocking The isBlocking to set.
        */
  -    public void setServerMode(boolean isServerMode)
  +    public void setIsBlocking(boolean isBlocking)
       {
  -        this.isServerMode = isServerMode;
  +        this.isBlocking = isBlocking;
       }
  -    
  +
  +    /**
  +     * @param isBlocking The isBlocking to set.
  +     */
  +    public void setIsBlocking(Boolean isBlocking)
  +    {
  +        this.isBlocking = isBlocking.booleanValue();
  +    }
  +
  +    /**
  +     * @param isBlocking The isBlocking to set.
  +     */
  +    public void setIsBlocking(String isBlocking)
  +    {
  +        this.isBlocking = Boolean.valueOf(isBlocking).booleanValue();
  +    }
  +
       /**
        * @return Returns the tempHome.
        */
  -    public File getTempHome()
  +    public String getTempHome()
       {
  -        return tempHome;
  +        return this.tempHome;
       }
       
       /**
        * @param tempHome The tempHome to set.
        */
  -    public void setTempHome(File tempHome)
  +    public void setTempHome(String tempHome)
       {
           this.tempHome = tempHome;
       }
  -    
  +
       /**
        * @return Returns the logger.
        */
  @@ -243,12 +425,110 @@
       }
       
       /**
  +     * @return Returns the args.
  +     */
  +    public String [] getArgs()
  +    {
  +        return args;
  +    }
  +    /**
  +     * @param args The args to set.
  +     */
  +    public void setArgs(String [] args)
  +    {
  +        this.args = args;
  +    }
  +    
  +    /**
  +     * @return Returns the hasShutdownHook.
  +     */
  +    public boolean hasShutdownHook()
  +    {
  +        return hasShutdownHook;
  +    }
  +    
  +    /**
  +     * @param hasShutdownHook The hasShutdownHook to set.
  +     */
  +    public void setHasShutdownHook(boolean hasShutdownHook)
  +    {
  +        this.hasShutdownHook = hasShutdownHook;
  +    }
  +
  +    /**
  +     * @param hasShutdownHook The hasShutdownHook to set.
  +     */
  +    public void setHasShutdownHook(Boolean hasShutdownHook)
  +    {
  +        this.hasShutdownHook = hasShutdownHook.booleanValue();
  +    }
  +
  +    /**
  +     * @param hasShutdownHook The hasShutdownHook to set.
  +     */
  +    public void setHasShutdownHook(String hasShutdownHook)
  +    {
  +        this.hasShutdownHook = 
Boolean.valueOf(hasShutdownHook).booleanValue();
  +    }
  +
  +    /**
  +     * @see java.lang.Object#toString()
  +     */
  +    public String toString()
  +    {
  +        StringBuffer result = new StringBuffer();
  +        StringBuffer argsLine = new StringBuffer();
  +        
  +        result.append(getClass().getName() + "@" + 
Integer.toHexString(hashCode()));
  +        
  +        result.append('[');
  +        result.append("workingDir=" + new File("").getAbsolutePath());       
 
  +        result.append(',');
  +
  +        result.append("args=");        
  +        
  +        for( int i=0; i<this.getArgs().length; i++ )
  +        {
  +            argsLine.append( this.getArgs()[i] );
  +         
  +            if( (i+1) < this.getArgs().length )
  +            {
  +                argsLine.append( " " );
  +            }
  +        }
  +        
  +        result.append( argsLine.toString() );
  +        result.append(',');
  +        
  +        result.append("applicationName=" + this.getApplicationName());       
 
  +        result.append(',');
  +        result.append("applicationHome=" + this.getApplicationHome());
  +        result.append(',');
  +        result.append("tempHome=" + this.getTempHome());
  +        result.append(',');
  +        result.append("logger=" + this.getLogger().getClass().getName());
  +        result.append(',');
  +        result.append("isBlocking=" + this.isBlocking);
  +        result.append(',');
  +        result.append("hasShutdownHook=" + this.hasShutdownHook());
  +        result.append(',');
  +        result.append("containerConfigValue=" + 
this.getContainerConfigValue());                
  +        result.append(']');
  +        
  +        return result.toString();                
  +    }
  +
  +    /**
        * @return Returns the isInitialized.
        */
  -    protected boolean isInitialized()
  +    public boolean isInitialized()
       {
           return isInitialized;
       }
  +
  +    /////////////////////////////////////////////////////////////////////////
  +    // Implementation
  +    /////////////////////////////////////////////////////////////////////////
       
       /**
        * @param isInitialized The isInitialized to set.
  @@ -257,19 +537,15 @@
       {
           this.isInitialized = isInitialized;
       }
  -    
  -    /////////////////////////////////////////////////////////////////////////
  -    // Implementation
  -    /////////////////////////////////////////////////////////////////////////
   
       /**
        * Initialize the instance
        * 
        * @throws Exception the initialization failed
        */
  -    protected void initialize() throws Exception
  +    public void initialize() throws Exception
       {       
  -        this.getLogger().info( "Initializing " + this.getClass().getName() );
  +        this.getLogger().debug( "Initializing " + this.getClass().getName() 
);
           
           ServiceContainerConfiguration config = new 
ServiceContainerConfiguration();
           
  @@ -279,11 +555,12 @@
           config.setApplicationRootDir( this.getApplicationHome() );
           config.setTempRootDir( this.getTempHome() );
           config.loadContainerConfiguration( this.getContainerConfigValue(), 
"auto" );
  +        
           this.container = ServiceContainerFactory.create( config );           
 
                
           // initialize shutdown hook of JVM for a server application
   
  -        if( this.isServerMode() )
  +        if( this.hasShutdownHook() )
           {
                this.getLogger().debug( "Registering shutdown hook" );
                Shutdown shutdown = new Shutdown( this );
  @@ -344,5 +621,4 @@
               this.getLogger().error(msg,e);
           }        
       }
  -    
   }
  
  
  
  1.1                  
jakarta-turbine-fulcrum/yaafi/src/java/org/apache/fulcrum/yaafi/cli/Getopt.java
  
  Index: Getopt.java
  ===================================================================
  package org.apache.fulcrum.yaafi.cli;
  
  /*
   * Copyright 2004 Apache Software Foundation
   * Licensed  under the  Apache License,  Version 2.0  (the "License");
   * you may not use  this file  except in  compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed  under the  License is distributed on an "AS IS" BASIS,
   * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
   * implied.
   *
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  /**
  * Extremly simply command line parsing class.
  */
  
  public class Getopt
  {
      /** the prefix for determining command line parameters, e.g "-" or "--" */
      private String prefix;
  
      /** the command line parameters */
      private String[] args;
  
      /**
       * Constructor
       * @param args the command line parameters
       */
      public Getopt( String[] args )
      {
          this(args,"--");
      }
  
      /**
       * Constructor.
       *
       * @param args the command line parameters
       * @param prefix the prefix for command line paramters
       */
      public Getopt( String[] args, String prefix )
      {
          this.prefix = prefix;
  
          if( args == null )
          {
              this.args = new String[0];
          }
          else
          {
              this.args = args;
          }
      }
  
      /**
       * @param option the option we are looking for
       * @return is the given option contained in the command line arguments?
       */
  
      public boolean contains( String option )
      {
          return( this.find(option) >= 0 ? true : false );
      }
  
      /**
       * @return the number of command line arguments
       */
      public int length()
      {
          return this.args.length;
      }
  
      /**
       * Returns the string value for the given option.
       * @param option the option
       * @return the associated value
       */
      public String getStringValue( String option )
      {
          return this.getValue(option);
      }
  
      /**
       * Returns the string value for the given option.
       * @param option the option
       * @param defaultValue the default value if the option is not defined
       * @return the associated value
       */
      public String getStringValue( String option, String defaultValue )
      {
          return this.getValue(option,defaultValue);
      }
  
      /**
       * Returns the boolean value for the given option.
       * @param option the option
       * @return the associated value
       */
  
      public boolean getBooleanValue( String option )
      {
          return Boolean.valueOf(this.getValue(option)).booleanValue();
      }
  
      /**
       * Returns the boolean value for the given option.
       * @param option the option
       * @param defaultValue the default value if the option is not defined
       * @return the associated value
       */
      public boolean getBooleanValue( String option, boolean defaultValue )
      {
          String temp = new Boolean(defaultValue).toString();
          return Boolean.valueOf(this.getValue(option,temp)).booleanValue();
      }
  
      /**
       * Get the given argument.
       * @param index the index of the command line argument
       * @return the commandl ine argument
       */
      private String getArg( int index )
      {
          return this.args[index];
      }
  
      /**
       * @option the option
       * @return the index of the give option or -1 otherwise
       */
      private int find( String option )
      {
          String strOption = this.prefix + option;
  
          // Iterate through all command line arguments and look for 
"-[chOption]"
  
          for( int i = 0; i < args.length; i++)
          {
              if ( args[i].equals( strOption ) )
              {
                  return i;
              }
          }
  
          return -1;
      }
  
      /**
       * Determines if a value is defined for the given option
       * @param option the given option
       * @return true if a value is defined
       */
      private boolean hasValue( String option )
      {
          return this.hasValue( this.find(option) );
      }
  
      /**
       * Determines if a value is defined for the given option
       * @param option the given option
       * @return true if a value is defined
       */
      private boolean hasValue( int index )
      {
          String value = null;
  
          if( (index+1) < this.length() )
          {
              value = this.getArg(index+1);
  
              if( value.startsWith(this.prefix) )
              {
                  return false;
              }
              else
              {
                  return true;
              }
          }
          else
          {
              return false;
          }
      }
  
      /**
       * Get the value of a command line option
       * @param option the option
       * @param defaultValue the default value if the option was not found
       * @return the value of the option
       */
      private String getValue( String option )
      {
          String value = this.getValue(option,null);
  
          if( value == null )
          {
              // the options is there but no value was defined by the caller
              String msg = "No value supplied for " + this.prefix + option;
              throw new IllegalArgumentException( msg );
          }
          else
          {
              return value;
          }
      }
  
      /**
       * Get the value of a command line option
       * @param option the option
       * @param defaultValue the default value if the option was not found
       * @return the value of the option
       */
      private String getValue( String option, String defaultValue )
      {
          int index = this.find(option);
  
          if( index < 0 )
          {
              // the option is not found
              return defaultValue;
          }
  
          if( this.hasValue(index) )
          {
              // a value is available for this option
              return this.getArg(index+1);
          }
          else
          {
              // the options is there but no value was defined by the caller
              String msg = "No value supplied for " + this.prefix + option;
              throw new IllegalArgumentException( msg );
          }
      }
  }
  
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to