1 3 5 22 23 package edu.neu.ccs.jmk; 24 25 import java.io.*; 26 27 34 final class ExecOperator 35 implements Operator 36 { 37 38 42 public String getName() { 43 return "exec"; 44 } 45 46 54 public void exec(String [] args, PrintWriter out) 55 throws CommandFailedException 56 { 57 String msg = null; try { 59 Process p = Runtime.getRuntime().exec(args); 61 Thread t = new Thread (new BufferedCopy(p.getInputStream(), out)); 63 t.start(); 64 new BufferedCopy(p.getErrorStream(), out).run(); 66 int exitCode = p.waitFor(); t.join(); if (exitCode != 0) { 69 if (args.length > 0) { msg = args[0]; 71 for (int i = 1; i < args.length; i++) 72 msg += " " + args[i]; 73 } 74 else 75 msg = "No args to exec"; 76 } 77 } 78 catch (IOException ioEx) { msg = "In exec: " + ioEx.toString(); 80 } 81 catch (InterruptedException iEx) { msg = "In waitFor: " + iEx.toString(); 83 } 84 if (msg != null) 85 throw new CommandFailedException(msg); 86 } 87 88 92 private static class BufferedCopy 93 implements Runnable 94 { 95 private InputStream is; 96 private PrintWriter out; 97 98 BufferedCopy(InputStream is, PrintWriter out) { 99 this.is = is; 100 this.out = out; 101 } 102 103 public void run() { 104 BufferedReader br = new BufferedReader(new InputStreamReader(is)); 105 try { 106 for (;;) { 107 String line = br.readLine(); 108 if (line == null) 109 break; 110 out.println(line); 111 } 112 br.close(); 113 } 114 catch (IOException ex) { } 115 } 116 } 117 118 123 public static void main(String [] args) { 124 PrintWriter out = new PrintWriter(System.out, true); 125 try { 126 new ExecOperator().exec(args, out); 127 } 128 catch (Throwable t) { 129 System.err.println("Internal error: " + t.getMessage()); 130 t.printStackTrace(); 131 } 132 out.println("Exec command completed"); 133 } 134 } 135 | Popular Tags |