List of usage examples for org.apache.commons.exec DefaultExecuteResultHandler DefaultExecuteResultHandler
public DefaultExecuteResultHandler()
From source file:org.jfastcgi.client.FastCGIHandler.java
public void startProcess(final String cmd) throws IOException { final DefaultExecutor pe = new DefaultExecutor(); processExecutor = pe;/*from ww w .j a v a2 s. c o m*/ pe.setWatchdog(new ExecuteWatchdog(60000)); processExecutor.setStreamHandler(new ExecuteStreamHandler() { private final Set<StreamLogger> loggers = new HashSet<StreamLogger>(); public void stop() throws IOException { } public void start() throws IOException { } public void setProcessOutputStream(final InputStream is) throws IOException { loggers.add(new StreamLogger(is, LoggerFactory.getLogger(FastCGIHandler.class.getName() + ".externalprocess.stdout"))); } public void setProcessInputStream(final OutputStream os) throws IOException { } public void setProcessErrorStream(final InputStream is) throws IOException { loggers.add(new StreamLogger(is, LoggerFactory.getLogger(FastCGIHandler.class.getName() + ".externalprocess.stderr"))); } }); getLog().info("Starting external process : " + cmd); pe.execute(CommandLine.parse(cmd), new DefaultExecuteResultHandler() { @Override public void onProcessFailed(final ExecuteException e) { super.onProcessFailed(e); getLog().error("while running process", e); } @Override public void onProcessComplete(final int exitValue) { getLog().info(String.format("external process exited with code %s : %s", exitValue, cmd)); } }); }
From source file:org.moneta.DropwizardContractTest.java
@BeforeClass public static void setUpBeforeClass() throws Exception { System.out.println("Java Temp Dir: " + System.getProperty("java.io.tmpdir")); executor = new DefaultExecutor(); resultHandler = new DefaultExecuteResultHandler(); String javaHome = System.getProperty("java.home"); String userDir = System.getProperty("user.dir"); executor.setStreamHandler(new PumpStreamHandler(System.out)); watchdog = new ExecuteWatchdog(10000); executor.setWatchdog(watchdog);//from w ww. ja va2 s.co m executor.execute(new CommandLine( javaHome + SystemUtils.FILE_SEPARATOR + "bin" + SystemUtils.FILE_SEPARATOR + "java.exe") .addArgument("-version")); executor.execute( new CommandLine( javaHome + SystemUtils.FILE_SEPARATOR + "bin" + SystemUtils.FILE_SEPARATOR + "java.exe") .addArgument("-jar") .addArgument(userDir + "/../moneta-dropwizard/target/moneta-dropwizard-" + ContractTestSuite.getProjectVersion() + ".jar") .addArgument("server").addArgument( "src/main/resources/dropwizard/moneta-dropwizard.yaml"), resultHandler); Thread.sleep(3000); System.out.println("Test sequence starting...."); }
From source file:org.n52.movingcode.runtime.processors.python.PythonCLIProbe.java
public static boolean testExecutable() { CommandLine commandLine = CommandLine.parse(PythonCLIProcessor.pythonExecutable + " --version"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); Executor executor = new DefaultExecutor(); // put a watchdog with a timeout ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(timeout_seconds) * 1000); executor.setWatchdog(watchdog);//w ww .j a v a 2 s. c o m try { executor.execute(commandLine, resultHandler); resultHandler.waitFor(); int exitVal = resultHandler.getExitValue(); if (exitVal != 0) { return false; } return true; } catch (Exception e) { return false; } }
From source file:org.n52.movingcode.runtime.processors.python.PythonCLIProbe.java
public static String getVersion() { try {//from ww w. j a v a 2s . c o m URL scriptURL = PythonCLIProbe.class.getResource(versionScriptFile); File sf = new File(scriptURL.toURI()); String scriptPath = sf.getAbsolutePath(); CommandLine commandLine = CommandLine.parse(PythonCLIProcessor.pythonExecutable + " " + scriptPath); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); Executor executor = new DefaultExecutor(); // put a watchdog with a timeout ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(timeout_seconds) * 1000); executor.setWatchdog(watchdog); ByteArrayOutputStream os = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(os); executor.setStreamHandler(psh); executor.execute(commandLine, resultHandler); resultHandler.waitFor(); int exitVal = resultHandler.getExitValue(); if (exitVal != 0) { return null; } return (os.toString()); } catch (Exception e) { return null; } }
From source file:org.n52.movingcode.runtime.processors.python.PythonCLIProcessor.java
public void execute(int timeoutSeconds) throws IllegalArgumentException, RuntimeException, IOException { if (!init()) { throw new IOException("Could not initialize the processor. Aborting operation."); }/* w w w . ja v a 2 s . c om*/ // load arguments and parse them to internal data format (--> Strings) for (IOParameter item : this.values()) { try { setValue(item); } catch (IOException e) { throw new IOException("Could not deal with parameter: " + item.getIdentifier().toString() + "\n" + e.getMessage()); } } // create command from parameters and values String executable = packageDescriptionDoc.getPackageDescription().getWorkspace().getExecutableLocation(); if (executable.startsWith("./")) { executable = executable.substring(2); } if (executable.startsWith(".\\")) { executable = executable.substring(2); } executable = "python " + this.clonedWorkspace + File.separator + executable; CommandLine cmdLine = buildCommandLine(executable, this.executionValues, this); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); Executor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream); executor.setStreamHandler(streamHandler); // put a watchdog if required if (timeoutSeconds > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(timeoutSeconds) * 1000); executor.setWatchdog(watchdog); } try { executor.execute(cmdLine, resultHandler); resultHandler.waitFor(); int exitVal = resultHandler.getExitValue(); if (exitVal != 0) { LOGGER.error("stderr was: " + errorStream.toString()); LOGGER.error("stdout was: " + outputStream.toString()); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("stdout was:" + outputStream.toString()); LOGGER.debug("stderr was:" + errorStream.toString()); } } } catch (ExecuteException e) { throw new RuntimeException(e.getMessage()); } catch (IOException e) { throw new IOException(e.getMessage()); } catch (InterruptedException e) { throw new RuntimeException( "Execution was interrupted. Process aborted.\n Message was: " + e.getMessage()); } // update executionData - file data only // code below is all about setting the input stream for output media data for (ParameterID identifier : this.keySet()) { if (this.get(identifier).isMessageOut()) { if (this.get(identifier).supportsType(IODataType.MEDIA)) { @SuppressWarnings("unchecked") List<MediaData> mediaValues = (List<MediaData>) this.get(identifier); for (int i = 0; i < mediaValues.size(); i++) { String fileName = this.executionValues.get(identifier)[i]; // <-- this is the important line --> mediaValues.get(i).setMediaStream(new FileInputStream(fileName)); } } else { // not supported for CLI } } } }
From source file:org.n52.movingcode.runtime.processors.r.RCLIProbe.java
private static boolean testExecutable() { CommandLine commandLine = CommandLine.parse(RCLIProcessor.rExecutable + " " + VERSION_CALL); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); Executor executor = new DefaultExecutor(); // put a watchdog with a timeout ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(TIMEOUT_SECONDS) * 1000); executor.setWatchdog(watchdog);/*from w w w . j av a2 s. c o m*/ try { executor.execute(commandLine, resultHandler); resultHandler.waitFor(); int exitVal = resultHandler.getExitValue(); if (exitVal != 0) { return false; } return true; } catch (Exception e) { return false; } }
From source file:org.n52.movingcode.runtime.processors.r.RCLIProbe.java
private static String getVersion() { try {/*w ww. j a v a 2 s. co m*/ CommandLine commandLine = CommandLine.parse(RCLIProcessor.rExecutable + " " + VERSION_CALL); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); Executor executor = new DefaultExecutor(); // put a watchdog with a timeout ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(TIMEOUT_SECONDS) * 1000); executor.setWatchdog(watchdog); ByteArrayOutputStream os = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(os); executor.setStreamHandler(psh); executor.execute(commandLine, resultHandler); resultHandler.waitFor(); int exitVal = resultHandler.getExitValue(); if (exitVal != 0) { return null; } String osString = os.toString(); String versionString = osString.substring(osString.lastIndexOf(": ") + 2); versionString = versionString.substring(0, versionString.indexOf('\n')); return (versionString); } catch (Exception e) { LOGGER.error("Could not get version string.", e); return null; } }
From source file:org.obm.push.mail.greenmail.ExternalProcess.java
protected ClosableProcess execute(Map<String, String> cliArgs) throws ExternalProcessException { setCommandLineArgs(cliArgs);//from w ww . j a v a 2 s .c o m final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); final Executor executor = buildExecutor(); executeProcess(resultHandler, executor); waitForProcessStartTime(resultHandler); return new ClosableProcess() { @Override public void closeProcess() throws InterruptedException { executor.getWatchdog().destroyProcess(); resultHandler.waitFor(); } }; }
From source file:org.onehippo.forge.gallerymagick.core.command.AbstractMagickCommand.java
/** * Execute the Magick command with the sub-command and arguments. * @param stdOut standard output stream// www . j a v a 2 s . c o m * @throws MagickExecuteException if an execution exception occurs * @throws IOException if IO exception occurs */ public void execute(final OutputStream stdOut) throws IOException { CommandLine cmdLine = createCommandLine(); ByteArrayOutputStream errStream = null; int exitValue = 0; DefaultExecuteResultHandler resultHandler = null; try { errStream = new ByteArrayOutputStream(512); final DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler streamHandler; if (stdOut != null) { streamHandler = new PumpStreamHandler(stdOut, errStream); } else { streamHandler = new PumpStreamHandler(System.out, errStream); } executor.setStreamHandler(streamHandler); if (getWorkingDirectory() != null) { executor.setWorkingDirectory(getWorkingDirectory()); } long timeout = NumberUtils.toLong(System.getProperty(PROP_TIMEOUT), DEFAULT_COMMAND_TIMEOUT); if (timeout > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(DEFAULT_COMMAND_TIMEOUT); executor.setWatchdog(watchdog); resultHandler = new DefaultExecuteResultHandler(); executor.execute(cmdLine, resultHandler); log.debug("Executed with watchdog: {}", cmdLine); resultHandler.waitFor(); } else { exitValue = executor.execute(cmdLine); log.debug("Executed without watchdog: {}", cmdLine); } } catch (ExecuteException | InterruptedException e) { if (resultHandler != null) { exitValue = resultHandler.getExitValue(); } if (e.getCause() == null) { throw new MagickExecuteException(getExecutionErrorMessage(cmdLine, errStream, e), exitValue); } else { throw new MagickExecuteException(getExecutionErrorMessage(cmdLine, errStream, e), exitValue, e.getCause()); } } finally { IOUtils.closeQuietly(errStream); } }
From source file:org.opencron.agent.AgentProcessor.java
@Override public Response execute(final Request request) throws TException { if (!this.password.equalsIgnoreCase(request.getPassword())) { return errorPasswordResponse(request); }/*from w w w .ja va 2 s .c om*/ String command = request.getParams().get("command") + EXITCODE_SCRIPT; String pid = request.getParams().get("pid"); //?? Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L); boolean timeoutFlag = timeout > 0; logger.info("[opencron]:execute:{},pid:{}", command, pid); File shellFile = CommandUtils.createShellFile(command, pid); Integer exitValue; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final Response response = Response.response(request); final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE); final Timer timer = new Timer(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath()); final DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream); executor.setStreamHandler(stream); response.setStartTime(new Date().getTime()); //?0,shell executor.setExitValue(0); if (timeoutFlag) { //... executor.setWatchdog(watchdog); // timer.schedule(new TimerTask() { @Override public void run() { //,kill... if (watchdog.isWatching()) { /** * watchdogdestroyProcesskill... * watchdog.destroyProcess(); */ timer.cancel(); watchdog.stop(); //call kill... request.setAction(Action.KILL); try { kill(request); response.setExitCode(Opencron.StatusCode.TIME_OUT.getValue()); } catch (TException e) { e.printStackTrace(); } } } }, timeout * 60 * 1000); // resultHandler = new DefaultExecuteResultHandler() { @Override public void onProcessComplete(int exitValue) { super.onProcessComplete(exitValue); timer.cancel(); } @Override public void onProcessFailed(ExecuteException e) { super.onProcessFailed(e); timer.cancel(); } }; } executor.execute(commandLine, resultHandler); resultHandler.waitFor(); } catch (Exception e) { if (e instanceof ExecuteException) { exitValue = ((ExecuteException) e).getExitValue(); } else { exitValue = Opencron.StatusCode.ERROR_EXEC.getValue(); } if (Opencron.StatusCode.KILL.getValue().equals(exitValue)) { if (timeoutFlag) { timer.cancel(); watchdog.stop(); } logger.info("[opencron]:job has be killed!at pid :{}", request.getParams().get("pid")); } else { logger.info("[opencron]:job execute error:{}", e.getCause().getMessage()); } } finally { exitValue = resultHandler.getExitValue(); if (CommonUtils.notEmpty(outputStream.toByteArray())) { try { outputStream.flush(); String text = outputStream.toString(); if (notEmpty(text)) { try { text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), ""); response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY))); exitValue = Integer.parseInt(text .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim()); } catch (IndexOutOfBoundsException e) { response.setMessage(text); } } outputStream.close(); } catch (Exception e) { logger.error("[opencron]:error:{}", e); } } if (Opencron.StatusCode.TIME_OUT.getValue() == response.getExitCode()) { response.setSuccess(false).end(); } else { response.setExitCode(exitValue) .setSuccess(response.getExitCode() == Opencron.StatusCode.SUCCESS_EXIT.getValue()).end(); } if (shellFile != null) { shellFile.delete();// } } logger.info("[opencron]:execute result:{}", response.toString()); watchdog.stop(); return response; }