List of usage examples for java.lang ProcessBuilder ProcessBuilder
public ProcessBuilder(String... command)
From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java
public static int executeCommandGetReturnCode(String cmd, String workingDir, String executeFrom) { if (workingDir == null) { workingDir = "/tmp"; }/*from ww w. j a v a 2 s . com*/ logger.debug("Execute command: " + cmd + ". Working dir: " + workingDir); try { String[] splitStr = cmd.split("\\s+"); ProcessBuilder pb = new ProcessBuilder(splitStr); pb.directory(new File(workingDir)); pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output Map<String, String> env = pb.environment(); String path = env.get("PATH"); path = path + File.pathSeparator + "/usr/bin:/usr/sbin"; logger.debug("PATH to execute command: " + pb.environment().get("PATH")); env.put("PATH", path); Process p = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = reader.readLine()) != null) { logger.debug(line); } p.waitFor(); int returnCode = p.exitValue(); logger.debug("Execute command done: " + cmd + ". Get return code: " + returnCode); return returnCode; } catch (InterruptedException | IOException e1) { logger.error("Error when execute command. Error: " + e1); } return -1; }
From source file:hudson.slaves.CommandLauncher.java
@Override public void launch(SlaveComputer computer, final TaskListener listener) { EnvVars _cookie = null;/* w w w . j a va 2s . c o m*/ Process _proc = null; try { Slave node = computer.getNode(); if (node == null) { throw new AbortException("Cannot launch commands on deleted nodes"); } listener.getLogger().println(hudson.model.Messages.Slave_Launching(getTimestamp())); if (getCommand().trim().length() == 0) { listener.getLogger().println(Messages.CommandLauncher_NoLaunchCommand()); return; } listener.getLogger().println("$ " + getCommand()); ProcessBuilder pb = new ProcessBuilder(Util.tokenize(getCommand())); final EnvVars cookie = _cookie = EnvVars.createCookie(); pb.environment().putAll(cookie); pb.environment().put("WORKSPACE", StringUtils.defaultString(computer.getAbsoluteRemoteFs(), node.getRemoteFS())); //path for local slave log {// system defined variables String rootUrl = Jenkins.getInstance().getRootUrl(); if (rootUrl != null) { pb.environment().put("HUDSON_URL", rootUrl); // for backward compatibility pb.environment().put("JENKINS_URL", rootUrl); pb.environment().put("SLAVEJAR_URL", rootUrl + "/jnlpJars/slave.jar"); } } if (env != null) { pb.environment().putAll(env); } final Process proc = _proc = pb.start(); // capture error information from stderr. this will terminate itself // when the process is killed. new StreamCopyThread("stderr copier for remote agent on " + computer.getDisplayName(), proc.getErrorStream(), listener.getLogger()).start(); computer.setChannel(proc.getInputStream(), proc.getOutputStream(), listener.getLogger(), new Channel.Listener() { @Override public void onClosed(Channel channel, IOException cause) { reportProcessTerminated(proc, listener); try { ProcessTree.get().killAll(proc, cookie); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "interrupted", e); } } }); LOGGER.info("slave agent launched for " + computer.getDisplayName()); } catch (InterruptedException e) { e.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch())); } catch (RuntimeException e) { e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError())); } catch (Error e) { e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError())); } catch (IOException e) { Util.displayIOException(e, listener); String msg = Util.getWin32ErrorMessage(e); if (msg == null) { msg = ""; } else { msg = " : " + msg; } msg = hudson.model.Messages.Slave_UnableToLaunch(computer.getDisplayName(), msg); LOGGER.log(Level.SEVERE, msg, e); e.printStackTrace(listener.error(msg)); if (_proc != null) { reportProcessTerminated(_proc, listener); try { ProcessTree.get().killAll(_proc, _cookie); } catch (InterruptedException x) { x.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch())); } } } }
From source file:energy.usef.environment.tool.security.VaultService.java
/** * Executes a class's static main method with the current java executable and classpath in a separate process. * /*from w w w .j a v a2 s . c om*/ * @param klass the class to call the static main method for * @param params the parameters to provide * @return the exit code of the process * @throws IOException * @throws InterruptedException */ public static int exec(@SuppressWarnings("rawtypes") Class klass, List<String> params) throws IOException, InterruptedException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String classpath = System.getProperty("java.class.path"); String className = klass.getCanonicalName(); // construct the command line List<String> command = new ArrayList<String>(); command.add(javaBin); command.add("-cp"); command.add(classpath); command.add(className); command.addAll(params); LOGGER.debug("executing class '{}' with params '{}' in classpath '{}' with java binary '{}'", className, params.toString(), classpath, javaBin); // build and start the Vault's process ProcessBuilder builder = new ProcessBuilder(command); Process process = builder.start(); process.waitFor(); // get the input and error streams of the process and log them InputStream in = process.getInputStream(); InputStream en = process.getErrorStream(); InputStreamReader is = new InputStreamReader(in); InputStreamReader es = new InputStreamReader(en); BufferedReader br = new BufferedReader(is); BufferedReader be = new BufferedReader(es); String read = br.readLine(); while (read != null) { LOGGER.debug(read); read = br.readLine(); } read = be.readLine(); while (read != null) { LOGGER.debug(read); read = be.readLine(); } br.close(); is.close(); in.close(); return process.exitValue(); }
From source file:jetbrains.exodus.util.ForkSupportIO.java
protected ForkSupportIO(@NotNull final String name, @NotNull String[] jvmArgs, @NotNull String[] args) throws IOException { try {/*from ww w .j a v a 2s .c o m*/ serverSocket = new ServerSocket(0, 10); log.info("Listening on port: " + serverSocket.getLocalPort()); } catch (IOException e) { log.fatal("Failed to open server socket.", e); throw e; } this.name = name; // static does not suite here since System.getProperty result can vary final String javaHome = System.getProperty("java.home"); if (javaHome == null || javaHome.length() == 0) { throw new IllegalStateException("java.home is undefined"); } final File bin = new File(javaHome, "bin"); File javaFile = new File(bin, "java"); if (!(javaFile.exists() && javaFile.isFile())) { javaFile = new File(bin, "java.exe"); if (!(javaFile.exists() && javaFile.isFile())) { throw new IllegalStateException(javaFile.getPath() + " doesn't exist"); } } final String classpath = join(getClasspath(getClass()), File.pathSeparator); final String[] commonJvmArgs = { javaFile.getPath(), // "-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=7777", "-cp", classpath }; final List<String> trueArgs = new ArrayList<>(); trueArgs.addAll(Arrays.asList(commonJvmArgs)); trueArgs.addAll(Arrays.asList(jvmArgs)); trueArgs.add(ForkedProcessRunner.class.getName()); trueArgs.add(Integer.toString(serverSocket.getLocalPort())); trueArgs.add(name); trueArgs.addAll(Arrays.asList(args)); log.info("Ready to start process with arguments: " + trueArgs); builder = new ProcessBuilder(trueArgs); }
From source file:com.reelfx.model.ScreenRecorder.java
public void run() { try {//from w ww . j a va2 s . c om if (Applet.IS_MAC) { List<String> macArgs = new ArrayList<String>(); macArgs.add(MAC_EXEC.getAbsolutePath()); macArgs.add(OUTPUT_FILE.getAbsolutePath()); ProcessBuilder pb = new ProcessBuilder(macArgs); recordingProcess = pb.start(); fireProcessUpdate(RECORDING_STARTED); errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "mac E"); inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "mac O"); logger.info("Starting listener threads..."); errorGobbler.start(); inputGobbler.start(); recordingProcess.waitFor(); fireProcessUpdate(RECORDING_COMPLETE); } else if (Applet.IS_LINUX) { // can have problem with file permissions when methods are invoked via Javascript even if applet is signed, // thus some code needs to wrapped in a privledged block AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { try { int width = Applet.CAPTURE_VIEWPORT.width; if (width % 2 != 0) width--; int height = Applet.CAPTURE_VIEWPORT.height; if (height % 2 != 0) height--; List<String> ffmpegArgs = new ArrayList<String>(); //ffmpegArgs.add("/usr/bin/ffmpeg"); ffmpegArgs.add(Applet.BIN_FOLDER.getAbsoluteFile() + File.separator + "ffmpeg"); // screen capture settings ffmpegArgs.addAll( parseParameters("-y -f x11grab -s " + width + "x" + height + " -r 20 -i :0.0+" + Applet.CAPTURE_VIEWPORT.x + "," + Applet.CAPTURE_VIEWPORT.y)); // microphone settings (good resource: http://www.oreilly.de/catalog/multilinux/excerpt/ch14-05.htm) /* 04/29/2010 - ffmpeg gets much better framerate when not recording microphone (let Java do this) * if(audioSource != null) { String driver = audioIndex > 0 ? "/dev/dsp"+audioIndex : "/dev/dsp"; ffmpegArgs.addAll(parseParameters("-f oss -ac 1 -ar "+AudioRecorder.FREQ+" -i "+driver)); }*/ // output file settings ffmpegArgs.addAll(parseParameters("-vcodec mpeg4 -r 20 -b 5000k")); // -s "+Math.round(width*SCALE)+"x"+Math.round(height*SCALE)) ffmpegArgs.add(OUTPUT_FILE.getAbsolutePath()); logger.info("Executing this command: " + prettyCommand(ffmpegArgs)); ProcessBuilder pb = new ProcessBuilder(ffmpegArgs); recordingProcess = pb.start(); // fireProcessUpdate(RECORDING_STARTED); // moved to action listener method errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "ffmpeg E"); inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "ffmpeg O"); logger.info("Starting listener threads..."); errorGobbler.start(); errorGobbler.addActionListener("Stream mapping:", self); inputGobbler.start(); recordingProcess.waitFor(); fireProcessUpdate(RECORDING_COMPLETE); } catch (Exception e) { logger.error("Error running Linux screen recorder!", e); } return null; } }); } else if (Applet.IS_WINDOWS) { // can have problem with file permissions when methods are invoked via Javascript even if applet is signed, // thus some code needs to wrapped in a privileged block AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { try { List<String> ffmpegArgs = new ArrayList<String>(); ffmpegArgs.add(FFMPEG_EXEC.getAbsolutePath()); // for full screen, use simply "cursor:desktop" int width = Applet.CAPTURE_VIEWPORT.width % 2 == 0 ? Applet.CAPTURE_VIEWPORT.width : Applet.CAPTURE_VIEWPORT.width - 1; int height = Applet.CAPTURE_VIEWPORT.height % 2 == 0 ? Applet.CAPTURE_VIEWPORT.height : Applet.CAPTURE_VIEWPORT.height - 1; String viewport = ":offset=" + Applet.CAPTURE_VIEWPORT.x + "," + Applet.CAPTURE_VIEWPORT.y; viewport += ":size=" + width + "," + height; ffmpegArgs.addAll(parseParameters("-y -f gdigrab -r 20 -i cursor:desktop" + viewport + " -vcodec mpeg4 -b 5000k " + OUTPUT_FILE)); logger.info("Executing this command: " + prettyCommand(ffmpegArgs)); ProcessBuilder pb = new ProcessBuilder(ffmpegArgs); recordingProcess = pb.start(); //fireProcessUpdate(RECORDING_STARTED); // moved to action listener method // ffmpeg doesn't get the microphone on Windows, but this allows it to record a better frame rate anyway errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "ffmpeg E"); inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "ffmpeg O"); logger.info("Starting listener threads..."); errorGobbler.start(); errorGobbler.addActionListener("Stream mapping:", self); inputGobbler.start(); recordingProcess.waitFor(); fireProcessUpdate(RECORDING_COMPLETE); } catch (Exception e) { logger.error("Error while running Windows screen recorder!", e); } return null; } }); } } catch (Exception ie) { logger.error("Exception while running ScreenRecorder!", ie); } }
From source file:cz.cuni.mff.ksi.jinfer.autoeditor.BububuEditor.java
/** * Draws automaton and waits until user picks two states and clicks * 'continue' button.// w ww . j a v a 2 s . c o m * * @param automaton automaton to be drawn * @return if user picks exactly two states returns Pair of them otherwise null */ @Override public List<State<T>> drawAutomatonToPickStates(final Automaton<T> automaton) { final DirectedSparseMultigraph<State<T>, Step<T>> graph = new DirectedSparseMultigraph<State<T>, Step<T>>(); final Map<State<T>, Set<Step<T>>> automatonDelta = automaton.getDelta(); // Get vertices = states of automaton for (Entry<State<T>, Set<Step<T>>> entry : automatonDelta.entrySet()) { graph.addVertex(entry.getKey()); } // Get edges of automaton for (Entry<State<T>, Set<Step<T>>> entry : automatonDelta.entrySet()) { for (Step<T> step : entry.getValue()) { graph.addEdge(step, step.getSource(), step.getDestination()); } } Map<State<T>, Point2D> positions = new HashMap<State<T>, Point2D>(); ProcessBuilder p = new ProcessBuilder(Arrays.asList("/usr/bin/dot", "-Tplain")); try { Process k = p.start(); k.getOutputStream().write((new AutomatonToDot<T>()).convertToDot(automaton, symbolToString).getBytes()); k.getOutputStream().flush(); BufferedReader b = new BufferedReader(new InputStreamReader(k.getInputStream())); k.getOutputStream().close(); Scanner s = new Scanner(b); s.next(); s.next(); double width = s.nextDouble(); double height = s.nextDouble(); double windowW = 500; double windowH = 300; while (s.hasNext()) { if (s.next().equals("node")) { int nodeName = s.nextInt(); double x = s.nextDouble(); double y = s.nextDouble(); for (State<T> state : automatonDelta.keySet()) { if (state.getName() == nodeName) { positions.put(state, new Point((int) (windowW * x / width), (int) (windowH * y / height))); break; } } } } } catch (IOException ex) { Exceptions.printStackTrace(ex); } Transformer<State<T>, Point2D> trans = TransformerUtils.mapTransformer(positions); // TODO rio find suitable layout final Layout<State<T>, Step<T>> layout = new StaticLayout<State<T>, Step<T>>(graph, trans); //layout.setSize(new Dimension(300,300)); // sets the initial size of the space visualizationViewer = new VisualizationViewer<State<T>, Step<T>>(layout); //visualizationViewer.setPreferredSize(new Dimension(350,350)); //Sets the viewing area size visualizationViewer.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<State<T>>()); visualizationViewer.getRenderContext().setEdgeLabelTransformer(new Transformer<Step<T>, String>() { @Override public String transform(Step<T> i) { return BububuEditor.this.symbolToString.toString(i.getAcceptSymbol()); } }); final PluggableGraphMouse gm = new PluggableGraphMouse(); gm.add(new PickingUnlimitedGraphMousePlugin<State<T>, Step<T>>()); visualizationViewer.setGraphMouse(gm); // Call GUI in a special thread. Required by NB. synchronized (this) { WindowManager.getDefault().invokeWhenUIReady(new Runnable() { @Override public void run() { // Pass this as argument so the thread will be able to wake us up. AutoEditorTopComponent.findInstance().drawAutomatonBasicVisualizationServer(BububuEditor.this, visualizationViewer, "Please select two states to be merged together."); } }); try { // Sleep on this. this.wait(); } catch (InterruptedException e) { return null; } } /* AutoEditorTopComponent wakes us up. Get the result and return it. * VisualizationViewer should give us the information about picked vertices. */ final Set<State<T>> pickedSet = visualizationViewer.getPickedVertexState().getPicked(); List<State<T>> lst = new ArrayList<State<T>>(pickedSet); return lst; }
From source file:eu.abc4trust.cryptoEngine.uprove.util.UProveLauncher.java
public void start(int port, String name) { this.startCalled = true; // System.out.println("UProveLauncher.start - instance : " + this + // " - port : " + launchName + " :" + launchPort + " - is stopped == " + // stopped + " - uproveProcess " + this.uproveProcess ); ProcessBuilder processBuilder; if (this.isWindows()) { processBuilder = new ProcessBuilder(this.WINDOWS_COMMAND); } else {/* w w w . j av a 2 s . c o m*/ processBuilder = new ProcessBuilder(this.NON_WINDOWS_COMMAND); } processBuilder.command().add("" + port); //Map<String, String> env = processBuilder.environment(); //env.clear(); processBuilder.directory(this.workingDirectory); try { this.uproveProcess = processBuilder.start(); // System.out.println(this.uproveProcess.exitValue()); InputStream is = this.uproveProcess.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; String terminationString = "Press Enter to exit"; boolean done = false; while (!done) { line = br.readLine(); if (line != null) { System.out.println(line); done = line.endsWith(terminationString); } else { System.out.println("UProveLauncher - we get null on stdout from process - process has died.."); break; } } this.debugOutputCollector = new DebugOutputCollector(this.uproveProcess, name); this.debugOutput = new Thread(this.debugOutputCollector, "DebugCollector"); if (done) this.debugOutput.start(); // System.out.println("process started"); } catch (IOException ex) { throw new RuntimeException(ex); } }
From source file:de.teamgrit.grit.checking.compile.HaskellCompileChecker.java
/** * checkProgram invokes the Haskell compiler on a given file and reports * the output./*from w w w. jav a 2 s . c o m*/ * * @param pathToProgramFile * Specifies the file or folder containing that should be * compiled. (accepts .lhs and .hs files) * @param compilerName * The compiler to be used (usually ghc). * @param compilerFlags * Additional flags to be passed to the compiler. * @throws FileNotFoundException * Is thrown when the file in pathToProgramFile cannot be * opened * @throws BadCompilerSpecifiedException * Is thrown when the given compiler cannot be called * @return A {@link CompilerOutput} that contains all compiler messages and * flags on how the compile run went. * @throws BadFlagException * When ghc doesn't recognize a flag, this exception is thrown. */ @Override public CompilerOutput checkProgram(Path pathToProgramFile, String compilerName, List<String> compilerFlags) throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException { Process compilerProcess = null; try { // create compiler invocation. List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName, compilerFlags); ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation); // make sure the compiler stays in its directory. compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile()); compilerProcess = compilerProcessBuilder.start(); // this will never happen because createCompilerInvocation never // throws this Exception. Throw declaration needs to be in method // declaration because of the implemented Interface although we // never use it in the HaskellCompileChecker } catch (CompilerOutputFolderExistsException e) { LOGGER.severe("A problem while compiling, which never should happen, occured" + e.getMessage()); } catch (BadCompilerSpecifiedException e) { throw new BadCompilerSpecifiedException(e.getMessage()); } catch (IOException e) { // If we cannot call the compiler we return a CompilerOutput // initialized with false, false, indicating // that the compiler wasn't invoked properly and that there was no // clean Compile. CompilerOutput compilerInvokeError = new CompilerOutput(); compilerInvokeError.setClean(false); compilerInvokeError.setCompilerInvoked(false); return compilerInvokeError; } // Now we read compiler output. If everything is ok ghc reports // nothing in the errorStream. InputStream compilerOutputStream = compilerProcess.getErrorStream(); InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream); BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader); String line; CompilerOutput compilerOutput = new CompilerOutput(); compilerOutput.setCompilerInvoked(true); List<String> compilerOutputLines = new LinkedList<>(); try { while ((line = compilerOutputBuffer.readLine()) != null) { compilerOutputLines.add(line); } // Errors are separated via an empty line (""). But after the // the last error the OutputBuffer has nothing more to write. // In order to recognize the last error we insert an empty String // at the end of the list. // Only needs to be done when there are errors. if (compilerOutputLines.size() != 0) { line = ""; compilerOutputLines.add(line); } compilerOutputStream.close(); compilerStreamReader.close(); compilerOutputBuffer.close(); compilerProcess.destroy(); } catch (IOException e) { // Reading might go wrong here if ghc should unexpectedly die LOGGER.severe("Error while reading from compiler stream."); compilerOutput.setClean(false); compilerOutput.setCompileStreamBroken(true); return compilerOutput; } // ghc -c generates a .o(object) and a .hi(haskell interface) file. // But we don't need those files so they can be deleted. // The generated files have the same name like our input file so we // can just exchange the file endings in order to get the // correct file paths for deletion if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) { // we use a file walker in order to find all files in the folder // and its subfolders RegexDirectoryWalker dirWalker = new RegexDirectoryWalker(".+\\.([Ll])?[Hh][Ss]"); try { Files.walkFileTree(pathToProgramFile, dirWalker); } catch (IOException e) { LOGGER.severe("Could not walk submission " + pathToProgramFile.toString() + " while building copiler invocation: " + e.getMessage()); } for (Path candidatePath : dirWalker.getFoundFiles()) { File candidateFile = candidatePath.toFile(); if (!candidateFile.isDirectory()) { String extension = FilenameUtils.getExtension(candidateFile.toString()); if (extension.matches("[Ll]?[Hh][Ss]")) { File ghcGeneratedObject = new File( FilenameUtils.removeExtension(candidateFile.toString()) + ".o"); File ghcGeneratedInterface = new File( FilenameUtils.removeExtension(candidateFile.toString()) + ".hi"); ghcGeneratedObject.delete(); ghcGeneratedInterface.delete(); } } } } else { String extension = FilenameUtils.getExtension(pathToProgramFile.toString()); if (extension.matches("[Ll]?[Hh][Ss]")) { File ghcGeneratedObject = new File( FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".o"); File ghcGeneratedInterface = new File( FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".hi"); ghcGeneratedObject.delete(); ghcGeneratedInterface.delete(); } } // if there are no errors there is no Output to handle if (compilerOutputLines.size() != 0) { compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput); } else { compilerOutput.setClean(true); } return compilerOutput; }
From source file:com.anrisoftware.globalpom.exec.core.DefaultProcessTask.java
@Override public ProcessTask call() throws CommandExecException { List<String> command = commandLine.getCommand(); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(commandLine.getWorkingDir()); builder.redirectOutput(Redirect.PIPE); builder.redirectError(Redirect.PIPE); builder.redirectInput(Redirect.PIPE); try {/* w w w .j a va 2 s . c o m*/ startProcess(builder); } catch (IOException e) { throw log.errorStartCommand(this, e, commandLine); } catch (InterruptedException e) { throw log.commandInterrupted(this, e, commandLine); } catch (ExecutionException e) { throw log.errorStartCommand(this, e.getCause(), commandLine); } return this; }
From source file:org.mashupmedia.encode.ProcessManager.java
public void startProcess(ProcessQueueItem processQueueItem) throws IOException { try {/*ww w . j av a2 s. c o m*/ logger.info("Starting process..."); List<String> commands = processQueueItem.getCommands(); ProcessBuilder processBuilder = new ProcessBuilder(commands); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); // The started on date should have already been set Date startedOn = processQueueItem.getProcessStartedOn(); if (startedOn == null) { processQueueItem.setProcessStartedOn(new Date()); } processQueueItem.setProcess(process); InputStream inputStream = process.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = bufferedReader.readLine()) != null) { logger.info(line); } IOUtils.closeQuietly(inputStream); try { int waitForValue = process.waitFor(); logger.info("Process waitFor value = " + waitForValue); } catch (InterruptedException e) { logger.error("Error waiting for waitFor.", e); } int exitValue = process.exitValue(); logger.info("Process exit value = " + exitValue); } finally { processQueueItems.remove(processQueueItem); encodeMediaItemTaskManager.processQueue(); } }