1 3 4 5 19 20 package edu.neu.ccs.jmk.contrib; 21 22 import java.io.*; 23 import edu.neu.ccs.jmk.*; 24 25 32 final public class ExecChdirOperator 33 implements Operator 34 { 35 36 40 public String getName() { 41 return "execdir"; 42 } 43 44 52 public void exec(String [] argsWithDir, PrintWriter out) 53 throws CommandFailedException 54 { 55 String msg = null; String [] args = new String [argsWithDir.length - 1]; 57 try { 58 File dir = new File(argsWithDir[0]); 60 System.arraycopy(argsWithDir, 1, args, 0, args.length); 61 argsWithDir = null; 62 Process p = Runtime.getRuntime().exec(args, null, dir); 63 Thread t = new Thread (new BufferedCopy(p.getInputStream(), out)); 65 t.start(); 66 new BufferedCopy(p.getErrorStream(), out).run(); 68 int exitCode = p.waitFor(); t.join(); if (exitCode != 0) { 71 if (args.length > 0) { msg = args[0]; 73 for (int i = 1; i < args.length; i++) 74 msg += " " + args[i]; 75 } 76 else 77 msg = "No args to exec"; 78 } 79 } 80 catch (IOException ioEx) { msg = "In exec: " + ioEx.toString(); 82 } 83 catch (InterruptedException iEx) { msg = "In waitFor: " + iEx.toString(); 85 } 86 if (msg != null) 87 throw new CommandFailedException(msg); 88 } 89 90 94 private static class BufferedCopy 95 implements Runnable 96 { 97 private InputStream is; 98 private PrintWriter out; 99 100 BufferedCopy(InputStream is, PrintWriter out) { 101 this.is = is; 102 this.out = out; 103 } 104 105 public void run() { 106 BufferedReader br = new BufferedReader(new InputStreamReader(is)); 107 try { 108 for (;;) { 109 String line = br.readLine(); 110 if (line == null) 111 break; 112 out.println(line); 113 } 114 br.close(); 115 } 116 catch (IOException ex) { } 117 } 118 } 119 120 } 121 | Popular Tags |