/** * @see org.apache.commons.exec.ExecuteResultHandler#onProcessFailed(org.apache.commons.exec.ExecuteException) */ public void onProcessFailed(final ExecuteException e) { this.exitValue = e.getExitValue(); this.exception = e; this.hasResult = true; }
retval = StringUtils.chomp(stdout.toString()); if (resultHandler.getException() != null) { logger.warn("{}", resultHandler.getException().getMessage()); } else { logger.debug("exit code '{}', result '{}'", exitCode, retval);
/** * Stopping a pumper thread. The implementation actually waits * longer than specified in 'timeout' to detect if the timeout * was indeed exceeded. If the timeout was exceeded an IOException * is created to be thrown to the caller. * * @param thread the thread to be stopped * @param timeout the time in ms to wait to join */ protected void stopThread(final Thread thread, final long timeout) { if (thread != null) { try { if (timeout == 0) { thread.join(); } else { final long timeToWait = timeout + STOP_TIMEOUT_ADDITION; final long startTime = System.currentTimeMillis(); thread.join(timeToWait); if (!(System.currentTimeMillis() < startTime + timeToWait)) { final String msg = "The stop timeout of " + timeout + " ms was exceeded"; caught = new ExecuteException(msg, Executor.INVALID_EXITVALUE); } } } catch (final InterruptedException e) { thread.interrupt(); } } }
@Override public String handle(Task aTask) throws Exception { File scriptFile = File.createTempFile("_script", ".sh"); File logFile = File.createTempFile("log", null); FileUtils.writeStringToFile(scriptFile, aTask.getRequiredString("script")); try (PrintStream stream = new PrintStream(logFile);) { Process chmod = Runtime.getRuntime().exec(String.format("chmod u+x %s",scriptFile.getAbsolutePath())); int chmodRetCode = chmod.waitFor(); if(chmodRetCode != 0) { throw new ExecuteException("Failed to chmod", chmodRetCode); } CommandLine cmd = new CommandLine (scriptFile.getAbsolutePath()); logger.debug("{}",cmd); DefaultExecutor exec = new DefaultExecutor(); exec.setStreamHandler(new PumpStreamHandler(stream)); exec.execute(cmd); return FileUtils.readFileToString(logFile); } catch (ExecuteException e) { throw new ExecuteException(e.getMessage(),e.getExitValue(), new RuntimeException(FileUtils.readFileToString(logFile))); } finally { FileUtils.deleteQuietly(logFile); FileUtils.deleteQuietly(scriptFile); } }
LOG.error("ExecException while executing command: " + command.toString() + " - " + ee.getMessage()); throw new ExecException("Failed to execute command " + command, stdout, stderr, ee.getExitValue(), ee);
private static void execute(CommandLine cmdLine, File dir, DefaultExecutor executor, Map<String,String> environment) throws IOException { log.info("-Executing(" + dir + "): " + cmdLine); try { int exitValue = executor.execute(cmdLine, environment); if (exitValue != 0) { log.info("Had exit code " + exitValue + " when calling " + cmdLine); } } catch (ExecuteException e) { throw new ExecuteException("While executing (" + dir + "); " + cmdLine, e.getExitValue(), e); } } }
LOG.debug("outputStream: " + outputStream.toString()); entry.put("exitValue", String.valueOf(resultHandler.getExitValue())); entry.put("outputStream", outputStream.toString() + e.getMessage()); e.printStackTrace(); return entry; } catch (IOException e) {
resultHandler.getException().printStackTrace(); throw new ExecuteException("problems running command: " + command, resultHandler.getExitValue());
@Override public Map<String,Object> handle (Task aTask) throws Exception { CommandLine cmd = new CommandLine ("mediainfo"); cmd.addArgument(aTask.getRequiredString("input")); log.debug("{}",cmd); DefaultExecutor exec = new DefaultExecutor(); File tempFile = File.createTempFile("log", null); try (PrintStream stream = new PrintStream(tempFile);) { exec.setStreamHandler(new PumpStreamHandler(stream)); exec.execute(cmd); return parse(FileUtils.readFileToString(tempFile)); } catch (ExecuteException e) { throw new ExecuteException(e.getMessage(),e.getExitValue(), new RuntimeException(FileUtils.readFileToString(tempFile))); } finally { FileUtils.deleteQuietly(tempFile); } }
@Override public Object handle(Task aTask) throws Exception { List<String> options = aTask.getList("options", String.class); CommandLine cmd = new CommandLine ("ffmpeg"); options.forEach(o->cmd.addArgument(o)); log.debug("{}",cmd); DefaultExecutor exec = new DefaultExecutor(); File tempFile = File.createTempFile("log", null); try (PrintStream stream = new PrintStream(tempFile);) { exec.setStreamHandler(new PumpStreamHandler(stream)); int exitValue = exec.execute(cmd); return exitValue!=0?FileUtils.readFileToString(tempFile):cmd.toString(); } catch (ExecuteException e) { throw new ExecuteException(e.getMessage(),e.getExitValue(), new RuntimeException(FileUtils.readFileToString(tempFile))); } finally { FileUtils.deleteQuietly(tempFile); } }
protected int doExecution(DefaultExecutor executor, CommandLine commandLine, Map<Object, Object> env) { try { final StringJoiner paramsJoiner = new StringJoiner(" "); for (String cmdArg : commandLine.toStrings()) { paramsJoiner.add(cmdArg.replaceAll("(?<=\\.password=)(.*)", "****")); } logger.info("Executing: " + paramsJoiner.toString()); return executor.execute(commandLine, env); } catch (ExecuteException e) { return e.getExitValue(); } catch (Exception e) { throw new MuleControllerException("Error executing [" + commandLine.getExecutable() + " " + commandLine.getArguments() + "]", e); } }
@Override public void onProcessFailed(final ExecuteException e) { super.onProcessFailed(e); if (watchdog != null && watchdog.killedProcess()) { LOG.warn("Installation killed by watchdog"); } else { LOG.warn("Installation failed due to [{}]", e.getMessage()); } } }
/** * @see org.apache.commons.exec.Executor#execute(CommandLine, * java.util.Map, org.apache.commons.exec.ExecuteResultHandler) */ public void execute(final CommandLine command, final Map<String, String> environment, final ExecuteResultHandler handler) throws ExecuteException, IOException { if (workingDirectory != null && !workingDirectory.exists()) { throw new IOException(workingDirectory + " doesn't exist."); } if (watchdog != null) { watchdog.setProcessNotStarted(); } final Runnable runnable = new Runnable() { public void run() { int exitValue = Executor.INVALID_EXITVALUE; try { exitValue = executeInternal(command, environment, workingDirectory, streamHandler); handler.onProcessComplete(exitValue); } catch (final ExecuteException e) { handler.onProcessFailed(e); } catch (final Exception e) { handler.onProcessFailed(new ExecuteException("Execution failed", exitValue, e)); } } }; this.executorThread = createThread(runnable, "Exec Default Executor"); getExecutorThread().start(); }
@Override public Map<String,Object> handle(Task aTask) throws Exception { CommandLine cmd = new CommandLine ("ffprobe"); cmd.addArgument("-v") .addArgument("quiet") .addArgument("-print_format") .addArgument("json") .addArgument("-show_error") .addArgument("-show_format") .addArgument("-show_streams") .addArgument(aTask.getRequiredString("input")); log.debug("{}",cmd); DefaultExecutor exec = new DefaultExecutor(); File tempFile = File.createTempFile("log", null); try (PrintStream stream = new PrintStream(tempFile);) { exec.setStreamHandler(new PumpStreamHandler(stream)); exec.execute(cmd); return parse(FileUtils.readFileToString(tempFile)); } catch (ExecuteException e) { throw new ExecuteException(e.getMessage(),e.getExitValue(), new RuntimeException(FileUtils.readFileToString(tempFile))); } finally { FileUtils.deleteQuietly(tempFile); } }
private static String executePyhtonScript(File file) throws IOException { // prepare command line CommandLine cmd = new CommandLine("python"); cmd.addArgument(FileUtil.getCanonicalPath(file), true); // prepare capturing script output ByteArrayOutputStream osOutput = new ByteArrayOutputStream(); ByteArrayOutputStream osError = new ByteArrayOutputStream(); PumpStreamHandler streamHeandler = new PumpStreamHandler(osOutput, osError); // execute script DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(streamHeandler); try { int exitValue = executor.execute(cmd); if (exitValue == 0) { return osOutput.toString(StandardCharsets.UTF_8.name()); } else { throw new IOException("Python script execution of '" + FileUtil.getCanonicalPath(file) + "' failed " + "with error code " + exitValue + ":\n" + osError.toString(StandardCharsets.UTF_8.name())); } } catch (ExecuteException ex) { throw new IOException("Python script execution of '" + FileUtil.getCanonicalPath(file) + "' failed " + "with error code " + ex.getExitValue() + ":\n" + osError.toString(StandardCharsets.UTF_8.name())); } }
import org.apache.commons.exec.*; import java.io.IOException; public class NativeKillerRunnable implements Runnable { private static final Logger logger = LoggerFactory.getLogger(NativeKillerRunnable.class); @Override public void run() { String commandtoexec = "top -n 1 -m 100"; CommandLine cmdLine = CommandLine.parse(commandtoexec); DefaultExecutor executor = new DefaultExecutor(); try { PumpStreamHandler psh = new PumpStreamHandler(new LogOutputStream() { @Override protected void processLine(String s, int i) { s = s.trim(); //check for name of your binary process if(s.contains("mybinary")) { String[] strings = s.split(" "); android.os.Process.killProcess(Integer.parseInt(strings[0])); logger.info("killed mybinary process with pid = "+strings[0]); } } }); executor.setStreamHandler(psh); executor.execute(cmdLine); } catch (ExecuteException executeException) { logger.error("caught exception while killing mybinary process "+executeException.getMessage()); } }
public void run() { int exitValue = Executor.INVALID_EXITVALUE; try { exitValue = executeInternal(command, environment, workingDirectory, streamHandler); handler.onProcessComplete(exitValue); } catch (final ExecuteException e) { handler.onProcessFailed(e); } catch (final Exception e) { handler.onProcessFailed(new ExecuteException("Execution failed", exitValue, e)); } } };
/** * Executes the given command synchronously. * * @param command The command to execute. * @param processInput Input provided to the process. * @return The result of the execution, or empty if the process does not terminate within the timeout set for this executor. * @throws IOException if the process execution failed. */ public Optional<ProcessResult> execute(String command, String processInput) throws IOException { ByteArrayOutputStream processErr = new ByteArrayOutputStream(); ByteArrayOutputStream processOut = new ByteArrayOutputStream(); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(createStreamHandler(processOut, processErr, processInput)); ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.SECONDS.toMillis(timeoutSeconds)); executor.setWatchdog(watchDog); executor.setExitValues(successExitCodes); int exitCode; try { exitCode = executor.execute(CommandLine.parse(command)); } catch (ExecuteException e) { exitCode = e.getExitValue(); } return (watchDog.killedProcess()) ? Optional.empty() : Optional.of(new ProcessResult(exitCode, processOut.toString(), processErr.toString())); }
return executor.execute(cli, env); // this throws ExecuteException if process return code != 0 } catch (ExecuteException e) { throw new LauncherException("Failed to run Maven: " + e.getMessage() + "\n" + cli, e);
throw new ExecuteException("Process exited with an error: " + exitValue, exitValue);