1 package org.sapia.magnet.domain.system; 2 3 import org.apache.log4j.Logger; 6 import org.sapia.magnet.Log; 7 8 import java.io.File ; 11 import java.io.IOException ; 12 13 14 25 public class ProcessTask implements Runnable { 26 27 31 32 private static final Logger _theLogger = Logger.getLogger(ProcessTask.class); 33 34 38 39 private String [] _theCommands; 40 41 42 private String [] _theEnvironmentVariables; 43 44 45 private File _theWorkingDirectory; 46 47 51 58 public ProcessTask(String [] someCommands, String [] someVariables, File aDirectory) { 59 _theCommands = someCommands; 60 _theEnvironmentVariables = someVariables; 61 _theWorkingDirectory = aDirectory; 62 } 63 64 68 71 public void run() { 72 Process aProcess = null; 73 74 try { 76 aProcess = Runtime.getRuntime().exec( 77 _theCommands, _theEnvironmentVariables, _theWorkingDirectory); 78 } catch (IOException ioe) { 79 String aMessage = "Unable to execute the process"; 80 _theLogger.error(aMessage, ioe); 81 Log.error(aMessage + " - " + Log.extactMessage(ioe)); 82 } 83 84 boolean isTerminated = false; 86 while (!isTerminated) { 87 try { 88 Thread.sleep(1000); 90 91 StringBuffer aBuffer = new StringBuffer (); 93 while (aProcess.getInputStream().available() > 0) { 94 aBuffer.append((char) aProcess.getInputStream().read()); 95 } 96 if (aBuffer.length() > 0) { 97 _theLogger.info("OUTPUT >>> " + aBuffer.toString()); 98 } 99 100 aBuffer = new StringBuffer (); 102 while (aProcess.getErrorStream().available() > 0) { 103 aBuffer.append((char) aProcess.getErrorStream().read()); 104 } 105 if (aBuffer.length() > 0) { 106 _theLogger.error("ERROR >>> " + aBuffer.toString()); 107 } 108 109 int anExitValue = aProcess.exitValue(); 111 isTerminated = true; 112 _theLogger.info("Process terminated with exit value: " + anExitValue); 113 114 } catch (InterruptedException ie) { 115 isTerminated = true; 116 _theLogger.warn("INTERRUPTED: Force termination of the process"); 117 aProcess.destroy(); 118 119 } catch (IOException ioe) { 120 String aMessage = "Caugh an I/O error while monitoring the running process"; 121 _theLogger.warn(aMessage, ioe); 122 123 } catch (IllegalThreadStateException itse) { 124 126 } catch (RuntimeException re) { 127 String aMessage = "Caugh a system error while monitoring the running process"; 128 _theLogger.warn(aMessage, re); 129 } 130 } 131 } 132 } 133 | Popular Tags |