List of usage examples for org.apache.commons.exec DefaultExecutor setStreamHandler
public void setStreamHandler(final ExecuteStreamHandler streamHandler)
From source file:org.eclipse.kura.linux.net.modem.SupportedUsbModems.java
/** * Execute command an return splitted lines * * @param command// w w w . j a va 2s.c o m * the command to execute * @return the lines output by the command * @throws IOException * if executing the commands fails */ private static List<String> execute(final String command) throws ExecuteException, IOException { final DefaultExecutor executor = new DefaultExecutor(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(out, NullOutputStream.NULL_OUTPUT_STREAM)); int rc = executor.execute(CommandLine.parse(command)); s_logger.debug("Called {} - rc = {}", command, rc); return IOUtils.readLines(new ByteArrayInputStream(out.toByteArray())); }
From source file:org.estatio.webapp.services.other.EstatioOtherServices.java
@Programmatic String execute(String command) { int exitValue = 1; CommandLine commandLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0);// ww w.j a v a 2 s. c o m ExecuteStreamHandler handler = executor.getStreamHandler(); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout); executor.setStreamHandler(psh); try { handler.setProcessOutputStream(System.in); } catch (IOException e) { } try { exitValue = executor.execute(commandLine); } catch (ExecuteException e) { return e.getMessage(); } catch (IOException e) { return e.getMessage(); } return stdout.toString(); }
From source file:org.evosuite.utils.ProcessLauncher.java
public int launchNewProcess(File baseDir, String cmdString, int timeout) throws IOException, ProcessTimeoutException { DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog timeoutWatchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(timeoutWatchdog); PumpStreamHandler streamHandler = new PumpStreamHandler(this.outAndErr, this.outAndErr, this.input); executor.setStreamHandler(streamHandler); if (baseDir != null) { executor.setWorkingDirectory(baseDir); }/*from www .ja v a 2 s. c o m*/ int exitValue; try { logger.debug("About to execute command " + cmdString); exitValue = executor.execute(CommandLine.parse(cmdString)); if (executor.isFailure(exitValue) && timeoutWatchdog.killedProcess()) { // it was killed on purpose by the watchdog logger.debug("A timeout occured while executing a process"); logger.debug("The command is " + cmdString); throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString); } return exitValue; } catch (ExecuteException e) { if (timeoutWatchdog.killedProcess()) { logger.debug("A timeout occured while executing a process"); logger.debug("The command is " + cmdString); throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString); } else { throw 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);//from w w w .j a v a 2 s . co m 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.fuin.esmp.EventStorePostStartMojo.java
@Override protected final void executeGoal() throws MojoExecutionException { if (postStartCommand == null) { throw new MojoExecutionException("postStartCommand not set"); }/*from ww w. ja v a 2 s.com*/ LOG.info("postStartCommand={}", postStartCommand); final CommandLine cmdLine = new CommandLine(postStartCommand); final DefaultExecutor executor = new DefaultExecutor(); try { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final PumpStreamHandler psh = new PumpStreamHandler(bos); executor.setStreamHandler(psh); executor.setWorkingDirectory(getEventStoreDir()); final int exitCode = executor.execute(cmdLine); messages = asList(bos.toString()); if (exitCode == 0) { LOG.info("Post-start command executed successfully"); logDebug(messages); } else { LOG.error("Post-start command failed with exit code: {}", exitCode); logError(messages); } } catch (final IOException ex) { throw new MojoExecutionException("Error executing the command line: " + cmdLine, ex); } }
From source file:org.geoserver.importer.transform.AbstractCommandLinePreTransform.java
protected boolean checkAvailable() throws IOException { try {/*from ww w . j a v a 2 s. com*/ CommandLine cmd = new CommandLine(getExecutable()); for (String option : getAvailabilityTestOptions()) { cmd.addArgument(option); } // prepare to run DefaultExecutor executor = new DefaultExecutor(); // grab at least some part of the outputs int limit = 16 * 1024; try (OutputStream os = new BoundedOutputStream(new ByteArrayOutputStream(), limit); OutputStream es = new BoundedOutputStream(new ByteArrayOutputStream(), limit)) { PumpStreamHandler streamHandler = new PumpStreamHandler(os, es); executor.setStreamHandler(streamHandler); int result = executor.execute(cmd); if (result != 0) { LOGGER.log(Level.SEVERE, "Failed to execute command " + cmd.toString() + "\nStandard output is:\n" + os.toString() + "\nStandard error is:\n" + es.toString()); return false; } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Failure to execute command " + cmd.toString(), e); return false; } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Failure to locate executable for class " + this.getClass(), e); return false; } return true; }
From source file:org.geoserver.importer.transform.AbstractCommandLineTransform.java
@Override public void apply(ImportTask task, ImportData data) throws Exception { boolean inline = isInline(); File executable = getExecutable(); File inputFile = getInputFile(data); Map<String, File> substitutions = new HashMap<>(); substitutions.put("input", inputFile); File outputDirectory = null;//from www . ja v a 2s . c o m File outputFile = null; if (!inline) { outputDirectory = getOutputDirectory(data); outputFile = new File(outputDirectory, inputFile.getName()); substitutions.put("output", outputFile); } // setup the options CommandLine cmd = new CommandLine(executable); cmd.setSubstitutionMap(substitutions); setupCommandLine(inline, cmd); // prepare to run DefaultExecutor executor = new DefaultExecutor(); // make sure we don't try to execute for too much time executor.setWatchdog(new ExecuteWatchdog(DEFAULT_TIMEOUT)); // grab at least some part of the outputs int limit = 16 * 1024; try { try (OutputStream os = new BoundedOutputStream(new ByteArrayOutputStream(), limit); OutputStream es = new BoundedOutputStream(new ByteArrayOutputStream(), limit)) { PumpStreamHandler streamHandler = new PumpStreamHandler(os, es); executor.setStreamHandler(streamHandler); try { int result = executor.execute(cmd); if (executor.isFailure(result)) { // toString call is routed to ByteArrayOutputStream, which does the right string // conversion throw new IOException( "Failed to execute command " + cmd.toString() + "\nStandard output is:\n" + os.toString() + "\nStandard error is:\n" + es.toString()); } } catch (Exception e) { throw new IOException("Failure to execute command " + cmd.toString() + "\nStandard output is:\n" + os.toString() + "\nStandard error is:\n" + es.toString(), e); } } // if not inline, replace inputs with output if (!inline) { List<String> names = getReplacementTargetNames(data); File inputParent = inputFile.getParentFile(); for (String name : names) { File output = new File(outputDirectory, name); File input = new File(inputParent, name); if (output.exists()) { // uses atomic rename on *nix, delete and copy on Windows IOUtils.rename(output, input); } else if (input.exists()) { input.delete(); } } } } finally { if (outputDirectory != null) { FileUtils.deleteQuietly(outputDirectory); } } }
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 www . j a v a2 s. c o m*/ 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 w w w .ja v a2 s . c om*/ 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. * /* www. j ava 2 s . c o 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()); } }