List of usage examples for org.apache.commons.exec PumpStreamHandler PumpStreamHandler
public PumpStreamHandler(final OutputStream out, final OutputStream err)
PumpStreamHandler
. From source file:org.rhq.server.control.ControlCommand.java
protected void killPid(String pid) throws IOException { Executor executor = new DefaultExecutor(); executor.setWorkingDirectory(getBinDir()); PumpStreamHandler streamHandler = new PumpStreamHandler(createNullOutputStream(), createNullOutputStream()); executor.setStreamHandler(streamHandler); org.apache.commons.exec.CommandLine commandLine; commandLine = new org.apache.commons.exec.CommandLine("kill").addArgument(pid); executor.execute(commandLine);/*from w ww . j a va 2 s . com*/ }
From source file:org.rhq.server.control.ControlCommand.java
protected boolean isUnixPidRunning(String pid) { Executor executor = new DefaultExecutor(); executor.setWorkingDirectory(getBinDir()); PumpStreamHandler streamHandler = new PumpStreamHandler(createNullOutputStream(), createNullOutputStream()); executor.setStreamHandler(streamHandler); org.apache.commons.exec.CommandLine commandLine; commandLine = new org.apache.commons.exec.CommandLine("kill").addArgument("-0").addArgument(pid); boolean isRunning = true; // assume it is running try {/*from w ww . j a v a 2 s .c o m*/ int code = executor.execute(commandLine); if (code != 0) { isRunning = false; } } catch (ExecuteException ee) { log.debug("kill -0 for pid [" + pid + "] threw exception with exit value [" + ee.getExitValue() + "]"); if (ee.getExitValue() == 1) { // return code 1 means process does not exist isRunning = false; } } catch (IOException e) { log.error("Checking for running process failed. Will assume it is running. Error: " + e.getMessage()); } log.debug("unix pid [" + pid + "] " + ((isRunning) ? "is" : "is NOT") + " running"); return isRunning; }
From source file:org.rhq.storage.installer.StorageInstaller.java
private String exec(File workingDir, org.apache.commons.exec.CommandLine cmdLine) throws Exception { Executor executor = new DefaultExecutor(); org.apache.commons.io.output.ByteArrayOutputStream buffer = new org.apache.commons.io.output.ByteArrayOutputStream(); NullOutputStream nullOs = new NullOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(nullOs, buffer); executor.setWorkingDirectory(workingDir); executor.setStreamHandler(streamHandler); String result = ""; try {//from w w w . j ava 2 s.co m exec(executor, cmdLine); result = buffer.toString(); } finally { try { buffer.close(); nullOs.close(); } catch (Exception e) { // best effort } } return result; }
From source file:org.sakuli.actions.environment.CommandLineUtil.java
static public CommandLineResult runCommand(String command, boolean throwException) throws SakuliException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream error = new ByteArrayOutputStream(); CommandLineResult result = new CommandLineResult(); try {// w w w .j ava2 s. co m DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(outputStream, error)); int exitCode = executor.execute(CommandLine.parse(command)); result.setExitCode(exitCode); result.setOutput(error.toString() + outputStream.toString()); } catch (Exception e) { if (throwException) { throw new SakuliException(e, String.format("Error during execution of command '%s': %s", command, error.toString())); } result.setExitCode(resolveExitCode(e.getMessage())); result.setOutput(e.getMessage()); } return result; }
From source file:org.sikuli.natives.CommandExecutorHelper.java
public static CommandExecutorResult execute(String commandString, int expectedExitValue) throws Exception { ByteArrayOutputStream error = new ByteArrayOutputStream(); ByteArrayOutputStream stout = new ByteArrayOutputStream(); CommandLine cmd = CommandLine.parse(commandString); try {/*from ww w. j a va 2 s . c o m*/ DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(expectedExitValue); executor.setStreamHandler(new PumpStreamHandler(stout, error)); //if exit value != expectedExitValue => Exception int exitValue = executor.execute(cmd); return new CommandExecutorResult(exitValue, stout.toString(), error.toString()); } catch (Exception e) { int exitValue = -1; if (e instanceof ExecuteException) { exitValue = ((ExecuteException) e).getExitValue(); } throw new CommandExecutorException("error in command " + cmd.toString(), new CommandExecutorResult(exitValue, stout.toString(), error.toString())); } }
From source file:org.springframework.data.release.io.CommonsExecOsCommandOperations.java
private Future<CommandResult> executeCommand(String command, File executionDirectory, boolean silent) throws IOException { StringWriter writer = new StringWriter(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try (WriterOutputStream outputStream = new WriterOutputStream(writer)) { String outerCommand = "/bin/bash -lc"; CommandLine outer = CommandLine.parse(outerCommand); outer.addArgument(command, false); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(executionDirectory); executor.setStreamHandler(new PumpStreamHandler(silent ? outputStream : System.out, null)); executor.execute(outer, ENVIRONMENT, resultHandler); resultHandler.waitFor();//from w w w. j a va 2 s . c o m } catch (InterruptedException e) { throw new IllegalStateException(e); } return new AsyncResult<CommandResult>( new CommandResult(resultHandler.getExitValue(), writer.toString(), resultHandler.getException())); }
From source file:org.stanwood.media.info.MediaFileInfoFetcher.java
private String getCommandOutput(boolean captureStdout, boolean captureStderr, boolean failOnExitCode, String command, Object... args) throws StanwoodException { CommandLine cmdLine = new CommandLine(command); for (Object arg : args) { if (arg instanceof File) { cmdLine.addArgument(((File) arg).getAbsolutePath(), false); } else if (arg instanceof String) { cmdLine.addArgument((String) arg, false); }//from www . j a va 2s.c o m } if (log.isDebugEnabled()) { log.debug("About to execute: " + cmdLine.toString()); //$NON-NLS-1$ } Executor exec = new DefaultExecutor(); exec.setExitValues(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, -1 }); try { ByteArrayOutputStream capture = new ByteArrayOutputStream(); OutputStream out; if (captureStdout) { out = capture; } else { out = new LoggerOutputStream(Level.INFO); } OutputStream err; ; if (captureStderr) { err = capture; } else { err = new LoggerOutputStream(Level.ERROR); } exec.setStreamHandler(new PumpStreamHandler(out, err)); int exitCode = exec.execute(cmdLine); if (failOnExitCode && exitCode != 0) { log.error(capture.toString()); throw new StanwoodException(MessageFormat .format(Messages.getString("MediaFileInfoFetcher.NON_ZERO"), exitCode, cmdLine.toString())); //$NON-NLS-1$ } return capture.toString(); } catch (IOException e) { throw new StanwoodException(MessageFormat .format(Messages.getString("MediaFileInfoFetcher.UnableExecuteSysCmd"), cmdLine.toString()), e); //$NON-NLS-1$ } }
From source file:org.stem.ExternalNode.java
private DefaultExecuteResultHandler startStemProcess(CommandLine commandLine, Map env) throws MojoExecutionException { try {/*from ww w. j a v a 2 s . c o m*/ DefaultExecutor exec = new DefaultExecutor(); DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler(); exec.setWorkingDirectory(nodeDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(log); LogOutputStream stderr = new MavenLogOutputStream(log); log.debug("Executing command line: " + commandLine); PumpStreamHandler streamHandler = new PumpStreamHandler(stdout, stderr); streamHandler.start(); exec.setStreamHandler(streamHandler); exec.execute(commandLine, env, execHandler); // try // { // execHandler.waitFor(); // } // catch (InterruptedException e) // { // e.printStackTrace(); // } return execHandler; } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } }
From source file:org.waarp.gateway.kernel.exec.ExecuteExecutor.java
public void run() throws Reply421Exception { // Check if the execution will be done through LocalExec daemon if (AbstractExecutor.useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(arg, delay, futureCompletion); localExecClient.disconnect(); return; } // else continue }//from www.j a v a2s.c o m // Execution is done internally File exec = new File(args[0]); if (exec.isAbsolute()) { if (!exec.canExecute()) { logger.error("Exec command is not executable: " + args[0]); throw new Reply421Exception("Pre Exec command is not executable"); } } CommandLine commandLine = new CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } int status = -1; try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(10); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e2) { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error("System Exception: " + e.getMessage() + "\n Exec cannot execute command " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } catch (IOException e2) { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error( "Exception: " + e.getMessage() + "\n Exec in error with " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } logger.info("System Exception: " + e.getMessage() + " but finally get the command executed " + commandLine.toString()); } else { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error("Exception: " + e.getMessage() + "\n Exec in error with " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } } catch (IOException e) { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error("Exception: " + e.getMessage() + "\n Exec in error with " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } try { pumpStreamHandler.stop(); } catch (IOException e1) { } if (watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) logger.error("Exec is in Time Out"); status = -1; } if (status == 0) { futureCompletion.setSuccess(); logger.info("Exec OK with {}", commandLine); } else if (status == 1) { logger.warn("Exec in warning with {}", commandLine); futureCompletion.setSuccess(); } else { logger.debug("Status: " + status + (status == -1 ? " Tiemout" : "") + " Exec in error with " + commandLine.toString()); throw new Reply421Exception("Pre command executed in error"); } }
From source file:org.waarp.openr66.context.task.ExecMoveTask.java
@Override public void run() { /*// w w w . ja v a 2 s . c o m * First apply all replacements and format to argRule from context and argTransfer. Will * call exec (from first element of resulting string) with arguments as the following value * from the replacements. Return 0 if OK, else 1 for a warning else as an error. The last * line of stdout will be the new name given to the R66File in case of status 0. The * previous file should be deleted by the script or will be deleted in case of status 0. If * the status is 1, no change is made to the file. */ logger.info("ExecMove with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); // Force the WaitForValidation waitForValidation = true; if (Configuration.configuration.isUseLocalExec() && useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion); LocalExecResult result = localExecClient.getLocalExecResult(); move(result.getStatus(), result.getResult(), finalname); localExecClient.disconnect(); return; } // else continue } String[] args = finalname.split(" "); File exec = new File(args[0]); if (exec.isAbsolute()) { if (!exec.canExecute()) { logger.error("Exec command is not executable: " + finalname); R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner()); futureCompletion.setResult(result); futureCompletion.cancel(); return; } } CommandLine commandLine = new CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = null; try { outputStream = new PipedOutputStream(inputStream); } catch (IOException e1) { try { inputStream.close(); } catch (IOException e) { } logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1); futureCompletion.setFailure(e1); return; } PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } LastLineReader lastLineReader = new LastLineReader(inputStream); Thread thread = new Thread(lastLineReader, "ExecRename" + session.getRunner().getSpecialId()); thread.setDaemon(true); Configuration.configuration.getExecutorService().execute(thread); int status = -1; try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(Configuration.RETRYINMS); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { try { outputStream.close(); } catch (IOException e2) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e2) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } catch (IOException e1) { try { outputStream.close(); } catch (IOException e2) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e2) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error( "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } } else { try { outputStream.close(); } catch (IOException e1) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e1) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error( "ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } } catch (IOException e) { try { outputStream.close(); } catch (IOException e1) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e1) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } try { outputStream.flush(); } catch (IOException e) { } try { outputStream.close(); } catch (IOException e) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } try { if (delay > 0) { thread.join(delay); } else { thread.join(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { inputStream.close(); } catch (IOException e1) { } String newname = null; if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) status = -1; newname = "TimeOut"; } else { newname = lastLineReader.getLastLine(); if (status == 0 && (newname == null || newname.isEmpty())) { status = 1; } } move(status, newname, commandLine.toString()); }