List of usage examples for org.apache.commons.exec DefaultExecutor execute
public void execute(final CommandLine command, final ExecuteResultHandler handler) throws ExecuteException, IOException
From source file:org.apache.zeppelin.interpreter.launcher.Kubectl.java
public ExecuteWatchdog portForward(String resource, String[] ports) throws IOException { DefaultExecutor executor = new DefaultExecutor(); CommandLine cmd = new CommandLine(kubectlCmd); cmd.addArguments("port-forward"); cmd.addArguments(resource);/* w w w. j a v a 2 s . c om*/ cmd.addArguments(ports); ExecuteWatchdog watchdog = new ExecuteWatchdog(-1); executor.setWatchdog(watchdog); executor.execute(cmd, new ExecuteResultHandler() { @Override public void onProcessComplete(int i) { LOGGER.info("Port-forward stopped"); } @Override public void onProcessFailed(ExecuteException e) { LOGGER.debug("port-forward process exit", e); } }); return watchdog; }
From source file:org.cloudifysource.shell.commands.StartLocalCloud.java
private void startLocalAgent(Admin admin) throws ExecuteException, IOException { File binDir = new File(Environment.getHomeDirectory(), "bin"); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(binDir); CommandLine cmdLine = createCommandLine(); executor.setExitValue(0);/*w w w. j a v a2 s . c o m*/ executor.execute(cmdLine, new ExecuteResultHandler() { @Override public void onProcessFailed(ExecuteException e) { logger.log(Level.SEVERE, "Local Cloud Agent terminated unexpectedly", e); } @Override public void onProcessComplete(int arg0) { logger.fine("Local Cloud Agent terminated"); } }); boolean foundLus = admin.getLookupServices().waitFor(1, 1, TimeUnit.MINUTES); if (!foundLus) { throw new java.lang.IllegalStateException("Local Cloud Lookup Service did not start!"); } }
From source file:org.cloudifysource.shell.commands.TestRecipe.java
/** * Execute a command line in with a given map of environment settings. The execution outupt is filtered unless * verbose is set to true.// ww w . j av a 2s . co m * * @param cmdLine * The command to execute * @param env * Environment settings available for the command execution * @return the command's execution exit code, or -2 if the command failed to execute */ private int executeRecipe(final CommandLine cmdLine, final Map<Object, Object> env) { final DefaultExecutor executor = new DefaultExecutor(); // The watchdog will terminate the process if it does not end within the // specified timeout final int externalProcessTimeout = (this.timeout + EXTERNAL_PROCESS_WATCHDOG_ADDITIONAL_TIMEOUT) * 1000; final ExecuteWatchdog watchdog = new TestRecipeWatchdog(externalProcessTimeout); executor.setWatchdog(watchdog); executor.setExitValue(0); int result = -1; PipedInputStream in = null; PipedOutputStream out = null; BufferedReader reader = null; try { in = new PipedInputStream(); out = new PipedOutputStream(in); reader = new BufferedReader(new InputStreamReader(in)); final Thread thread = new Thread(new FilteredOutputHandler(reader, this.verbose)); thread.setDaemon(true); thread.start(); final PumpStreamHandler psh = new PumpStreamHandler(out, out); executor.setStreamHandler(psh); result = executor.execute(cmdLine, env); } catch (final ExecuteException e) { logger.log(Level.SEVERE, "A problem was encountered while executing the recipe: " + e.getMessage(), e); } catch (final IOException e) { logger.log(Level.SEVERE, "An IO Exception was encountered while executing the recipe: " + e.getMessage(), e); result = UNEXPECTED_ERROR_EXIT_CODE; } return result; }
From source file:org.eclipse.sisu.equinox.launching.internal.DefaultEquinoxLauncher.java
@Override public int execute(LaunchConfiguration configuration, int forkedProcessTimeoutInSeconds) throws EquinoxLaunchingException { String executable = configuration.getJvmExecutable(); if (executable == null || "".equals(executable)) { // use the same JVM as the one used to run Maven (the "java.home" one) executable = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; if (File.separatorChar == '\\') { executable = executable + ".exe"; }//from ww w. jav a2 s . co m } CommandLine cli = new CommandLine(executable); final boolean handleQuotes = false; cli.addArguments(configuration.getVMArguments(), handleQuotes); cli.addArguments(new String[] { "-jar", getCanonicalPath(configuration.getLauncherJar()) }, handleQuotes); cli.addArguments(configuration.getProgramArguments(), handleQuotes); log.info("Command line:\n\t" + cli.toString()); DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = null; if (forkedProcessTimeoutInSeconds > 0) { watchdog = new ExecuteWatchdog(forkedProcessTimeoutInSeconds * 1000L); executor.setWatchdog(watchdog); } // best effort to avoid orphaned child process executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); executor.setWorkingDirectory(configuration.getWorkingDirectory()); try { return executor.execute(cli, getMergedEnvironment(configuration)); } catch (ExecuteException e) { if (watchdog != null && watchdog.killedProcess()) { log.error("Timeout " + forkedProcessTimeoutInSeconds + " s exceeded. Process was killed."); } return e.getExitValue(); } catch (IOException e) { throw new EquinoxLaunchingException(e); } }
From source file:org.excalibur.service.aws.CommandExample.java
public static void main(String[] args) throws ExecuteException, IOException, InterruptedException { CommandLine command = new CommandLine("/bin/bash"); command.addArgument("-c", false); command.addArgument("iperf3 -t 30 -c iperf.scottlinux.com >> output.txt", false); //Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", "iperf3 -t 60 -c localhost"}); // System.out.println(new Mirror().on(process).get().field("pid")); //process.waitFor(); // System.out.println(process.exitValue()); // ManagementFactory.getRuntimeMXBean().getName(); // System.out.println(IOUtils.readLines(process.getInputStream())); //String command = "iperf3 -t 30 -c iperf.scottlinux.com"; ExecuteWatchdog watchdog = new ExecuteWatchdog(10); final DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler()); executor.setExitValue(1);/* ww w .j a v a 2 s.c om*/ executor.execute(command, new ExecuteResultHandler() { @Override public void onProcessFailed(ExecuteException e) { e.printStackTrace(); } @Override public void onProcessComplete(int exitValue) { System.out.println(exitValue); } }); }
From source file:org.jahia.modules.dm.thumbnails.video.impl.VideoThumbnailServiceImpl.java
public boolean generateThumbnail(File videoFile, File outputFile, int offsetSeconds, String size) throws DocumentOperationException { if (!isEnabled()) { logger.info("FFmpeg service is not enabled." + " Skip converting file {}", videoFile); return false; }/*from w w w. jav a 2s .c om*/ long timer = System.currentTimeMillis(); CommandLine cmd = getConvertCommandLine(videoFile, outputFile, String.valueOf(offsetSeconds), StringUtils.defaultIfEmpty(size, "320x240")); if (logger.isDebugEnabled()) { logger.debug("Execuiting thumbnail generation command: {}", cmd.toString()); } int exitValue = 0; StringOutputStream err = new StringOutputStream(); try { DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(null, err)); if (workingDir != null) { if (workingDir.exists() || workingDir.mkdirs()) { executor.setWorkingDirectory(workingDir); } } exitValue = executor.execute(cmd, System.getenv()); } catch (Exception e) { throw new DocumentOperationException(e); } finally { if (exitValue > 0 && err.getLength() > 0) { logger.error("External process finished with error. Cause: {}", err.toString()); } if (logger.isDebugEnabled() && err.getLength() > 0) { logger.debug(err.toString()); } } if (logger.isDebugEnabled()) { logger.debug("Generating thumbnail {} from {} done (exit code: {}) in {} ms", new Object[] { outputFile, videoFile, exitValue, (System.currentTimeMillis() - timer) }); } return exitValue == 0; }
From source file:org.jahia.modules.dm.viewer.impl.PDF2SWFConverterService.java
public boolean convert(File inputPdfFile, File outputSwfFile) throws DocumentOperationException { if (!isEnabled()) { logger.info("pdf2swf conversion service is not enabled." + " Skip converting file {}", inputPdfFile); return false; }/*from www . j ava 2 s.c o m*/ long timer = System.currentTimeMillis(); CommandLine cmd = getConvertCommandLine(inputPdfFile, outputSwfFile); if (logger.isDebugEnabled()) { logger.debug("Execuiting conversion command: {}", cmd.toString()); } int exitValue = 0; StringOutputStream out = new StringOutputStream(); StringOutputStream err = new StringOutputStream(); 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 (Exception e) { throw new DocumentOperationException(e); } finally { if (err.getLength() > 0) { logger.error("Conversion process finished with error. Cause: {}", err.toString()); } if (logger.isDebugEnabled() && out.getLength() > 0) { logger.debug(out.toString()); } } if (logger.isDebugEnabled()) { logger.debug("Conversion from {} to {} done (exit code: {}) in {} ms", new Object[] { inputPdfFile, outputSwfFile, exitValue, (System.currentTimeMillis() - timer) }); } return exitValue == 0; }
From source file:org.jahia.services.templates.SourceControlFactory.java
/** * Sets the executables for various SCM providers. * // w w w . ja v a 2 s .co m * @param sourceControlExecutables * a map with paths to SCM executables by SCM type */ public void setSourceControlExecutables(Map<String, String> sourceControlExecutables) { this.sourceControlExecutables = new HashMap<String, String>(); for (Map.Entry<String, String> entry : sourceControlExecutables.entrySet()) { try { DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler( new PumpStreamHandler(new StringOutputStream(), new StringOutputStream())); executor.execute(new CommandLine(entry.getValue()), System.getenv()); } catch (ExecuteException e) { // ignore this one as the command always returns error code 1 } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug("Unable to execute the " + entry.getKey() + " SCM executable: " + entry.getValue() + ". The SCM provider will be disabled. Cause: " + e.getMessage(), e); } else { logger.info("Cannot find a valid " + entry.getKey() + " SCM executable at: " + entry.getValue() + ". The SCM provider will be skipped."); } continue; } this.sourceControlExecutables.put(entry.getKey(), entry.getValue()); } }
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. * // w w w.j a v a 2 s . co m * @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.jfastcgi.client.FastCGIHandler.java
public void startProcess(final String cmd) throws IOException { final DefaultExecutor pe = new DefaultExecutor(); processExecutor = pe;/*w w w . j av a 2 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)); } }); }