1 package org.columba.core.base; 2 3 import java.io.BufferedReader ; 4 import java.io.IOException ; 5 import java.io.InputStream ; 6 import java.io.InputStreamReader ; 7 import java.io.OutputStream ; 8 9 import org.columba.core.io.StreamUtils; 10 11 17 18 24 public class IPCHelper { 25 26 static final java.util.logging.Logger LOG = java.util.logging.Logger 27 .getLogger("org.columba.core.base"); 29 protected StreamThread outputStream = null; 30 31 protected StreamThread errorStream = null; 32 33 protected OutputStream inputStream = null; 34 35 protected Process p; 36 37 public IPCHelper() { 38 } 40 41 50 public void executeCommand(String [] command) throws Exception { 51 this.p = Runtime.getRuntime().exec(command); 52 53 errorStream = new StreamThread(p.getErrorStream()); 54 outputStream = new StreamThread(p.getInputStream()); 55 inputStream = p.getOutputStream(); 56 57 errorStream.start(); 58 outputStream.start(); 59 } 60 61 public void send(String in) throws Exception { 62 inputStream.write(in.getBytes()); 63 inputStream.flush(); 64 inputStream.close(); 65 } 66 67 public void send(InputStream in) throws Exception { 68 StreamUtils.streamCopy(in, inputStream); 69 inputStream.flush(); 70 inputStream.close(); 71 } 72 73 public int waitFor() throws Exception { 74 int exitVal = p.waitFor(); 75 76 return exitVal; 77 } 78 79 86 public String getErrorString() throws Exception { 87 String str = errorStream.getBuffer(); 88 89 return str; 90 } 91 92 99 public String getOutputString() throws Exception { 100 String str = outputStream.getBuffer(); 101 102 return str; 103 } 104 105 109 public void waitForThreads() throws Exception { 110 outputStream.join(); 111 errorStream.join(); 112 } 113 114 public class StreamThread extends Thread { 115 InputStream is; 116 117 StringBuffer buf; 118 119 public StreamThread(InputStream theInputStream) { 120 this.is = theInputStream; 121 122 buf = new StringBuffer (); 123 } 124 125 @Override 126 public void run() { 127 try { 128 InputStreamReader isr = new InputStreamReader (is); 129 BufferedReader br = new BufferedReader (isr); 130 String line = null; 131 132 while ((line = br.readLine()) != null) { 133 LOG.info(">" + line); buf.append(line + "\n"); } 136 } catch (IOException ioe) { 137 ioe.printStackTrace(); 138 } 139 } 140 141 public String getBuffer() { 142 return buf.toString(); 143 } 144 } 145 } 146 | Popular Tags |