Example usage for org.apache.commons.exec Executor setStreamHandler

List of usage examples for org.apache.commons.exec Executor setStreamHandler

Introduction

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

Prototype

void setStreamHandler(ExecuteStreamHandler streamHandler);

Source Link

Document

Set a custom the StreamHandler used for providing input and retrieving the output.

Usage

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

/**
 * Executes the ImageMagick command using Apache Commons Exec.
 *
 * @param commandLine//from www  .  jav a2s .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
            * 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/*from  w  w  w  . j  a  v  a2 s .com*/
 *            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.kualigan.maven.plugins.api.DefaultPrototypeHelper.java

protected int executeCommandLine(final String... args) throws ExecuteException, IOException {
    final Executor exec = new DefaultExecutor();
    final Map enviro = new HashMap();
    try {// www.j  a v a  2s .  c o  m
        final Properties systemEnvVars = CommandLineUtils.getSystemEnvVars();
        enviro.putAll(systemEnvVars);
    } catch (IOException x) {
        getCaller().getLog().error("Could not assign default system enviroment variables.", x);
    }

    final File workingDirectory = new File(System.getProperty("java.io.tmpdir"));
    final org.apache.commons.exec.CommandLine commandLine = new org.apache.commons.exec.CommandLine(args[0]);
    for (int i = 1; i < args.length; i++) {
        commandLine.addArgument(args[i]);
    }

    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in));
    exec.setWorkingDirectory(workingDirectory);
    return exec.execute(commandLine, enviro);
}

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

public static String getVersion() {

    try {/*from w  w w  .ja  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.");
    }/* www  .  j  a v a2 s  .  c  o  m*/

    // 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 String getVersion() {
    try {/*from   w w  w  . j a  v  a2 s  .  c  o 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

private Executor buildExecutor() {
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(streamHandler);
    setTimeoutWatchdog(executor);//from   w w w . j  a v  a  2 s . c  om
    return executor;
}

From source file:org.openflamingo.core.cmd.CommandLineExecutor.java

/**
 *  ??? ./*ww  w.  j av  a2  s. c om*/
 *
 * @param args  ??    ?? ?
 * @throws java.io.IOException   ??  
 * @throws InterruptedException  ??    
 */
public static void main(String[] args) throws IOException, InterruptedException {
    CommandLine cmdLine = new CommandLine("/bin/ls");
    cmdLine.addArgument("-lsa");
    cmdLine.addArgument("/");
    /*
            cmdLine.addArgument("/p");
          cmdLine.addArgument("/h");
          cmdLine.addArgument("${file}");
            
          HashMap map = new HashMap();
          map.put("file", new File("invoice.pdf"));
            
          cmdLine.setSubstitutionMap(map);
    */

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    TailExecuteResultHandler resultHandler = new TailExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(500);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);

    TailPumpStreamHandler psh = new TailPumpStreamHandler(out);
    executor.setStreamHandler(psh);
    executor.execute(cmdLine, resultHandler);

    System.out.println(out.toString());

    resultHandler.waitFor();
}

From source file:org.openflamingo.engine.util.FileReader.java

/**
 * ? ??  ??  ? ? .//from  w w  w  . java2  s  . co m
 *
 * @param start     ??
 * @param end       ??
 * @param filename ?? ?
 * @return ?? 
 * @throws IOException          ?? ??   
 * @throws InterruptedException       
 */
public static String read(long start, long end, String filename) throws IOException, InterruptedException {
    String command = org.slf4j.helpers.MessageFormatter
            .arrayFormat("sed '{},{}!d' {}", new Object[] { start, end, filename }).getMessage();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(out);

    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(pumpStreamHandler);
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    return new String(out.toByteArray());
}

From source file:org.openflamingo.engine.util.FileReader.java

/**
 * ? ?? ??  ? ./*from   ww w  .ja  v a 2  s.  c  o m*/
 *
 * @param filename ??  ? ?
 * @return  ?? ?? 
 * @throws IOException          ?? ??   
 * @throws InterruptedException       
 */
public static int lines(String filename) throws IOException, InterruptedException {
    String command = org.slf4j.helpers.MessageFormatter.arrayFormat("sed -n '$=' {}", new Object[] { filename })
            .getMessage();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(out);

    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(pumpStreamHandler);
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    return Integer.parseInt(new String(out.toByteArray()).trim());
}