You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by pa...@apache.org on 2002/07/17 02:15:51 UTC

cvs commit: jakarta-commons-sandbox/daemon/src/java/org/apache/commons/launcher ChildMain.java LaunchTask.java Launcher.java LauncherException.java

patrickl    2002/07/16 17:15:51

  Modified:    daemon/src/java LauncherBootstrap.java
               daemon/src/java/org/apache/commons/launcher ChildMain.java
                        LaunchTask.java Launcher.java
  Removed:     daemon/src/java/org/apache/commons/launcher
                        LauncherException.java
  Log:
  Refactoring to remove unnecessary code and simplify the logging of errors
  
  Revision  Changes    Path
  1.6       +7 -43     jakarta-commons-sandbox/daemon/src/java/LauncherBootstrap.java
  
  Index: LauncherBootstrap.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/daemon/src/java/LauncherBootstrap.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -r1.5 -r1.6
  --- LauncherBootstrap.java	15 Jul 2002 19:58:57 -0000	1.5
  +++ LauncherBootstrap.java	17 Jul 2002 00:15:51 -0000	1.6
  @@ -188,55 +188,19 @@
               // method as we need it for printing the usage statement
               Method getLocalizedStringMethod = launcherClass.getDeclaredMethod("getLocalizedString", new Class[]{ String.class });
   
  -            // Parse the command line arguments
  -            int currentArg = 0;
  -
  -            // Get standard launcher arguments
  -            for ( ; currentArg < args.length; currentArg++) {
  -                // If we find a "-" argument or an argument without a
  -                // leading "-", there are no more standard launcher arguments
  -                if ("-".equals(args[currentArg])) {
  -                    currentArg++;
  -                    break;
  -                } else if (args[currentArg].length() > 0 && !"-".equals(args[currentArg].substring(0, 1))) {
  -                    break;
  -                } else if ("-help".equals(args[currentArg])) {
  -                    throw new IllegalArgumentException();
  -                } else if ("-executablename".equals(args[currentArg])) {
  -                    if (currentArg + 1 < args.length) {
  -                        Field executablePropNameField = launcherClass.getDeclaredField("executablePropName");
  -                        System.setProperty((String)executablePropNameField.get(null), args[++currentArg]);
  -                    } else {
  -                        throw new IllegalArgumentException(args[currentArg] + " " + getLocalizedStringMethod.invoke(null, new Object[]{ "missing.arg" }));
  -                    }
  -                } else if ("-verbose".equals(args[currentArg])) {
  -                    Method setVerboseMethod = launcherClass.getDeclaredMethod("setVerbose", new Class[]{ boolean.class });
  -                    setVerboseMethod.invoke(null, new Object[]{ new Boolean(true) });
  -                } else {
  -                    throw new IllegalArgumentException(args[currentArg] + " " + getLocalizedStringMethod.invoke(null, new Object[]{ "invalid.arg" }));
  -                }
  -            }
  -
  -            // Shift out standard launcher arguments
  -            String[] startArgs = new String[args.length - currentArg];
  -            for (int i = 0; i < startArgs.length; i++)
  -                startArgs[i] = args[i + currentArg];
  -
               // Invoke the LAUNCHER_MAIN_CLASS_NAME class' start() method.
               // If the ant.class.path property is not set correctly in the 
               // LAUNCHER_PROPS_FILE_NAME, this will throw an exception.
               Method startMethod = launcherClass.getDeclaredMethod("start", new Class[]{ String[].class, File.class });
  -            startMethod.invoke(null, new Object[]{ startArgs, launchFile });
  +            startMethod.invoke(null, new Object[]{ args, launchFile });
   
          } catch (Throwable t) {
  -            String message = t.getMessage();
  -            try {
  -                Method errorMethod = launcherClass.getMethod("error", new Class[]{ Throwable.class });
  -                errorMethod.invoke(null, new Object[]{ t });
  -            } catch (Exception e) {
  -                t.printStackTrace();
  -                System.exit(1);
  -            }
  +
  +           String message = t.getMessage();
  +           if (message != null)
  +               System.err.println(message);
  +           System.exit(1);
  +
           }
   
           // Always exit cleanly
  
  
  
  1.5       +1 -0      jakarta-commons-sandbox/daemon/src/java/org/apache/commons/launcher/ChildMain.java
  
  Index: ChildMain.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/daemon/src/java/org/apache/commons/launcher/ChildMain.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- ChildMain.java	14 Jul 2002 20:16:15 -0000	1.4
  +++ ChildMain.java	17 Jul 2002 00:15:51 -0000	1.5
  @@ -178,6 +178,7 @@
           } catch (Throwable t) {
               Launcher.setVerbose(true);
               Launcher.error(t);
  +            System.exit(1);
           }
   
       }
  
  
  
  1.10      +2 -0      jakarta-commons-sandbox/daemon/src/java/org/apache/commons/launcher/LaunchTask.java
  
  Index: LaunchTask.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/daemon/src/java/org/apache/commons/launcher/LaunchTask.java,v
  retrieving revision 1.9
  retrieving revision 1.10
  diff -u -r1.9 -r1.10
  --- LaunchTask.java	16 Jul 2002 06:42:28 -0000	1.9
  +++ LaunchTask.java	17 Jul 2002 00:15:51 -0000	1.10
  @@ -732,6 +732,8 @@
               if (Launcher.isStopped())
                   throw new BuildException();
   
  +        } catch (BuildException be) {
  +            throw be;
           } catch (Exception e) {
               if (Launcher.isStopped())
                   throw new BuildException(Launcher.getLocalizedString("launch.task.stopped", this.getClass().getName()));
  
  
  
  1.11      +120 -125  jakarta-commons-sandbox/daemon/src/java/org/apache/commons/launcher/Launcher.java
  
  Index: Launcher.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/daemon/src/java/org/apache/commons/launcher/Launcher.java,v
  retrieving revision 1.10
  retrieving revision 1.11
  diff -u -r1.10 -r1.11
  --- Launcher.java	16 Jul 2002 06:42:28 -0000	1.10
  +++ Launcher.java	17 Jul 2002 00:15:51 -0000	1.11
  @@ -66,6 +66,7 @@
   import org.apache.commons.launcher.types.ArgumentSet;
   import org.apache.commons.launcher.types.JVMArgumentSet;
   import org.apache.commons.launcher.types.SysPropertySet;
  +import org.apache.tools.ant.BuildException;
   import org.apache.tools.ant.Main;
   import org.apache.tools.ant.Project;
   import org.apache.tools.ant.ProjectHelper;
  @@ -163,7 +164,7 @@
       /**
        * Cached log
        */
  -    private static PrintStream log = null;
  +    private static PrintStream log = System.err;
   
       /**
        * The miminizedWindowTitle system property name.
  @@ -244,31 +245,6 @@
   
       //---------------------------------------------------------- Static Methods
   
  -    /**
  -     * Check the started flag. If the started flag is true, this method throws
  -     * an exception. If the started flag is set to false, this method returns.
  -     *
  -     * @throws LauncherException when the started flag is true
  -     */
  -    private static synchronized void checkStarted() throws LauncherException {
  -
  -        if (Launcher.started == true)
  -            throw new LauncherException(Launcher.getLocalizedString("launch.already.started"));
  -
  -    }
  -
  -    /**
  -     * Check the stopped flag. If the stopped flag is true, this method throws
  -     * an exception. If the stopped flag is set to false, this method returns.
  -     *
  -     * @throws LauncherException when the stopped flag is true
  -     */
  -    private static synchronized void checkStopped() throws LauncherException {
  -
  -        if (Launcher.stopped == true)
  -            throw new LauncherException(Launcher.getLocalizedString("launch.already.stopped"));
  -
  -    }
   
       /**
        * Get the started flag.
  @@ -294,46 +270,52 @@
   
       /**
        * Start the launching process. This method is essential the
  -     * <code>main(String[])<code> method for this class except that exceptions
  -     * are not caught and this method never invokes {@link System#exit(int)}.
  -     * This method is designed for applications that wish to invoke this class
  -     * directly from within their application's code.
  +     * <code>main(String[])<code> method for this class except that this method
  +     * never invokes {@link System#exit(int)}. This method is designed for
  +     * applications that wish to invoke this class directly from within their
  +     * application's code.
        *
        * @param args command line arguments
        * @param launchFile the XML file to execute
  -     * @throws LauncherException if any error occurs
  +     * @return true if this method completed without error and false if an
  +     *  error occurred or this method was stopped
        * @throws IllegalArgumentException if any error parsing the args parameter
        *  occurs
        */
  -    public static void start(String[] args, File launchFile)
  -        throws LauncherException, IllegalArgumentException
  +    public static boolean start(String[] args, File launchFile)
  +        throws IllegalArgumentException
      {
   
           // Check make sure that neither this method or the stop() method is
           // already running since we do not support concurrency
           synchronized (Launcher.lock) {
  -            Launcher.checkStarted();
  -            Launcher.checkStopped();
  +            if (Launcher.isStarted() || Launcher.isStopped())
  +                return false;
               Launcher.setStarted(true);
           }
   
  -        // Cache the current class loader for this thread and set the class
  -        // loader before running Ant. Note that we only set the class loader
  -        // if we are running a Java version earlier than 1.4 as on 1.4 this
  -        // causes unnecessary loading of the XML parser classes.
  -        ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
  -        boolean lessThan14 = true;
  -        try {
  -            Class.forName("java.lang.CharSequence");
  -            lessThan14 = false;
  -        } catch (ClassNotFoundException cnfe) {
  -            // If this class does not exist, then we are not running Java 1.4
  -        }
  -        if (lessThan14)
  -            Thread.currentThread().setContextClassLoader(Launcher.class.getClassLoader());
  +        boolean returnValue = true;
  +        ClassLoader parentLoader = null;
  +        Thread shutdownHook = new Thread(new Launcher());
  +        Runtime runtime = Runtime.getRuntime();
   
           try {
   
  +            // Cache the current class loader for this thread and set the class
  +            // loader before running Ant. Note that we only set the class loader
  +            // if we are running a Java version earlier than 1.4 as on 1.4 this
  +            // causes unnecessary loading of the XML parser classes.
  +            parentLoader = Thread.currentThread().getContextClassLoader();
  +            boolean lessThan14 = true;
  +            try {
  +                Class.forName("java.lang.CharSequence");
  +                lessThan14 = false;
  +            } catch (ClassNotFoundException cnfe) {
  +                // If this class does not exist, then we are not running Java 1.4
  +            }
  +            if (lessThan14)
  +                Thread.currentThread().setContextClassLoader(Launcher.class.getClassLoader());
  +
               Project project = new Project();
   
               // Set the project's class loader
  @@ -363,6 +345,29 @@
               // Parse the arguments
               int currentArg = 0;
   
  +            // Get standard launcher arguments
  +            for ( ; currentArg < args.length; currentArg++) {
  +                // If we find a "-" argument or an argument without a
  +                // leading "-", there are no more standard launcher arguments
  +                if ("-".equals(args[currentArg])) {
  +                    currentArg++;
  +                    break;
  +                } else if (args[currentArg].length() > 0 && !"-".equals(args[currentArg].substring(0, 1))) {
  +                    break;
  +                } else if ("-help".equals(args[currentArg])) {
  +                    throw new IllegalArgumentException();
  +                } else if ("-executablename".equals(args[currentArg])) {
  +                    if (currentArg + 1 < args.length)
  +                        System.setProperty(Launcher.EXECUTABLE_PROP_NAME, args[++currentArg]);
  +                    else
  +                        throw new IllegalArgumentException(args[currentArg] + " " + Launcher.getLocalizedString("missing.arg"));
  +                } else if ("-verbose".equals(args[currentArg])) {
  +                    Launcher.setVerbose(true);
  +                } else {
  +                    throw new IllegalArgumentException(args[currentArg] + " " + Launcher.getLocalizedString("invalid.arg"));
  +                }
  +            }
  +
               // Get target
               String target = null;
               if (currentArg < args.length)
  @@ -424,24 +429,33 @@
                   throw new IllegalArgumentException(target + " " + Launcher.getLocalizedString("invalid.target"));
   
               // Execute the target
  -            Thread shutdownHook = new Thread(new Launcher());
  -            Runtime runtime = Runtime.getRuntime();
               try {
                   runtime.addShutdownHook(shutdownHook);
               } catch (NoSuchMethodError nsme) {
                   // Early JVMs do not support this method
               }
               project.executeTarget(target);
  -            try {
  -                runtime.removeShutdownHook(shutdownHook);
  -            } catch (NoSuchMethodError nsme) {
  -                // Early JVMs do not support this method
  -            }
   
           } catch (Throwable t) {
  -            throw new LauncherException(t);
  +            // Log any errors
  +            returnValue = false;
  +            String message = t.getMessage();
  +            if (t instanceof IllegalArgumentException) {
  +                Launcher.error(message, true);
  +            } else {
  +                if (Launcher.verbose)
  +                    Launcher.error(t);
  +                else
  +                    Launcher.error(message, false);
  +            }
           } finally {
               synchronized (Launcher.lock) {
  +                // Remove the shutdown hook
  +                try {
  +                    runtime.removeShutdownHook(shutdownHook);
  +                } catch (NoSuchMethodError nsme) {
  +                    // Early JVMs do not support this method
  +                }
                   // Reset the class loader after running Ant
                   Thread.currentThread().setContextClassLoader(parentLoader);
                   // Reset stopped flag
  @@ -451,14 +465,16 @@
               }
           }
   
  +        return returnValue;
  +
       }
   
       /**
        * Interrupt the {@link #start(String[], File)} method. This is done
        * by forcing the current or next scheduled invocation of the
  -     * {@link LaunchTask#execute()} method to throw and exception. In addition,
  +     * {@link LaunchTask#execute()} method to throw an exception. In addition,
        * this method will terminate any synchronous child processes that any
  -     * instances of the {@link LaunchTask} class  have launched. Note, however,
  +     * instances of the {@link LaunchTask} class have launched. Note, however,
        * that this method will <b>not</b> terminate any asynchronous child
        * processes that have been launched. Accordingly, applications that use
        * this method are encouraged to always set the LaunchTask.TASK_NAME task's
  @@ -467,23 +483,27 @@
        * After this method has been executed, it will not return until is safe to
        * execute the {@link #start(String[], File)} method.
        *
  -     * @throws LauncherException if any error occurs
  +     * @return true if this method completed without error and false if an
  +     *  error occurred or the launch process is already stopped
        */
  -    public static void stop() throws LauncherException {
  +    public static boolean stop() {
   
           synchronized (Launcher.lock) {
               // Check the stopped flag to avoid concurrent execution of this
               // method
  -            Launcher.checkStopped();
  +            if (Launcher.isStopped())
  +                return false;
   
  -            // Make sure that the start() method is running. If not, just return
  -            // as there is nothing to do.
  +            // Make sure that the start() method is running. If not, just
  +            // return as there is nothing to do.
               if (Launcher.isStarted())
                   Launcher.setStopped(true);
               else
  -                return;
  +                return false;
           }
   
  +        boolean returnValue = true;
  +
           try {
   
               // Kill all of the synchronous child processes
  @@ -496,14 +516,24 @@
               }
   
               // Make sure that the start() method has really finished
  -            checkStarted();
  +            if (Launcher.isStarted())
  +                returnValue = true;
   
  -        } catch (Exception e) {
  -            throw new LauncherException(e);
  +        } catch (Throwable t) {
  +            // Log any errors
  +            returnValue = false;
  +            String message = t.getMessage();
  +            if (Launcher.verbose)
  +                Launcher.error(t);
  +            else
  +                Launcher.error(message, false);
           } finally {
               // Reset stopped flag
               Launcher.setStopped(false);
           }
  +
  +        return returnValue;
  +
       }
   
       /**
  @@ -518,7 +548,7 @@
               Launcher.getLog().println(Launcher.getLocalizedString("error") + ": " + message);
           if (usage)
               Launcher.getLog().println(Launcher.getLocalizedString("usage"));
  -        System.exit(1);
  +
       }
   
       /**
  @@ -533,7 +563,6 @@
               Launcher.getLog().println(Launcher.getLocalizedString("error") + ": " + message);
           else
               t.printStackTrace(Launcher.getLog());
  -        System.exit(1);
   
       }
   
  @@ -544,16 +573,17 @@
        *
        * @return the canonical directory of the class or jar file that this class
        *  file was loaded from
  -     * @throws LauncherException if the canonical directory or jar file
  +     * @throws IOException if the canonical directory or jar file
        *  cannot be found
        */
  -    public static File getBootstrapDir() throws LauncherException {
  +    public static File getBootstrapDir() throws IOException {
   
           File file = Launcher.getBootstrapFile();
           if (file.isDirectory())
               return file;
           else
               return file.getParentFile();
  +
       }
   
       /**
  @@ -562,10 +592,10 @@
        *
        * @return the canonical directory or jar file that this class
        *  file was loaded from
  -     * @throws LauncherException if the canonical directory or jar file
  +     * @throws IOException if the canonical directory or jar file
        *  cannot be found
        */
  -    public static File getBootstrapFile() throws LauncherException {
  +    public static File getBootstrapFile() throws IOException {
   
           if (bootstrapFile == null) {
   
  @@ -573,7 +603,7 @@
               String classResourceName = "/" + Launcher.class.getName().replace('.', '/') + ".class";
               URL resource = Launcher.class.getResource(classResourceName);
               if (resource == null)
  -                throw new LauncherException(Launcher.getLocalizedString("bootstrap.file.not.found") + ": " + Launcher.class.getName());
  +                throw new IOException(Launcher.getLocalizedString("bootstrap.file.not.found") + ": " + Launcher.class.getName());
               String resourcePath = null;
               String embeddedClassName = null;
               boolean isJar = "jar".equals(resource.getProtocol()) ? true : false;
  @@ -593,7 +623,7 @@
               if (resourcePath.indexOf("file:") == 0)
                   resourcePath = resourcePath.substring(5);
               else
  -                throw new LauncherException(Launcher.getLocalizedString("bootstrap.file.not.file") + ": " + Launcher.class.getName());
  +                throw new IOException(Launcher.getLocalizedString("bootstrap.file.not.found") + ": " + Launcher.class.getName());
   
               // Coerce the URL into a file and check that it exists. Note that
               // the JVM <code>File(String)</code> constructor automatically
  @@ -602,12 +632,8 @@
               // URL encoded slashes.
               File file = new File(resourcePath);
               if (!file.exists() || !file.canRead())
  -                throw new LauncherException(Launcher.getLocalizedString("bootstrap.file.not.found") + ": " + Launcher.class.getName());
  -            try {
  -                bootstrapFile = file.getCanonicalFile();
  -            } catch (IOException ioe) {
  -                throw new LauncherException(ioe);
  -            }
  +                throw new IOException(Launcher.getLocalizedString("bootstrap.file.not.found") + ": " + Launcher.class.getName());
  +            bootstrapFile = file.getCanonicalFile();
   
           }
   
  @@ -649,7 +675,7 @@
        */
       public static synchronized PrintStream getLog() {
   
  -        return (Launcher.log == null) ? System.err : Launcher.log;
  +        return Launcher.log;
   
       }
   
  @@ -657,20 +683,14 @@
        * Set the classpath to the current JVM's tools classes.
        *
        * @return a string suitable for use as a JVM's -classpath argument
  -     * @throws LauncherException if the tools classes cannot be found
  +     * @throws IOException if the tools classes cannot be found
        */
  -    public static synchronized String getToolsClasspath()
  -        throws LauncherException
  -    {
  +    public static synchronized String getToolsClasspath() throws IOException {
   
           if (toolsClasspath == null) {
   
               File javaHome = null;
  -            try {
  -                javaHome = new File(System.getProperty("java.home")).getCanonicalFile();
  -            } catch (Exception e) {
  -                throw new LauncherException(e);
  -            }
  +            javaHome = new File(System.getProperty("java.home")).getCanonicalFile();
               Class clazz = null;
               String[] toolsPaths = new String[2];
               toolsPaths[0] = javaHome.getParent() + File.separator +
  @@ -704,7 +724,7 @@
               }
   
               if (clazz == null)
  -                throw new LauncherException(Launcher.getLocalizedString("sdk.tools.not.found"));
  +                throw new IOException(Launcher.getLocalizedString("sdk.tools.not.found"));
   
               // Save classpath.
               if (toolsFile != null)
  @@ -753,30 +773,6 @@
       }
   
       /**
  -     * Get this class' resource bundle.
  -     *
  -     * @return the ResourceBundle for this class
  -     * @throws LauncherException if any error occurs
  -     */
  -    private static synchronized ResourceBundle getResourceBundle()
  -        throws LauncherException
  -    {
  -
  -        if (resourceBundle == null) {
  -
  -            // Load the resource bundle
  -            try {
  -            } catch (Exception e) {
  -                throw new LauncherException(e);
  -            }
  -
  -        }
  -
  -        return resourceBundle;
  -
  -    }
  -
  -    /**
        * Resolve ${...} style macros in strings. This method will replace any
        * embedded ${...} strings in the specified unresolved parameter with the
        * value of the system property in the enclosed braces. Note that any '$'
  @@ -795,11 +791,9 @@
        *
        * @param unresolved the string to be resolved
        * @return the resolved String
  -     * @throws LauncherException if any error occurs
  +     * @throws IOException if any error occurs
        */
  -    private static String resolveString(String unresolved)
  -        throws LauncherException
  -    {
  +    private static String resolveString(String unresolved) throws IOException {
   
           if (unresolved == null)
               return null;
  @@ -898,11 +892,12 @@
        *
        * @param a PrintStream instance to print output to
        */
  -    public static synchronized void setLog(PrintStream log)
  -        throws LauncherException
  -    {
  +    public static synchronized void setLog(PrintStream log) {
   
  -        Launcher.log = log;
  +        if (log != null)
  +            Launcher.log = log;
  +        else
  +            Launcher.log = System.err;
   
       }
   
  
  
  

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>