public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { stringBuffer.append(line).append(System.getProperty("line.separator")); } } catch (IOException ioe) { ioe.printStackTrace(); } }
public String getBuffer() { return stringBuffer.toString(); }
public String runCmd(String command, String[] parms) throws ServiceException { String result = ""; try { String osName = System.getProperty("os.name"); LOG.debug("OS name: " + osName); String[] cmd; int nextParm; if (osName.equals("Windows NT") || osName.equals("Windows XP")) { cmd = new String[3 + parms.length]; cmd[0] = "cmd.exe"; cmd[1] = "/C"; nextParm = 2; } else if (osName.equals("Windows 95")) { cmd = new String[3 + parms.length]; cmd[0] = "command.com"; cmd[1] = "/C"; nextParm = 2; } else // Assuming that else is unix or unix-like in this regard of not needing an explicit // shell program. { cmd = new String[1 + parms.length]; nextParm = 0; } // Example values to use for 'command' here: // If using cygwin on a Windows OS: // "c:\\cygwin\\bin\\telnet.exe 192.168.1.101" // "c:\\cygwin\\bin\\expect.exe /tmp/telnettojbdesktop.exp" // If using a Unix (I'm guessing here): // "telnet 192.168.1.101" // "expect /tmp/telnettojbdesktop.exp" cmd[nextParm++] = command; for (String p : parms) { cmd[nextParm++] = p; } if (LOG.isDebugEnabled()) { StringBuffer buffer = new StringBuffer(); for (String a : cmd) { buffer.append(a).append(" "); } LOG.debug("Executing " + buffer.toString()); } Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd); StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); errorGobbler.start(); outputGobbler.start(); // This is the stream used to pass INPUT to the process. (It's called the "output stream" // because // it's an *output* stream from the perspective of this class.) OutputStream outputStream = proc.getOutputStream(); int exitVal = proc.waitFor(); if (exitVal != 0) { LOG.error("Exit value from " + cmd[2] + ": " + exitVal); } String stdErr = errorGobbler.getBuffer(); if (stdErr.length() > 0) { result = stdErr; } String stdOut = outputGobbler.getBuffer(); if (stdOut.length() > 0) { // It's intentional that stdOut replaces what was in stdErr if there *is* anything in // stdOut. result = stdOut; } } catch (Throwable t) { throw new ServiceException(ServiceError.RUNTIME_ERROR, t); } return result; }