Example usage for org.apache.commons.exec PumpStreamHandler PumpStreamHandler

List of usage examples for org.apache.commons.exec PumpStreamHandler PumpStreamHandler

Introduction

In this page you can find the example usage for org.apache.commons.exec PumpStreamHandler PumpStreamHandler.

Prototype

public PumpStreamHandler(final OutputStream outAndErr) 

Source Link

Document

Construct a new PumpStreamHandler.

Usage

From source file:org.kitodo.imagemanagement.ConvertRunner.java

/**
 * Executes the ImageMagick command using Apache Commons Exec.
 *
 * @param commandLine/*from   w  ww. ja  v  a2 s .  co m*/
 *            command line to execute
 * @throws IOException
 *             if I/O fails
 */
void run(IMOperation commandLine) throws IOException {
    Executor executor = new DefaultExecutor();

    OutputStream outAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outAndErr));

    long timeoutMillis = 1000
            * KitodoConfig.getIntParameter(ParameterImageManagement.TIMEOUT_SEC, DEFAULT_TIMEOUT_MINS);
    executor.setWatchdog(new ExecuteWatchdog(timeoutMillis));

    CommandLine command;
    try {
        String sshHosts = KitodoConfig.getParameter(ParameterImageManagement.SSH_HOST);
        command = new CommandLine("ssh");
        String[] hosts = sshHosts.split(",");
        String host = hosts[RANDOMNESS_GENERATOR.nextInt(hosts.length)];
        command.addArgument(host, false);
        command.addArgument(convertCommand + ' ' + commandLine.toString(), false);
    } catch (NoSuchElementException e) {
        logger.trace("SSH not configured.", e);
        command = new CommandLine(convertCommand);
        command.addArguments(commandLine.toString());
    }

    try {
        logger.debug("Executing: {}", command);
        logger.trace("Timeout: {} mins", timeoutMillis / 60000d);
        executor.execute(command);
        logger.debug("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
    } catch (IOException | RuntimeException e) {
        logger.error("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
        throw e;
    }
}

From source file:org.kitodo.imagemanagementmodule.ConvertRunner.java

/**
 * Executes the ImageMagick command using Apache Commons Exec.
 *
 * @param commandLine//  www  .j a  v a 2 s .c  o m
 *            command line to execute
 * @throws IOException
 *             if I/O fails
 */
void run(IMOperation commandLine) throws IOException {
    Executor executor = new DefaultExecutor();

    OutputStream outAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outAndErr));

    long timeoutMillis = 1000
            * Config.getIntParameter("ImageManagementModule.timeoutSec", DEFAULT_TIMEOUT_MINS);
    executor.setWatchdog(new ExecuteWatchdog(timeoutMillis));

    CommandLine command;
    try {
        String sshHosts = Config.getParameter("ImageManagementModule.sshHosts");
        command = new CommandLine("ssh");
        String[] hosts = sshHosts.split(",");
        String host = hosts[RANDOMNESS_GENERATOR.nextInt(hosts.length)];
        command.addArgument(host, false);
        command.addArgument(convertCommand + ' ' + commandLine.toString(), false);
    } catch (NoSuchElementException e) {
        logger.trace("SSH not configured.", e);
        command = new CommandLine(convertCommand);
        command.addArguments(commandLine.toString());
    }

    try {
        logger.debug("Executing: {}", command);
        logger.trace("Timeout: {} mins", timeoutMillis / 60000d);
        executor.execute(command);
        logger.debug("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
    } catch (IOException | RuntimeException e) {
        logger.error("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
        throw e;
    }
}

From source file:org.mail.bridge.FolderMonitor.java

public synchronized void runScriptAgainstReceivedFiles(List<File> inboxFiles) {
    if (config.getInboxScript().isEmpty() || Utils.isEmpty(inboxFiles))
        return;/*from  w w  w. j a v  a2 s . c  o m*/
    LOG.debug("Run script '{}' against files {}", config.getInboxScript(), inboxFiles);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        CommandLine cmd = CommandLine.parse(config.getInboxScript());
        for (File file : inboxFiles)
            cmd.addArgument(file.getName(), true);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out));
        executor.setWatchdog(new ExecuteWatchdog(SCRIPT_TIMEOUT));
        Map<String, String> environment = EnvironmentUtils.getProcEnvironment();
        environment.putAll(config.asEnvironmentMap());
        executor.setWorkingDirectory(new File(System.getProperty("user.dir")));
        executor.execute(cmd, environment);
        LOG.info("Script '{}' successfully finished", config.getInboxScript());
        LOG.debug("Script output:\n{}", out.toString());
    } catch (ExecuteException e) {
        LOG.error(e.getMessage(), e);
        LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString());
        int c = config.getInboxScriptStopCode();
        if (c != 0 && c == e.getExitValue())
            postMessage(new Main.StopMessage(
                    String.format("Script '%s' exited with code %d that is configured as stop code",
                            config.getInboxScript(), c)));
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString());
    }
}

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  w w  . j  av  a2 s  .  c om*/
    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.mule.test.infrastructure.process.UnixController.java

@Override
public int getProcessId() {
    Map<Object, Object> newEnv = this.copyEnvironmentVariables();
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);//from   w w  w. j  a  v a  2  s.co m
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    if (this.doExecution(executor, new CommandLine(this.muleBin).addArgument("status"), newEnv) == 0) {
        Matcher matcher = STATUS_PATTERN.matcher(outputStream.toString());
        if (matcher.find()) {
            return Integer.parseInt(matcher.group(1));
        } else {
            throw new MuleControllerException("bin/mule status didn't return the expected pattern: " + STATUS);
        }
    } else {
        throw new MuleControllerException("Mule ESB is not running");
    }
}

From source file:org.n52.movingcode.runtime.processors.python.PythonCLIProbe.java

public static String getVersion() {

    try {/* w  ww.ja v  a 2  s .  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.r.RCLIProbe.java

private static String getVersion() {
    try {//from   ww w. j  a  v a  2 s.c om
        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.ng200.openolympus.cerberus.executors.OpenOlympusWatchdogExecutor.java

private static String callNativeId(boolean group) throws IOException {
    OpenOlympusWatchdogExecutor.ensureUserAndGroupExists();

    final CommandLine commandLine = new CommandLine("id");
    commandLine.addArgument(group ? "-g" : "-u");
    commandLine.addArgument("olympuswatchdogchild");

    final DefaultExecutor executor = new DefaultExecutor();

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    executor.setStreamHandler(new PumpStreamHandler(out));

    executor.setWatchdog(new ExecuteWatchdog(1000));

    try {//from  w w  w  .  j a v a2 s .  c om
        executor.execute(commandLine);

        return out.toString(StandardCharsets.UTF_8.name());
    } catch (final ExecuteException e) {
        throw new ExecuteException(
                "Couldn't find user/group id of the olympuswatchdogchild user/group: does it even exist?",
                e.getExitValue(), e);
    }
}

From source file:org.ng200.openolympus.controller.admin.DiagnosticsController.java

private File which(final String applicationName) {
    try {/*from   ww  w  .j a  v  a  2  s  .  c o m*/
        final DefaultExecutor executor = new DefaultExecutor();
        executor.setWatchdog(new ExecuteWatchdog(20000));
        final CommandLine commandLine = new CommandLine("which");
        commandLine.addArgument(applicationName);
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        executor.setStreamHandler(new PumpStreamHandler(byteArrayOutputStream));
        executor.execute(commandLine);
        final String fileName = byteArrayOutputStream.toString().trim();
        if (fileName.isEmpty()) {
            return null;
        }
        return new File(fileName);
    } catch (final IOException e) {
        return null;
    }
}

From source file:org.ng200.openolympus.FileAccess.java

public static void rsync(final Path from, final Path to) throws IOException {
    final CommandLine commandLine = new CommandLine("/usr/bin/rsync");
    commandLine.addArgument("-r");
    commandLine.addArgument("--ignore-errors");
    commandLine.addArgument(from.toAbsolutePath().toString());
    commandLine.addArgument(to.toAbsolutePath().toString());
    final DefaultExecutor executor = new DefaultExecutor();

    executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the
    // sandbox to
    // complete/* ww  w  .  jav  a  2  s .co  m*/
    final ByteArrayOutputStream outAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outAndErr));
    executor.setExitValues(new int[] { 0 });
    try {
        executor.execute(commandLine);
    } catch (final ExecuteException e) {
        throw new IOException("Rsync failed:\n" + outAndErr.toString(), e);
    }
}