List of usage examples for java.lang ProcessBuilder redirectErrorStream
boolean redirectErrorStream
To view the source code for java.lang ProcessBuilder redirectErrorStream.
Click Source Link
From source file:com.frostwire.desktop.DesktopVPNMonitor.java
private static String readProcessOutput(String command, String arguments) { String result = ""; ProcessBuilder pb = new ProcessBuilder(command, arguments); pb.redirectErrorStream(true); try {//from w ww . j a va2 s .c om Process process = pb.start(); InputStream stdout = process.getInputStream(); final BufferedReader brstdout = new BufferedReader(new InputStreamReader(stdout)); String line; try { StringBuilder sb = new StringBuilder(); while ((line = brstdout.readLine()) != null) { sb.append(line + "\r\n"); } result = sb.toString(); } catch (Throwable e) { LOG.error("Error reading routing table command output", e); } finally { IOUtils.closeQuietly(brstdout); IOUtils.closeQuietly(stdout); } } catch (Throwable e) { LOG.error("Error executing routing table command", e); } return result; }
From source file:com.junoyoon.BullsUtil.java
/** * Run command and//from w w w . j a va2s .c o m * * @param cmd * @return * @throws IOException */ public static String getCmdOutput(List<String> cmd) throws IOException { ProcessBuilder builder = new ProcessBuilder(); builder.command().addAll(cmd); builder.redirectErrorStream(true); StringBuilder result = new StringBuilder(1024); Process proc = builder.start(); boolean firstLine = true; for (Object eachLineObject : IOUtils.readLines(proc.getInputStream())) { String eachLine = (String) eachLineObject; if (firstLine) { eachLine = eachLine.replace("charset=us-ascii", "charset=" + Constant.DEFAULT_ENCODING); firstLine = false; } result.append(eachLine).append("\n"); } return result.toString(); }
From source file:Main.java
public static String runCommand(String[] command, String workdirectory) { String result = ""; Log.d("AppUtil.class", "#" + command); try {/* ww w . j a va2s . co m*/ ProcessBuilder builder = new ProcessBuilder(command); // set working directory if (workdirectory != null) { builder.directory(new File(workdirectory)); } builder.redirectErrorStream(true); Process process = builder.start(); InputStream in = process.getInputStream(); byte[] buffer = new byte[1024]; while (in.read(buffer) != -1) { String str = new String(buffer); result = result + str; } in.close(); } catch (Exception e) { e.printStackTrace(); } return result; }
From source file:org.esa.s2tbx.dataio.openjpeg.OpenJpegUtils.java
/** * Get the tile layout with opj_dump/*from w ww. j ava 2s . c o m*/ * * @param opjdumpPath path to opj_dump * @param jp2FilePath the path to the jpeg file * @return the tile layout for the openjpeg file * @throws IOException * @throws InterruptedException */ public static TileLayout getTileLayoutWithOpenJPEG(String opjdumpPath, Path jp2FilePath) throws IOException, InterruptedException { if (opjdumpPath == null) { throw new IllegalStateException("Cannot retrieve tile layout, opj_dump cannot be found"); } TileLayout tileLayout; String pathToImageFile = jp2FilePath.toAbsolutePath().toString(); if (SystemUtils.IS_OS_WINDOWS) { pathToImageFile = Utils.GetIterativeShortPathName(pathToImageFile); } ProcessBuilder builder = new ProcessBuilder(opjdumpPath, "-i", pathToImageFile); builder.redirectErrorStream(true); CommandOutput exit = OpenJpegUtils.runProcess(builder); if (exit.getErrorCode() != 0) { StringBuilder sbu = new StringBuilder(); for (String fragment : builder.command()) { sbu.append(fragment); sbu.append(' '); } throw new IOException( String.format("Command [%s] failed with error code [%d], stdoutput [%s] and stderror [%s]", sbu.toString(), exit.getErrorCode(), exit.getTextOutput(), exit.getErrorOutput())); } tileLayout = OpenJpegUtils.parseOpjDump(exit.getTextOutput()); return tileLayout; }
From source file:mitm.common.util.ProcessUtils.java
/** * Helper method that executes the given cmd and returns the output. The process will be destroyed * if the process takes longer to execute than the timeout. *///from w w w .jav a2s. com public static void executeCommand(List<String> cmd, long timeout, InputStream input, OutputStream output) throws IOException { Check.notNull(cmd, "cmd"); if (cmd.size() == 0) { throw new IOException("Process is missing."); } /* * Used for reporting */ String name = StringUtils.join(cmd, ","); /* * Watchdog that will be used to destroy the process on a timeout */ TaskScheduler watchdog = new TaskScheduler(ProcessUtils.class.getCanonicalName() + "#" + name); try { ProcessBuilder processBuilder = new ProcessBuilder(cmd); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); /* * Task that will destroy the process on a timeout */ Task processWatchdogTask = new DestroyProcessTimeoutTask(process, watchdog.getName()); watchdog.addTask(processWatchdogTask, timeout); /* * Task that will interrup the current thread on a timeout */ Task threadInterruptTimeoutTask = new ThreadInterruptTimeoutTask(Thread.currentThread(), watchdog.getName()); watchdog.addTask(threadInterruptTimeoutTask, timeout); /* * Send the input to the standard input of the process */ if (input != null) { IOUtils.copy(input, process.getOutputStream()); IOUtils.closeQuietly(process.getOutputStream()); } /* * Get the standard output from the process */ if (output != null) { IOUtils.copy(process.getInputStream(), output); } int exitValue; try { exitValue = process.waitFor(); } catch (InterruptedException e) { throw new IOException("Error executing [" + name + "]", e); } if (exitValue != 0) { throw new ProcessException("Error executing [" + name + "]. exit value: " + exitValue, exitValue); } } finally { /* * Need to cancel any pending tasks */ watchdog.cancel(); } }
From source file:net.technicpack.utilslib.Utils.java
/** * * Run a command on the local command line and return the program output. * THIS COMMAND IS BLOCKING! Only run for short command line stuff, or I guess run on a thread. * * @param command List of args to run on the command line * @return The newline-separated program output */// ww w.ja v a 2 s .com public static String getProcessOutput(String... command) { String out = null; try { ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(true); Process process = pb.start(); final BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); final StringBuilder response = new StringBuilder(); new Thread(new Runnable() { @Override public void run() { try { String line; while ((line = bufferedReader.readLine()) != null) { response.append(line + "\n"); } } catch (IOException ex) { //Don't let other process' problems concern us } finally { IOUtils.closeQuietly(bufferedReader); } } }).start(); process.waitFor(); if (response.toString().length() > 0) { out = response.toString().trim(); } } catch (IOException e) { //Some kind of problem running java -version or getting output, just assume the version is bad return null; } catch (InterruptedException ex) { //Something booted us while we were waiting on java -version to complete, just assume //this version is bad return null; } return out; }
From source file:org.roda.core.util.CommandUtility.java
/** * Execute the given command line.//from w w w. j a va2 s.c o m * * @param args * the command line as a list of arguments. * * @return a {@link String} with the output of the command. * * @throws CommandException */ public static String execute(boolean withErrorStream, String... args) throws CommandException { int exitValue = 0; String output; try { StringBuilder builder = new StringBuilder(); for (String arg : args) { builder.append(arg + " "); } LOGGER.debug("Executing {}", builder); // create and execute process ProcessBuilder processBuilder = new ProcessBuilder(args); processBuilder.redirectErrorStream(withErrorStream); Process process = processBuilder.start(); // Get process output InputStream is = process.getInputStream(); CaptureOutputThread captureOutputThread = new CaptureOutputThread(is); synchronized (is) { captureOutputThread.start(); // Wait until the CaptureOutputThread notifies that is finished // reading the input stream. LOGGER.debug("Waiting until CaptureOutputThread notifies"); is.wait(); } LOGGER.debug("CaptureOutputThread notified. Getting output..."); output = captureOutputThread.output; // Get process exit value exitValue = process.waitFor(); IOUtils.closeQuietly(is); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Command {} terminated with value {}", Arrays.toString(args), exitValue); } if (exitValue == 0) { return output; } else { throw new CommandException( "Command " + Arrays.toString(args) + " terminated with error code " + exitValue, exitValue, output); } } catch (IOException | InterruptedException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Error executing command {}", Arrays.toString(args), e); } throw new CommandException("Error executing command " + Arrays.toString(args) + " - " + e.getMessage(), e); } }
From source file:Main.java
public static String runCommand(String[] command, String workdirectory) { String result = ""; //AbLogUtil.d(AbAppUtil.class, "#"+command); try {// ww w . ja v a 2 s . c o m ProcessBuilder builder = new ProcessBuilder(command); // set working directory if (workdirectory != null) { builder.directory(new File(workdirectory)); } builder.redirectErrorStream(true); Process process = builder.start(); InputStream in = process.getInputStream(); byte[] buffer = new byte[1024]; while (in.read(buffer) != -1) { String str = new String(buffer); result = result + str; } in.close(); } catch (Exception e) { e.printStackTrace(); } return result; }
From source file:com.mewmew.fairy.v1.book.Xargs.java
public static void exec(Map<String, String> env, String cmd[], boolean redirectError, Output<String> output) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder(cmd); if (env != null) { pb.environment().putAll(env);/*from w ww . j a va2 s. c o m*/ } if (redirectError) { pb.redirectErrorStream(true); } final Process p = pb.start(); if (!redirectError) { new Thread(new Runnable() { public void run() { try { LineIterator err = new LineIterator(new InputStreamReader(p.getErrorStream())); while (err.hasNext()) { err.next(); } } finally { } } }).start(); } LineIterator out = new LineIterator(new InputStreamReader(p.getInputStream())); while (out.hasNext()) { output.output(out.nextLine()); } int code = p.waitFor(); if (code != 0) { throw new RuntimeException(String.format("return != 0, code = %d", code)); } }
From source file:com.sap.prd.mobile.ios.mios.Forker.java
static int forkProcess(final PrintStream out, final File executionDirectory, final String... args) throws IOException { if (out == null) throw new IllegalArgumentException("Print stream for log handling was not provided."); if (args == null || args.length == 0) throw new IllegalArgumentException("No arguments has been provided."); for (final String arg : args) if (arg == null || arg.isEmpty()) throw new IllegalArgumentException( "Invalid argument '" + arg + "' provided with arguments '" + Arrays.asList(args) + "'."); final ProcessBuilder builder = new ProcessBuilder(args); if (executionDirectory != null) builder.directory(executionDirectory); builder.redirectErrorStream(true); InputStream is = null;//from www .j a v a 2 s. com // // TODO: check if there is any support for forking processes in // maven/plexus // try { final Process process = builder.start(); is = process.getInputStream(); handleLog(is, out); return process.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e.getClass().getName() + " caught during while waiting for a forked process. This exception is not expected to be caught at that time.", e); } finally { // // Exception raised during close operation below are not reported. // That is actually bad. // We do not have any logging facility here and we cannot throw the // exception since this would swallow any // other exception raised in the try block. // May be we should revisit that ... // IOUtils.closeQuietly(is); } }