home *** CD-ROM | disk | FTP | other *** search
Java Source | 2000-04-03 | 2.9 KB | 125 lines |
- /*
- ** Sambar Server Exec Utility
- **
- ** Execute a command either synchronously or async
- ** much like the UNIX system or fork/exec functionality.
- **
- ** This appears on Core Web Programming from Prentice Hall Publishers,
- ** and may be freely used or adapted. 1997 Marty Hall, hall@apl.jhu.edu
- */
- package com.sambar.util;
-
- import java.io.*;
-
- public class Exec
- {
- private static boolean debug = true;
-
- public static void setDebug(boolean debugFlag)
- {
- debug = debugFlag;
- }
-
- /*
- ** Execute a command and return immediately.
- ** Return false if a problem is occurs due to an
- ** exception.
- */
- public static boolean exec(String command)
- {
- return (exec(command, false, false));
- }
-
- /*
- ** Execute a command and wait until it completes.
- ** Return false if a problem is occurs due to an
- ** exception or the command returned a non-zero value.
- */
- public static boolean execWait(String command)
- {
- return(exec(command, false, true));
- }
-
- /*
- ** Execute a command and print the output of the command.
- ** Return false if a problem is occurs due to an
- ** exception or the command returned a non-zero value.
- */
- public static boolean execPrint(String command)
- {
- return(exec(command, true, false));
- }
-
- private static boolean exec(String command, boolean printResults,
- boolean wait)
- {
- if (debug)
- {
- System.out.println("============================================");
- System.out.println("Executing '" + command + "'.");
- }
-
- try
- {
- Process p = Runtime.getRuntime().exec(command);
-
- if (printResults)
- {
- BufferedInputStream buffer;
- DataInputStream commandResult;
- buffer = new BufferedInputStream(p.getInputStream());
- commandResult = new DataInputStream(buffer);
- String s = null;
- try
- {
- while ((s = commandResult.readLine()) != null)
- System.out.println("Output: " + s);
- commandResult.close();
- if (p.exitValue() != 0)
- {
- if (debug)
- printError(command + " -- p.exitValue() != 0");
- return (false);
- }
- } catch (Exception e) {}
-
- }
- else if (wait)
- {
- try
- {
- int returnVal = p.waitFor();
- if (returnVal != 0)
- {
- if (debug)
- printError(command);
- return (false);
- }
- } catch (Exception e) {
- if (debug)
- printError(command, e);
- return (false);
- }
- }
- } catch (Exception e) {
- if (debug)
- printError(command, e);
- return (false);
- }
-
- return(true);
- }
-
- private static void printError(String command, Exception e)
- {
- System.out.println("Error doing exec(" + command + "): " +
- e.getMessage());
- System.out.println("Did you specify the full " + "pathname?");
- }
-
- private static void printError(String command)
- {
- System.out.println("Error executing '" + command + "'.");
- }
- }
-