1 4 package com.tc.simulator.crasher; 5 6 import org.apache.commons.io.FileUtils; 7 8 import com.tc.process.StreamCopier; 9 10 import java.io.File ; 11 import java.io.FileOutputStream ; 12 import java.io.IOException ; 13 import java.io.PrintStream ; 14 import java.text.DateFormat ; 15 import java.util.ArrayList ; 16 import java.util.Date ; 17 import java.util.List ; 18 19 public class ProcessContainer { 20 21 private static int STOPPED = 1; 22 private static int RUNNING = 3; 23 24 private final ProcessContainerConfig config; 25 private final List command = new ArrayList (); 26 private final PrintStream out; 27 private final DateFormat dateFormat; 28 29 private int state = STOPPED; 30 private Process process; 31 private Thread outcopy; 32 private Thread errcopy; 33 34 public ProcessContainer(ProcessContainerConfig config) throws IOException { 35 this.config = config; 36 this.dateFormat = config.getDateFormat(); 37 createCommand(); 38 System.out.println("command: " + command); 39 File outfile = new File (config.getOutputDirectory(), config.getOutputPrefix() + "." + config.getID() + ".out"); 40 FileUtils.forceMkdir(outfile.getParentFile()); 41 FileUtils.touch(outfile); 42 out = new PrintStream (new FileOutputStream (outfile)); 43 } 44 45 public synchronized boolean isStopped() { 46 return state == STOPPED; 47 } 48 49 public synchronized void start() throws IOException { 50 if (state != STOPPED) return; 51 println("starting process..."); 52 this.process = Runtime.getRuntime().exec((String []) command.toArray(new String [command.size()])); 53 this.outcopy = new Thread (new StreamCopier(this.process.getInputStream(), out)); 54 this.errcopy = new Thread (new StreamCopier(this.process.getErrorStream(), out)); 55 this.outcopy.start(); 56 this.errcopy.start(); 57 state = RUNNING; 58 } 59 60 public synchronized void stop() { 61 if (state != RUNNING) return; 62 println("stopping process..."); 63 this.process.destroy(); 64 synchronized (outcopy) { 65 outcopy.interrupt(); 66 } 67 synchronized (errcopy) { 68 errcopy.interrupt(); 69 } 70 state = STOPPED; 71 } 72 73 private void println(Object o) { 74 out.println(prefix() + ":" + o); 75 } 76 77 private String prefix() { 78 return dateFormat.format(new Date ()) + ": " + Thread.currentThread() + ": " + config.getID(); 79 } 80 81 private void createCommand() { 82 command.add(getJavaCommand()); 83 command.addAll(config.getServerArgs()); 84 command.add(config.getClassname()); 85 command.addAll(config.getMainClassArgs()); 86 } 87 88 private String getJavaCommand() { 89 return "java"; 90 } 91 } | Popular Tags |