public String executeCommand(String command) { System.out.println("$ " + command); StringBuffer output = new StringBuffer(); Process p = null; try { p = execute(command); p.waitFor(); String line = ""; BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((line = reader.readLine()) != null) { output.append(line + "\n"); } reader.close(); reader = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = reader.readLine()) != null) { output.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } finally { try { p.getInputStream().close(); p.getOutputStream().close(); p.getErrorStream().close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println(output.toString()); return output.toString(); }
@Before public void setUp() { processManager = new ProcessManager() { @Override Process startProcess(ProcessBuilder processBuilder, String msgCommandInfo) { return processStartedByManager; } }; processStartedByManager = mock(Process.class); when(processStartedByManager.getInputStream()).thenReturn(mock(InputStream.class)); when(processStartedByManager.getErrorStream()).thenReturn(mock(InputStream.class)); when(processStartedByManager.getOutputStream()).thenReturn(mock(OutputStream.class)); processOne = mock(Process.class); processTwo = mock(Process.class); when(processOne.getInputStream()).thenReturn(mock(InputStream.class)); when(processOne.getErrorStream()).thenReturn(mock(InputStream.class)); when(processOne.getOutputStream()).thenReturn(mock(OutputStream.class)); when(processOne.exitValue()).thenThrow(new IllegalStateException()); when(processTwo.exitValue()).thenThrow(new IllegalStateException()); when(processTwo.getInputStream()).thenReturn(mock(InputStream.class)); when(processTwo.getErrorStream()).thenReturn(mock(InputStream.class)); when(processTwo.getOutputStream()).thenReturn(mock(OutputStream.class)); ConcurrentMap<Process, ProcessWrapper> processMap = processManager.getProcessMap(); wrapperForProcessOne = new ProcessWrapper(processOne, "tag1", null, inMemoryConsumer(), null, "ERROR: "); processMap.put(processOne, wrapperForProcessOne); wrapperForProcessTwo = new ProcessWrapper(processTwo, "tag2", null, inMemoryConsumer(), null, "ERROR: "); processMap.put(processTwo, wrapperForProcessTwo); }
public static void openExternalURL(URL url) throws IOException { if (Util.isWindows()) { // Yes, this only works on windows final String systemBrowser = "explorer.exe"; final Runtime rt = Runtime.getRuntime(); final Process proc = rt.exec( new String[] { systemBrowser, "\"" + url.toString() + "\"", }); new StreamGobbler(proc.getErrorStream()); new StreamGobbler(proc.getInputStream()); } else if (Util.isMacOSX()) { // Yes, this only works on Mac OS X final Runtime rt = Runtime.getRuntime(); final Process proc = rt.exec( new String[] { "/usr/bin/open", url.toString(), }); new StreamGobbler(proc.getErrorStream()); new StreamGobbler(proc.getInputStream()); } else { throw new IOException("Only windows and Mac OS X browsers are yet supported"); } }
/** * Convert image formats which are not supported by Word (eg EPS, PDF), into ones which are. This * requires ImageMagick to be on your system's path; for EPS and PDF images, Ghostscript is also * required. * * @param is * @param os * @param density PixelsPerInch * @throws IOException * @throws InterruptedException */ public static void convertToPNG(InputStream is, OutputStream os, int density) throws IOException, InterruptedException { /* * See http://www.eichberger.de/2006/05/imagemagick-in-servlets.html * * "Calling 'convert - png:-' as an external command and feeding it the * source image as standard input and reading the converted image * (in this case png) as standard output" * */ log.info("Start ImageMagick..."); Process p = Runtime.getRuntime() .exec("imconvert -density " + density + " -units PixelsPerInch - png:-"); // GraphicsMagick is a little quicker than ImageMagick, // but v1.3.3 (of Dec 2008) still has the now fixed in GM bug // whereby the right most ~10% of the resulting image is chopped off // Process p = Runtime.getRuntime().exec("gm convert -density " + density + " -units // PixelsPerInch - png:-"); /* On Windows, if this results in "Invalid Parameter", * then either ImageMagick is not installed, * or exec is finding the wrong convert * program. See http://studio.imagemagick.org/pipermail/magick-users/2005-October/016464.html * and http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=8324&start=0 * * Rather than use full path, rename convert to imconvert (which Alfresco and others do) * */ // initialize Gobblers StreamGobbler inGobbler = new StreamGobbler(p.getInputStream(), os); StreamGobbler errGobbler = new StreamGobbler(p.getErrorStream(), System.err); // start them inGobbler.start(); errGobbler.start(); // p.getOutputStream() is the _output stream_ of the subprocess, so // this copies is into the standard input stream of the process try { copy2(is, new BufferedOutputStream(p.getOutputStream())); p.getOutputStream().close(); log.debug("Image copied..."); } catch (IOException ioe) { ioe.printStackTrace(); // debug copy2(p.getErrorStream(), System.err); } if (p.waitFor() != 0) { log.error("Error"); } log.debug("End Process..."); }
/** * Actually executes pt-online-schema change. Does not generate any Sql. * * @return always <code>null</code> */ @Override public Sql[] generate(Database database) { List<String> cmndline = buildCommand(database); log.info("Executing: " + filterCommands(cmndline)); ProcessBuilder pb = new ProcessBuilder(cmndline); pb.redirectErrorStream(true); Process p = null; final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final OutputStream tee = new FilterOutputStream(outputStream) { @Override public void write(int b) throws IOException { if (b == '\n') { log.info(outputStream.toString(Charset.defaultCharset().toString())); outputStream.reset(); } else { super.write(b); } } }; try { p = pb.start(); final InputStream in = p.getInputStream(); final InputStream err = p.getErrorStream(); IOThread reader = new IOThread(in, tee); IOThread reader2 = new IOThread(err, tee); reader.start(); reader2.start(); int exitCode = p.waitFor(); reader.join(5000); reader2.join(5000); // log the remaining output log.info(outputStream.toString(Charset.defaultCharset().toString())); if (exitCode != 0) { throw new RuntimeException("Percona exited with " + exitCode); } } catch (IOException e) { throw new UnexpectedLiquibaseException(e); } catch (InterruptedException e) { throw new UnexpectedLiquibaseException(e); } finally { if (p != null) { StreamUtil.closeQuietly(p.getErrorStream()); StreamUtil.closeQuietly(p.getInputStream()); StreamUtil.closeQuietly(p.getOutputStream()); p.destroy(); } StreamUtil.closeQuietly(outputStream); } return null; }
protected TestSuite buildSuite() { TestSuite suite = new TestSuite("Shared Dart tests"); if (!V8Launcher.isConfigured()) { return configurationProblem( suite, "Please set the system property com.google.dart.runner.d8"); } File file = new File(listTests[0]); if (!file.canExecute()) { return configurationProblem(suite, file.getPath() + " is not executable"); } ProcessBuilder builder = new ProcessBuilder(listTests); try { Process process = builder.start(); InputStream inputStream = process.getInputStream(); StringBuilder sb = new StringBuilder(); try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); LineReader lineReader = new LineReader(inputStreamReader); String line; while ((line = lineReader.readLine()) != null) { if (!line.startsWith("dartc/")) { suite.addTest(SharedTestCase.getInstance(line, false)); } else if (line.startsWith("dartc/client/")) { suite.addTest(SharedTestCase.getInstance(line, true)); } } } finally { inputStream.close(); process.getOutputStream().close(); InputStreamReader inputStreamReader = new InputStreamReader(process.getErrorStream()); CharStreams.copy(inputStreamReader, sb); process.getErrorStream().close(); } process.waitFor(); if (process.exitValue() != 0) { sb.insert(0, file.getPath()); sb.insert(0, " returned non-zero exit code.\n"); return configurationProblem(suite, sb.toString()); } } catch (IOException e) { throw new AssertionError(e); } catch (InterruptedException e) { throw new AssertionError(e); } return suite; }
public String getLauncherDetails(String prefix) { try { final String javaVersionCommand = javaCommand + " -version"; Process proc = Runtime.getRuntime().exec(javaVersionCommand); try { InputStream inputStream = proc.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(prefix); buffer.append(line); buffer.append('\n'); } return buffer.toString(); } finally { proc.destroy(); } } catch (Exception e) { throw new RuntimeException(e); } }
/** * Initializes the xml-rpc communication. * * @param port the port where the communication should happen. * @param process this is the process that was spawned (server for the XML-RPC) * @throws MalformedURLException */ public PydevConsoleCommunication(int port, Process process, int clientPort) throws Exception { stdOutReader = new ThreadStreamReader(process.getInputStream()); stdErrReader = new ThreadStreamReader(process.getErrorStream()); stdOutReader.start(); stdErrReader.start(); // start the server that'll handle input requests this.webServer = new WebServer(clientPort); XmlRpcServer serverToHandleRawInput = this.webServer.getXmlRpcServer(); serverToHandleRawInput.setHandlerMapping( new XmlRpcHandlerMapping() { public XmlRpcHandler getHandler(String handlerName) throws XmlRpcNoSuchHandlerException, XmlRpcException { return PydevConsoleCommunication.this; } }); this.webServer.start(); IXmlRpcClient client = new ScriptXmlRpcClient(process, stdErrReader, stdOutReader); client.setPort(port); this.client = client; }
/** * Execute the given command and optionally wait and dump the results to standard out * * @param args command and arguments * @param wait true =wait for either completion or timeout time and dump output, false don't wait * and ignore the output. * @exception Exception */ private static void execCmdDumpResults(String[] args, boolean wait) throws Exception { // We need the process inputstream and errorstream ProcessStreamResult prout = null; ProcessStreamResult prerr = null; System.out.flush(); bos.flush(); BufferedOutputStream _bos = bos; if (!wait) { // not interested in the output, don't expect a huge amount. // information will just be written to the byte array in // memory and never used. _bos = new BufferedOutputStream(new ByteArrayOutputStream()); } // Start a process to run the command Process pr = execCmd(args); // Note, the timeout handling will only come into effect when we make // the Wait() call on ProcessStreamResult. prout = new ProcessStreamResult(pr.getInputStream(), _bos, timeoutMinutes); prerr = new ProcessStreamResult(pr.getErrorStream(), _bos, timeoutMinutes); if (!wait) return; // wait until all the results have been processed or if we timed out prout.Wait(); prerr.Wait(); _bos.flush(); System.out.flush(); }
public static String runFile(final Project project, String filePath) { String result = ""; try { String path = new File(filePath).getPath().replaceFirst("file:\\\\", ""); if (Utils.debug) { Utils.print("running: perl " + "\"" + path + "\""); } String cmd = ((project == null) ? getPerlPath("") : getPerlPath(project)); ; String[] params = {cmd, ((os.equals(os.Windows)) ? "\"" + path + "\"" : path)}; Process p = Runtime.getRuntime().exec(params); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())); result = printStream(input); printStream(err); int resultCode = p.waitFor(); if (resultCode != 0) { throw new Exception("Failed to run perl - Code (" + resultCode + ")"); } } catch (Exception e) { e.printStackTrace(); } return result; }
public void setUpSolrFile(String url) throws Exception { if (setUpIsDone) { return; } // do the setup File testDir = (Paths.get(getClass().getResource("/" + testFile).toURI()).getParent()).toFile(); ProcessBuilder pb = new ProcessBuilder("java", "-Durl=" + url + "/update", "-jar", "post.jar", testFile); pb.directory(testDir); LOGGER.log(Level.FINE, "Starting SOLR import"); final Process command = pb.start(); LOGGER.log(Level.FINE, "Started SOLR import"); String line; BufferedReader bri = new BufferedReader(new InputStreamReader(command.getInputStream())); BufferedReader bre = new BufferedReader(new InputStreamReader(command.getErrorStream())); while ((line = bri.readLine()) != null) { LOGGER.log(Level.FINE, line); } bri.close(); while ((line = bre.readLine()) != null) { LOGGER.log(Level.FINE, line); } bre.close(); int i = command.waitFor(); assertTrue(i == 0); LOGGER.log(Level.FINE, "SOLR import DONE!"); setUpIsDone = true; }
public boolean execute(GPLoadMeta meta, boolean wait) throws KettleException { Runtime rt = Runtime.getRuntime(); try { gploadProcess = rt.exec(createCommandLine(meta, true)); // any error message? StreamLogger errorLogger = new StreamLogger(gploadProcess.getErrorStream(), "ERROR"); // any output? StreamLogger outputLogger = new StreamLogger(gploadProcess.getInputStream(), "OUTPUT"); // kick them off errorLogger.start(); outputLogger.start(); if (wait) { // any error??? int exitVal = gploadProcess.waitFor(); logBasic( BaseMessages.getString( PKG, "GPLoad.Log.ExitValuePsqlPath", "" + exitVal)); // $NON-NLS-1$ } } catch (Exception ex) { // Don't throw the message upwards, the message contains the password. throw new KettleException("Error while executing \'" + createCommandLine(meta, false) + "\'"); } return true; }
private static int executeCmd(String[] args, String outFile, String errFile) throws Exception { LOG.info("Running: " + org.apache.commons.lang.StringUtils.join(args, ' ')); PrintStream out = outFile == null ? SessionState.getConsole().getChildOutStream() : new PrintStream(new FileOutputStream(outFile), true); PrintStream err = errFile == null ? SessionState.getConsole().getChildErrStream() : new PrintStream(new FileOutputStream(errFile), true); Process executor = Runtime.getRuntime().exec(args); StreamPrinter errPrinter = new StreamPrinter(executor.getErrorStream(), null, err); StreamPrinter outPrinter = new StreamPrinter(executor.getInputStream(), null, out); outPrinter.start(); errPrinter.start(); int result = executor.waitFor(); outPrinter.join(); errPrinter.join(); if (outFile != null) { out.close(); } if (errFile != null) { err.close(); } return result; }
public ArrayList<String> executeCommand(SHELL_CMD shellCmd) { String line = null; ArrayList<String> fullResponse = new ArrayList<String>(); Process localProcess = null; try { localProcess = Runtime.getRuntime().exec(shellCmd.command); } catch (Exception e) { return null; // e.printStackTrace(); } BufferedReader in = new BufferedReader(new InputStreamReader(localProcess.getInputStream())); BufferedReader er = new BufferedReader(new InputStreamReader(localProcess.getErrorStream())); try { while ((line = in.readLine()) != null) { fullResponse.add(line); } if (fullResponse.size() <= 0) { while ((line = er.readLine()) != null) { fullResponse.add(line); } } in.close(); er.close(); } catch (Exception e) { // e.printStackTrace(); } return fullResponse; }
public static void command(String command) { boolean err = false; try { Process process = new ProcessBuilder(command.split(" ")).start(); BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream())); String s; while ((s = results.readLine()) != null) { System.out.println(s); } BufferedReader errors = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((s = errors.readLine()) != null) { System.err.println(s); err = true; } } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } if (err) { throw new OSExecuteException("Errors executing " + command); } }
// Method: runTest // Runs the script specified in the test case object public void runTest() { try { Process p = Runtime.getRuntime().exec(this.execCommandLine); InputStreamReader esr = new InputStreamReader(p.getErrorStream()); BufferedReader ereader = new BufferedReader(esr); InputStreamReader isr = new InputStreamReader(p.getInputStream()); BufferedReader ireader = new BufferedReader(isr); String line = null; String line1 = null; while ((line = ireader.readLine()) != null) { // System.out.println("Output: " + line); System.out.println(line); } while ((line1 = ereader.readLine()) != null) { System.err.println("Error: " + line1); } int exitValue = p.waitFor(); tcInstanceTools.LogMessage('d', "Test Case exit value: " + exitValue); if (exitValue == 0) { setTestCaseResult(Result.Pass); } else { setTestCaseResult(Result.Fail); } } catch (IOException ioe) { System.out.println("Error: " + ioe.getMessage()); } catch (InterruptedException e) { System.out.println("Error: " + e.getMessage()); } }
/** * Run a Process, and read the various streams so there is not a buffer overrun. * * @param p The Process to be executed * @param output The Stream to receive the Process' output stream * @param error The Stream to receive the Process' error stream * @param doNotPrintStrings A collection of strings that should not be dumped to std.out * @return true if the Process returned 0, false otherwise */ public static boolean runCommand( final Process p, final OutputStream output, final OutputStream error, final List<String> doNotPrintStrings) { final StreamRedirector errorStream = new StreamRedirector(p.getErrorStream(), error, doNotPrintStrings); final StreamRedirector outputStream = new StreamRedirector(p.getInputStream(), output, doNotPrintStrings); errorStream.start(); outputStream.start(); try { final boolean retValue = p.waitFor() == 0; // give the threads time to collect the final output from the Process errorStream.join(); outputStream.join(); return retValue; } catch (final InterruptedException ex) { LOG.debug("Command execution Intercepted", ex); return false; } }
private static void checkIsAvailableAndGetVersion() { ProcessBuilder pb = new ProcessBuilder(COMMAND, "--version"); pb.redirectErrorStream(true); Process p = null; try { p = pb.start(); p.waitFor(); perconaToolkitVersion = StreamUtil.getStreamContents(p.getInputStream()); if (perconaToolkitVersion != null) { perconaToolkitVersion = perconaToolkitVersion.replaceAll("\n|\r", ""); } available = true; log.info("Using percona toolkit: " + perconaToolkitVersion); } catch (IOException e) { available = false; } catch (InterruptedException e) { available = false; } finally { if (p != null) { StreamUtil.closeQuietly(p.getErrorStream()); StreamUtil.closeQuietly(p.getInputStream()); StreamUtil.closeQuietly(p.getOutputStream()); p.destroy(); } } }
private void processTranslateError(Process translate) { ErrorStreamProcess errorProcess = new ErrorStreamProcess(translate.getErrorStream(), "Error"); errorProcess.run(); if (!errorProcess.getErrorConent().isEmpty()) { System.out.println(errorProcess.getErrorConent()); } }
public void createMatchTable() throws IOException, InterruptedException { addReport("Matching keypoints started"); // File matchTable = new File(FileHelper.mergePath(imageDirectory, // keypointMatchTableFilename)); // // if(matchTable.exists()) { // addReport("Match table \""+keypointMatchTableFilename+"\" exists, therefore skip // matching"); // return; // } ProcessBuilder pb = new ProcessBuilder( keypointMatcherPath, FileHelper.mergePath(imageDirectory, imageListKeysFilename), FileHelper.mergePath(imageDirectory, keypointMatchTableFilename)); pb.directory(new File(imageDirectory)); Process p = pb.start(); addReport(p.getInputStream(), p.getErrorStream()); if (p.waitFor() != 0) { addReport("Matching keypoints error"); stop(); } }
/** * Close the streams belonging to the given Process. In the original implementation all exceptions * were dropped which is probably not a good thing. On the other hand the signature allows * throwing an IOException so the curent implementation might be quite okay. * * @param process the <CODE>Process</CODE>. * @throws IOException closing one of the three streams failed */ private void closeStreams(final Process process) throws IOException { IOException caught = null; try { process.getInputStream().close(); } catch (IOException e) { caught = e; } try { process.getOutputStream().close(); } catch (IOException e) { caught = e; } try { process.getErrorStream().close(); } catch (IOException e) { caught = e; } if (caught != null) { throw caught; } }
public static int runProcess(String[] pstr, int timeout) throws TimeoutException, InterruptedException, IOException { String cmdStr = ""; for (String st : pstr) { cmdStr = cmdStr + " " + st; } SDFSLogger.getLog().debug("Executing [" + cmdStr + "]"); Process p = null; try { p = Runtime.getRuntime().exec(pstr, null, new File(Main.volume.getPath())); ReadStream s1 = new ReadStream("stdin", p.getInputStream()); ReadStream s2 = new ReadStream("stderr", p.getErrorStream()); s1.start(); s2.start(); } catch (Throwable e) { SDFSLogger.getLog().error("unable to execute " + cmdStr, e); throw new IOException(e); } long now = System.currentTimeMillis(); long finish = now + timeout; while (isAlive(p) && (System.currentTimeMillis() < finish)) { Thread.sleep(10); } if (isAlive(p)) { throw new TimeoutException("Process [" + cmdStr + "] timeout out after [" + timeout + "] ms"); } return p.exitValue(); }
public String execRecognizer() { try { String inputFile = new File(tmpdir, "input").getAbsolutePath(); String[] args = new String[] {"java", "-classpath", tmpdir + pathSep + CLASSPATH, "Test", inputFile}; // String cmdLine = "java -classpath "+CLASSPATH+pathSep+tmpdir+" Test " + new File(tmpdir, // "input").getAbsolutePath(); // System.out.println("execParser: "+cmdLine); Process process = Runtime.getRuntime().exec(args, null, new File(tmpdir)); StreamVacuum stdoutVacuum = new StreamVacuum(process.getInputStream()); StreamVacuum stderrVacuum = new StreamVacuum(process.getErrorStream()); stdoutVacuum.start(); stderrVacuum.start(); process.waitFor(); stdoutVacuum.join(); stderrVacuum.join(); String output = null; output = stdoutVacuum.toString(); if (stderrVacuum.toString().length() > 0) { this.stderrDuringParse = stderrVacuum.toString(); System.err.println("exec stderrVacuum: " + stderrVacuum); } return output; } catch (Exception e) { System.err.println("can't exec recognizer"); e.printStackTrace(System.err); } return null; }
@Override public CommandRunner.CommandOutput runCommandAndWaitForExit( File workingDir, List<String> arguments) throws IOException, InterruptedException { File binary = new File(arguments.get(0)); if (!binary.exists()) { logger.error("Binary {} does not exists, fix your configuration!", binary.getAbsolutePath()); return createErrorCommandOutput(); } if (!binary.canExecute()) { logger.error( "Binary {} can't be executed, fix your configuration!", binary.getAbsolutePath()); return createErrorCommandOutput(); } ProcessBuilder pb = new ProcessBuilder(arguments); pb.directory(workingDir); Process process = pb.start(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); CommandRunnerImpl.StreamGobbler sgerr = new CommandRunnerImpl.StreamGobbler(process.getErrorStream(), stderr); CommandRunnerImpl.StreamGobbler sgout = new CommandRunnerImpl.StreamGobbler(process.getInputStream(), stdout); sgerr.start(); sgout.start(); int exitCode = process.waitFor(); sgerr.join(); sgout.join(); CommandRunner.CommandOutput result = new CommandRunner.CommandOutput(stdout.toByteArray(), stderr.toByteArray()); result.setExitCode(exitCode); return result; }
public static void main(String[] args) { try { String ls_1; Process process = null; // File handle = new File("../tmp/ctb_v1/data"); File handle = new File("../tmp/ctb_v6/data/bracketed"); BufferedWriter bout = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("../tmp/malt.train"), "UTF-8")); for (File sub : Arrays.asList(handle.listFiles())) { String file = sub.getAbsolutePath(); if (!file.endsWith(".fid")) continue; clean(file); process = Runtime.getRuntime() .exec( "cmd /c java -jar ../tmp/Penn2Malt.jar " + file + " ../tmp/headrules.txt 3 2 chtb"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((ls_1 = bufferedReader.readLine()) != null) { System.out.println(ls_1); } bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((ls_1 = bufferedReader.readLine()) != null) { System.out.println(ls_1); } } } catch (IOException e) { System.err.println(e); } }
public static void mountExt4() { makeDirectory(Constants.MOUNT_PATH); try { final ProcessBuilder pb = new ProcessBuilder("mount", Constants.NBD_DEVICE, Constants.MOUNT_PATH); final StringBuilder err = new StringBuilder(); final Process startClientProcess = pb.start(); final BufferedReader stdErr = new BufferedReader( new InputStreamReader(startClientProcess.getErrorStream(), StandardCharsets.UTF_8)); final BufferedReader stdOut = new BufferedReader( new InputStreamReader(startClientProcess.getInputStream(), StandardCharsets.UTF_8)); startClientProcess.waitFor(); errorHandler(startClientProcess, stdErr, stdOut, err); } catch (final IOException e) { throw new RuntimeException(e); } catch (final InterruptedException e) { throw new RuntimeException(e); } }
public static TByteArrayList transformByExternalCommand( final String command, final InputStream input) throws IOException { final Process process = Runtime.getRuntime().exec(command); final InputStream in = process.getInputStream(); final OutputStream out = process.getOutputStream(); final TByteArrayList bytes = new TByteArrayList(100500); final byte[] buffer = new byte[1024 * 1024]; try { int read; while ((read = input.read(buffer)) > 0) { out.write(buffer, 0, read); if (in.available() > 0) { read = in.read(buffer); bytes.add(buffer, 0, read); } } out.close(); while ((read = in.read(buffer)) > 0) { bytes.add(buffer, 0, read); } in.close(); } catch (IOException ioe) { System.err.println(readByteStream(process.getErrorStream())); LOG.error(ioe); throw ioe; } return bytes; }
/** * Creates a transcoded input stream by executing the given command. If <code>in</code> is not * null, data from it is copied to the command. * * @param command The command to execute. * @param in Data to feed to the command. May be <code>null</code>. * @throws IOException If an I/O error occurs. */ public TranscodeInputStream(String[] command, final InputStream in) throws IOException { StringBuffer buf = new StringBuffer("Starting transcoder: "); for (String s : command) { buf.append('[').append(s).append("] "); } LOG.debug(buf); process = Runtime.getRuntime().exec(command); processOutputStream = process.getOutputStream(); processInputStream = process.getInputStream(); // Must read stderr from the process, otherwise it may block. final String name = command[0]; new InputStreamReaderThread(process.getErrorStream(), name, true).start(); // Copy data in a separate thread if (in != null) { new Thread(name + " TranscodedInputStream copy thread") { public void run() { try { IOUtils.copy(in, processOutputStream); } catch (IOException x) { // Intentionally ignored. Will happen if the remote player closes the stream. } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(processOutputStream); } } }.start(); } }
private void serve(InputStream sis, OutputStream sos) throws IOException { // kills the process if client closes the stream; // closes the stream if process is terminated/ended output. // therefore we need the interruption mechanism. Process process = Runtime.getRuntime().exec("bash"); InputStream pis = process.getInputStream(); InputStream pes = process.getErrorStream(); OutputStream pos = process.getOutputStream(); try { threads.add(new CopyThread(pis, sos)); threads.add(new CopyThread(pes, sos)); threads.add(new CopyThread(sis, pos)); threads.add( new InterruptibleThread() { protected void run0() throws InterruptedException { process.waitFor(); } }); Util.startJoin(threads); } finally { process.destroy(); } }
/** * @return * @throws IllegalStateException if {@code tesseract} binary invoked with {@code --list-langs} * returns a code {@code != 0} */ public List<String> getAvailableLanguages() throws IllegalStateException, IOException, InterruptedException { ProcessBuilder tesseractProcessBuilder = new ProcessBuilder(this.getBinary(), "--list-langs"); Process tesseractProcess = tesseractProcessBuilder.redirectOutput(ProcessBuilder.Redirect.PIPE).start(); int tesseractProcessReturnCode = tesseractProcess.waitFor(); String tesseractProcessStdout = IOUtils.toString(tesseractProcess.getInputStream()); String tesseractProcessStderr = IOUtils.toString(tesseractProcess.getErrorStream()); if (tesseractProcessReturnCode != 0) { throw new IllegalStateException( String.format( "The tesseract process '%s' unexpectedly returned with non-zero return code %d and output '%s' (stdout) and '%s' (stderr).", this.getBinary(), tesseractProcessReturnCode, tesseractProcessStdout, tesseractProcessStderr)); } // tesseract --list-langs prints to stderr, reported as // https://bugs.launchpad.net/ubuntu/+source/tesseract/+bug/1481015 List<String> langs = new LinkedList<>(); for (String lang : tesseractProcessStderr.split("\n")) { if (!lang.startsWith("List of available languages")) { langs.add(lang); } } Collections.sort(langs, String.CASE_INSENSITIVE_ORDER); return langs; }