List of usage examples for org.apache.commons.exec DefaultExecutor setStreamHandler
public void setStreamHandler(final ExecuteStreamHandler streamHandler)
From source file:org.jahia.utils.ProcessHelper.java
/** * Executes the external process using the provided command, arguments (optional), parameter substitution map to expand variables in the * command or arguments in form of <code>${variable}<code> (optional) and a working directory (optional). * Buffers for process output and error stream can be provided. * /* ww w .j a v a2s . c om*/ * @param command * the command to be executed * @param arguments * optional arguments for the command * @param parameterSubstitutionMap * optional values for variables to be expanded * @param workingDir * optional working directory for the process to be started from * @param resultOut * the buffer to write the process execution output into (optional) * @param resultErr * the buffer to write the process execution error into (optional) * @return the execution status * @return redirectOutputs if set to <code>true</code> the output of the execution will be also redirected to standard system out and * the error to error out * @throws JahiaRuntimeException * in case the process execution failed */ public static int execute(String command, String arguments[], Map<String, Object> parameterSubstitutionMap, File workingDir, StringBuilder resultOut, StringBuilder resultErr, boolean redirectOutputs) throws JahiaRuntimeException { long timer = System.currentTimeMillis(); CommandLine cmd = new CommandLine(command); if (arguments != null && arguments.length > 0) { cmd.addArguments(arguments, false); } if (parameterSubstitutionMap != null && !parameterSubstitutionMap.isEmpty()) { cmd.setSubstitutionMap(parameterSubstitutionMap); } if (logger.isDebugEnabled()) { logger.debug("Executing command: {}", cmd.toString()); } else if (redirectOutputs) { logger.info("Executing command: "); logger.info(cmd.toString()); } int exitValue = 0; StringOutputStream out = new StringOutputStream(redirectOutputs ? System.out : null); StringOutputStream err = new StringOutputStream(redirectOutputs ? System.err : null); try { DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(out, err)); if (workingDir != null) { if (workingDir.exists() || workingDir.mkdirs()) { executor.setWorkingDirectory(workingDir); } } exitValue = executor.execute(cmd, System.getenv()); } catch (ExecuteException ee) { return ee.getExitValue(); } catch (Exception e) { throw new JahiaRuntimeException(e); } finally { if (resultErr != null) { resultErr.append(err.toString()); } if (resultOut != null) { resultOut.append(out.toString()); } if (exitValue > 0) { logger.error("External process finished with error. Cause: {}", err.toString()); } if (logger.isDebugEnabled()) { logger.debug("Execution took {} ms and finished with status {} and output {}", new Object[] { (System.currentTimeMillis() - timer), exitValue, out.toString() }); } } return exitValue; }
From source file:org.jberet.support.io.OsCommandBatchlet.java
/** * {@inheritDoc}// w ww.ja v a 2 s.c o m * <p> * This method runs the OS command. * If the command completes successfully, its process exit code is returned. * If there is exception while running the OS command, which may be * caused by timeout, the command being stopped, or other errors, the process * exit code is set as the step exit status, and the exception is thrown. * * @return the OS command process exit code * * @throws Exception upon errors */ @Override public String process() throws Exception { final DefaultExecutor executor = new DefaultExecutor(); final CommandLine commandLineObj; if (commandLine != null) { commandLineObj = CommandLine.parse(commandLine); } else { if (commandArray == null) { throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, null, "commandArray"); } else if (commandArray.isEmpty()) { throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, commandArray.toString(), "commandArray"); } commandLineObj = new CommandLine(commandArray.get(0)); final int len = commandArray.size(); if (len > 1) { for (int i = 1; i < len; i++) { commandLineObj.addArgument(commandArray.get(i)); } } } if (workingDir != null) { executor.setWorkingDirectory(workingDir); } if (streamHandler != null) { executor.setStreamHandler((ExecuteStreamHandler) streamHandler.newInstance()); } SupportLogger.LOGGER.runCommand(commandLineObj.getExecutable(), Arrays.toString(commandLineObj.getArguments()), executor.getWorkingDirectory().getAbsolutePath()); if (commandOkExitValues != null) { executor.setExitValues(commandOkExitValues); } watchdog = new ExecuteWatchdog( timeoutSeconds > 0 ? timeoutSeconds * 1000 : ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); executor.execute(commandLineObj, environment, resultHandler); resultHandler.waitFor(); final ExecuteException exception = resultHandler.getException(); if (exception != null) { stepContext.setExitStatus(String.valueOf(resultHandler.getExitValue())); if (!isStopped) { throw exception; } else { SupportLogger.LOGGER.warn("", exception); } } return String.valueOf(resultHandler.getExitValue()); }
From source file:org.jboss.jdocbook.translate.PotSynchronizerImpl.java
private void executeXml2pot(File masterFile, File potFile) { CommandLine commandLine = CommandLine.parse("xml2pot"); commandLine.addArgument(FileUtils.resolveFullPathName(masterFile)); DefaultExecutor executor = new DefaultExecutor(); try {/* w ww . j av a 2s . c om*/ final FileOutputStream xmlStream = new FileOutputStream(potFile); PumpStreamHandler streamDirector = new PumpStreamHandler(xmlStream, System.err); executor.setStreamHandler(streamDirector); try { log.trace("updating POT file {0}", potFile); executor.execute(commandLine); } finally { try { xmlStream.flush(); xmlStream.close(); } catch (IOException ignore) { // intentionally empty... } } } catch (IOException e) { throw new JDocBookProcessException("unable to open output stream for POT file [" + potFile + "]"); } }
From source file:org.jboss.jdocbook.translate.TranslatorImpl.java
private void generateTranslatedXML(File masterFile, File poFile, File translatedFile) { if (!masterFile.exists()) { log.trace("skipping translation; source file did not exist : {}", masterFile); return;//from ww w. j a v a2 s . co m } if (!poFile.exists()) { log.trace("skipping translation; PO file did not exist : {}", poFile); return; } if (translatedFile.exists() && translatedFile.lastModified() >= masterFile.lastModified() && translatedFile.lastModified() >= poFile.lastModified()) { log.trace("skipping translation; up-to-date : {0}", translatedFile); return; } if (!translatedFile.getParentFile().exists()) { boolean created = translatedFile.getParentFile().mkdirs(); if (!created) { log.info("Unable to create directories for translation"); } } CommandLine commandLine = CommandLine.parse("po2xml"); commandLine.addArgument(FileUtils.resolveFullPathName(masterFile)); commandLine.addArgument(FileUtils.resolveFullPathName(poFile)); try { final FileOutputStream xmlStream = new FileOutputStream(translatedFile); DefaultExecutor executor = new DefaultExecutor(); try { PumpStreamHandler streamDirector = new PumpStreamHandler(xmlStream, System.err); executor.setStreamHandler(streamDirector); executor.execute(commandLine); } catch (IOException ioe) { throw new JDocBookProcessException("unable to execute po2xml : " + ioe.getMessage()); } finally { try { xmlStream.flush(); xmlStream.close(); } catch (IOException ignore) { // intentionally empty... } } } catch (IOException e) { throw new JDocBookProcessException( "unable to open output stream for translated XML file [" + translatedFile + "]"); } }
From source file:org.jboss.tools.windup.runtime.WindupRmiClient.java
public void startWindup(final IProgressMonitor monitor, String jreHome) { logInfo("Begin start RHAMT."); //$NON-NLS-1$ monitor.worked(1);/*from w ww . j av a 2 s . c o m*/ String windupExecutable = WindupRuntimePlugin.computeWindupExecutable(); if (windupExecutable == null) { WindupRuntimePlugin.logErrorMessage("rhamt-cli not specified."); //$NON-NLS-1$ return; } boolean executable = new File(windupExecutable).setExecutable(true); if (!executable) { WindupRuntimePlugin.logErrorMessage("rhamt-cli not executable."); //$NON-NLS-1$ return; } CommandLine cmdLine = CommandLine.parse(windupExecutable); Map<String, String> env = Maps.newHashMap(); for (Map.Entry<String, String> entry : System.getenv().entrySet()) { env.put(entry.getKey(), entry.getValue()); } if (!jreHome.trim().isEmpty()) { env.put(JAVA_HOME, jreHome); } logInfo("Using " + JAVA_HOME + " - " + jreHome); cmdLine.addArgument("--startServer"); //$NON-NLS-1$ cmdLine.addArgument(String.valueOf(getRmiPort())); watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); ExecuteResultHandler handler = new ExecuteResultHandler() { @Override public void onProcessFailed(ExecuteException e) { logInfo("The RHAMT process failed:"); //$NON-NLS-1$ logInfo(e.getMessage()); //$NON-NLS-1$ executionBuilder = null; notifyServerChanged(); } @Override public void onProcessComplete(int exitValue) { logInfo("The RHAMT process has completed."); //$NON-NLS-1$ executionBuilder = null; notifyServerChanged(); } }; DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() { @Override protected void processLine(String line, int logLevel) { logInfo("Message from RHAMT executor: " + line); //$NON-NLS-1$ monitor.worked(1); } })); executor.setWatchdog(watchdog); executor.setExitValue(1); monitor.worked(1); try { logInfo("Starting RHAMT in server mode..."); //$NON-NLS-1$ logInfo("Command-line: " + cmdLine); //$NON-NLS-1$ executor.execute(cmdLine, env, handler); } catch (IOException e) { WindupRuntimePlugin.log(e); } }
From source file:org.jcronjob.agent.AgentProcessor.java
@Override public Response execute(Request request) throws TException { if (!this.password.equalsIgnoreCase(request.getPassword())) { return errorPasswordResponse(request); }/*w w w . j a va2s. co m*/ String command = request.getParams().get("command") + EXITCODE_SCRIPT; String pid = request.getParams().get("pid"); logger.info("[cronjob]:execute:{},pid:{}", command, pid); File shellFile = CommandUtils.createShellFile(command, pid); Integer exitValue = 1; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Response response = Response.response(request); try { CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath()); DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream); executor.setStreamHandler(stream); response.setStartTime(new Date().getTime()); exitValue = executor.execute(commandLine); exitValue = exitValue == null ? 0 : exitValue; } catch (Exception e) { if (e instanceof ExecuteException) { exitValue = ((ExecuteException) e).getExitValue(); } else { exitValue = CronJob.StatusCode.ERROR_EXEC.getValue(); } if (exitValue == CronJob.StatusCode.KILL.getValue()) { logger.info("[cronjob]:job has be killed!at pid :{}", request.getParams().get("pid")); } else { logger.info("[cronjob]:job execute error:{}", e.getCause().getMessage()); } } finally { if (outputStream != null) { String text = outputStream.toString(); if (notEmpty(text)) { try { response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY))); response.setExitCode(Integer.parseInt( text.substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim())); } catch (IndexOutOfBoundsException e) { response.setMessage(text); response.setExitCode(exitValue); } catch (NumberFormatException e) { response.setExitCode(exitValue); } } else { response.setExitCode(exitValue); } try { outputStream.close(); } catch (Exception e) { logger.error("[cronjob]:error:{}", e); } } else { response.setExitCode(exitValue); } response.setSuccess(response.getExitCode() == CronJob.StatusCode.SUCCESS_EXIT.getValue()).end(); if (shellFile != null) { shellFile.delete();// } } logger.info("[cronjob]:execute result:{}", response.toString()); return response; }
From source file:org.jlab.clara.std.services.DataManager.java
private void stageInputFile(FilePaths files, EngineData output) { Path stagePath = FileUtils.getParent(files.stagedInputFile); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {/*from w w w.j av a2 s. c om*/ FileUtils.createDirectories(stagePath); CommandLine cmdLine = new CommandLine("cp"); cmdLine.addArgument(files.inputFile.toString()); cmdLine.addArgument(files.stagedInputFile.toString()); DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); System.out.printf("%s service: input file '%s' copied to '%s'%n", NAME, files.inputFile, stagePath); returnFilePaths(output, files); } catch (ExecuteException e) { ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim()); } catch (IOException e) { ServiceUtils.setError(output, "could not complete request: " + e.getMessage()); } }
From source file:org.jlab.clara.std.services.DataManager.java
private void removeStagedInputFile(FilePaths files, EngineData output) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {//from w w w . ja va 2 s. co m CommandLine cmdLine = new CommandLine("rm"); cmdLine.addArgument(files.stagedInputFile.toString()); DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); System.out.printf("%s service: staged input file %s removed%n", NAME, files.stagedInputFile); returnFilePaths(output, files); } catch (ExecuteException e) { ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim()); } catch (IOException e) { ServiceUtils.setError(output, "could not complete request: " + e.getMessage()); } }
From source file:org.jlab.clara.std.services.DataManager.java
private void saveOutputFile(FilePaths files, EngineData output) { Path outputPath = FileUtils.getParent(files.outputFile); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {//from ww w . ja v a 2 s .co m FileUtils.createDirectories(outputPath); CommandLine cmdLine = new CommandLine("mv"); // cmdLine.addArgument(files.stagedOutputFile.toString()); // cmdLine.addArgument(files.outputFile.toString()); // modified 09.12.18. Stage back multiple output files. vg Files.list(directoryPaths.stagePath).forEach(name -> { name.startsWith(files.stagedOutputFile.toString()); cmdLine.addArgument(name.toString()); }); cmdLine.addArgument(outputPath.toString()); // vg DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); System.out.printf("%s service: output file '%s' saved to '%s'%n", NAME, files.stagedOutputFile, outputPath); returnFilePaths(output, files); } catch (ExecuteException e) { ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim()); } catch (IOException e) { ServiceUtils.setError(output, "could not complete request: " + e.getMessage()); } }
From source file:org.kercoin.magrit.core.build.BuildTask.java
private int build(ByteArrayOutputStream stdout, PrintStream printOut) throws IOException { String command = findCommand(); printOut.println(String.format("Starting build with command '%s'", command)); CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executable = new DefaultExecutor(); executable.setWorkingDirectory(repository.getDirectory().getParentFile()); executable.setStreamHandler(new PumpStreamHandler(stdout)); return executable.execute(cmdLine); }