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

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

Introduction

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

Prototype

public void setStreamHandler(final ExecuteStreamHandler streamHandler) 

Source Link

Usage

From source file:com.jredrain.base.utils.CommandUtils.java

public static String executeShell(File shellFile, String... args) {
    String info = null;/* ww w . j a  v  a 2s  .co  m*/
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {

        String params = " ";
        if (CommonUtils.notEmpty(args)) {
            for (String p : args) {
                params += p + " ";
            }
        }

        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath() + params);
        DefaultExecutor exec = new DefaultExecutor();
        exec.setExitValues(null);
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputStream);
        exec.setStreamHandler(streamHandler);

        exec.execute(commandLine);
        info = outputStream.toString().trim();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info;
    }
}

From source file:io.selendroid.io.ShellCommand.java

public static void execAsync(String display, CommandLine commandline) throws ShellCommandException {
    log.info("executing async command: " + commandline);
    DefaultExecutor exec = new DefaultExecutor();

    ExecuteResultHandler handler = new DefaultExecuteResultHandler();
    PumpStreamHandler streamHandler = new PumpStreamHandler(new PritingLogOutputStream());
    exec.setStreamHandler(streamHandler);
    try {// w w w. ja va2 s  .c o  m
        if (display == null || display.isEmpty()) {
            exec.execute(commandline, handler);
        } else {
            Map env = EnvironmentUtils.getProcEnvironment();
            EnvironmentUtils.addVariableToEnvironment(env, "DISPLAY=:" + display);

            exec.execute(commandline, env, handler);
        }
    } catch (Exception e) {
        throw new ShellCommandException("An error occured while executing shell command: " + commandline, e);
    }
}

From source file:io.selendroid.standalone.io.ShellCommand.java

public static void execAsync(String display, CommandLine commandline) throws ShellCommandException {
    log.info("executing async command: " + commandline);
    DefaultExecutor exec = new DefaultExecutor();

    ExecuteResultHandler handler = new DefaultExecuteResultHandler();
    PumpStreamHandler streamHandler = new PumpStreamHandler(new PrintingLogOutputStream());
    exec.setStreamHandler(streamHandler);
    try {// w w w  . ja va2 s.c  om
        if (display == null || display.isEmpty()) {
            exec.execute(commandline, handler);
        } else {
            Map env = EnvironmentUtils.getProcEnvironment();
            EnvironmentUtils.addVariableToEnvironment(env, "DISPLAY=:" + display);

            exec.execute(commandline, env, handler);
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error executing command: " + commandline, e);
        throw new ShellCommandException("Error executing shell command: " + commandline, e);
    }
}

From source file:net.robyf.dbpatcher.util.MySqlUtil.java

private static InputStream executeAndGetOutput(final CommandLine commandLine) {
    try {/*w ww  .  j a v a2 s  .c om*/
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        PumpStreamHandler handler = new PumpStreamHandler(outStream);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setWatchdog(new ExecuteWatchdog(300000L));
        executor.setStreamHandler(handler);
        int returnCode = executor.execute(commandLine);
        if (returnCode != 0) {
            throw new UtilException("Error executing: " + commandLine //NOSONAR
                    + ", return code = " + returnCode); //NOSONAR
        }
        return new ByteArrayInputStream(outStream.toByteArray());
    } catch (IOException ioe) {
        throw new UtilException("Error executing: " + commandLine, ioe); //NOSONAR
    }
}

From source file:com.jaeksoft.searchlib.util.ExecuteUtils.java

final public static int command(File workingDirectory, String cmd, String classpath, boolean setJavaTempDir,
        OutputStream outputStream, OutputStream errorStream, Long timeOut, String... arguments)
        throws ExecuteException, IOException {
    Map<String, String> envMap = null;
    if (classpath != null) {
        envMap = new HashMap<String, String>();
        envMap.put("CLASSPATH", classpath);
    }//from ww w.j av  a 2s.c  o m
    CommandLine commandLine = new CommandLine(cmd);
    if (setJavaTempDir)
        if (!StringUtils.isEmpty(SystemUtils.JAVA_IO_TMPDIR))
            commandLine.addArgument(StringUtils.fastConcat("-Djava.io.tmpdir=", SystemUtils.JAVA_IO_TMPDIR),
                    false);
    if (arguments != null)
        for (String argument : arguments)
            commandLine.addArgument(argument);
    DefaultExecutor executor = new DefaultExecutor();
    if (workingDirectory != null)
        executor.setWorkingDirectory(workingDirectory);
    if (outputStream != null) {
        PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, errorStream);
        executor.setStreamHandler(pumpStreamHandler);
    }
    if (timeOut != null) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut);
        executor.setWatchdog(watchdog);
    }
    return envMap != null ? executor.execute(commandLine, envMap) : executor.execute(commandLine);
}

From source file:com.ghgande.j2mod.modbus.utils.TestUtils.java

/**
 * Runs a command line task and returns the screen output or throws and
 * error if something bad happened/*from w w w .ja v a  2s  .  co  m*/
 *
 * @param command Command to run
 *
 * @return Screen output
 *
 * @throws Exception
 */
public static String execToString(String command) throws Exception {

    // Prepare the command line

    CommandLine commandline = CommandLine.parse(command);

    // Prepare the output stream

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);

    // Prepare the executor

    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValues(null);
    exec.setStreamHandler(streamHandler);
    exec.setWatchdog(new ExecuteWatchdog(5000));

    // Execute the command
    try {
        exec.execute(commandline);
        return (outputStream.toString());
    } catch (Exception e) {
        throw new Exception(String.format("%s - %s", outputStream.toString(), e.getMessage()));
    }
}

From source file:eu.learnpad.verification.plugin.pn.modelcheckers.LOLA.java

public static String sync_getVerificationOutput(String lolaBinPath, String modelToVerify,
        String propertyToVerify, boolean useCoverabilitySearch, final int timeoutInSeconds) throws Exception {

    int cores = Runtime.getRuntime().availableProcessors();
    String filePath = System.getProperty("java.io.tmpdir") + "/" + java.util.UUID.randomUUID() + ".lola";
    IOUtils.writeFile(modelToVerify.getBytes(), filePath, false);
    //IOUtils.writeFile(propertyToVerify.getBytes(), filePath+".ctl", false);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = new CommandLine(lolaBinPath);

    cmdLine.addArgument("--nolog");

    //cmdLine.addArgument("--formula="+filePath+".ctl", false);
    cmdLine.addArgument("--formula=" + propertyToVerify, false);
    cmdLine.addArgument("--threads=" + cores);
    if (useCoverabilitySearch)
        cmdLine.addArgument("--search=cover");
    cmdLine.addArgument("-p");
    //cmdLine.addArgument("--path=\""+filePath+".out\"", false);
    //cmdLine.addArgument("--state=\""+filePath+".out\"", false);
    cmdLine.addArgument(filePath, false);

    DefaultExecutor exec = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(1000 * timeoutInSeconds);

    exec.setWatchdog(watchdog);/*from  w  w w.  j av a 2  s  .c o m*/
    exec.setStreamHandler(streamHandler);
    exec.setExitValues(new int[] { 0, 1, 2, 139, 35584 });
    int exitVal = exec.execute(cmdLine);

    String output = outputStream.toString();

    if (watchdog.killedProcess())
        throw new Exception("ERROR: Timeout occurred. LOLA has reached the execution time limit of "
                + timeoutInSeconds + " seconds, so it has been aborted.\nPartial Output:\n" + output);

    if (exitVal != 0 || output.equals("") || output.contains("aborting [#"))
        throw new Exception("ERROR: LOLA internal error\nExit code:" + exitVal + "\nExec: " + cmdLine.toString()
                + "\nOutput:\n" + output);
    new File(filePath).delete();
    return output;
}

From source file:fr.gouv.culture.vitam.utils.Executor.java

/**
 * Execute an external command//from  ww  w .  ja v  a  2 s .  c o  m
 * @param cmd
 * @param tempDelay
 * @param correctValues
 * @param showOutput
 * @param realCommand
 * @return correctValues if ok, < 0 if an execution error occurs, or other error values
 */
public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput,
        String realCommand) {
    // Create command with parameters
    CommandLine commandLine = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        commandLine.addArgument(cmd.get(i));
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    ByteArrayOutputStream outputStream;
    outputStream = new ByteArrayOutputStream();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
    defaultExecutor.setStreamHandler(pumpStreamHandler);

    defaultExecutor.setExitValues(correctValues);
    AtomicBoolean isFinished = new AtomicBoolean(false);
    ExecuteWatchdog watchdog = null;
    Timer timer = null;
    if (tempDelay > 0) {
        // If delay (max time), then setup Watchdog
        timer = new Timer(true);
        watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        defaultExecutor.setWatchdog(watchdog);
        CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand);
        timer.schedule(endOfExecute, tempDelay);
    }
    int status = -1;
    try {
        // Execute the command
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            } catch (IOException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            }
        } else {
            pumpStreamHandler.stop();
            System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                    + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
            status = -2;
            try {
                outputStream.close();
            } catch (IOException e2) {
            }
            return status;
        }
    } catch (IOException e) {
        pumpStreamHandler.stop();
        System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
        status = -2;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
        return status;
    } finally {
        isFinished.set(true);
        if (timer != null) {
            timer.cancel();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e1) {
        }
    }
    pumpStreamHandler.stop();
    if (defaultExecutor.isFailure(status) && watchdog != null) {
        if (watchdog.killedProcess()) {
            // kill by the watchdoc (time out)
            if (showOutput) {
                System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out");
            }
        }
        status = -3;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    } else {
        if (showOutput) {
            System.out.println("Exec: " + outputStream.toString());
        }
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    }
    return status;
}

From source file:com.mooregreatsoftware.gitprocess.lib.Pusher.java

private static ThePushResult doGitProgPush(GitLib gitLib, Branch localBranch, String remoteBranchName,
        boolean forcePush, String remoteName) {
    String cmd = String.format("git push --porcelain %s %s %s:%s", remoteName, forcePush ? "--force" : "",
            localBranch.shortName(), remoteBranchName);
    CommandLine commandLine = CommandLine.parse(cmd);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(gitLib.workingDirectory());
    final StringWriter stdOutWriter = new StringWriter();
    final StringWriter stdErrWriter = new StringWriter();
    executor.setStreamHandler(
            new PumpStreamHandler(new WriterOutputStream(stdOutWriter), new WriterOutputStream(stdErrWriter)));
    final int exitCode = Try.of(() -> {
        try {//from   w ww  .  ja v  a 2 s  .com
            return executor.execute(commandLine);
        } catch (ExecuteException e) {
            return e.getExitValue();
        } catch (IOException e) {
            final String message = e.getMessage();
            if (message != null && message.contains("No such file or directory")) {
                return 1;
            }
            e.printStackTrace();
            return -1;
        }
    }).get();

    return new ProcPushResult(stdOutWriter, stdErrWriter, exitCode);
}

From source file:com.boundlessgeo.wps.grass.GrassProcesses.java

/**
 * Define a GISBASE/LOCATION_NAME for the provided dem.
 *
 * @param operation Name used for the location on disk
 * @param dem File used to establish CRS and Bounds for the location
 * @return//from  ww  w  . j  a v  a 2  s  .c  om
 * @throws Exception
 */
static File location(CoordinateReferenceSystem crs) throws Exception {
    String code = CRS.toSRS(crs, true);
    File geodb = new File(System.getProperty("user.home"), "grassdata");
    File location = Files.createTempDirectory(geodb.toPath(), code).toFile();
    KVP kvp = new KVP("geodb", geodb, "location", location);

    // grass70 + ' -c epsg:' + myepsg + ' -e ' + location_path
    CommandLine cmd = new CommandLine(EXEC);
    cmd.addArgument("-c");
    cmd.addArgument("epsg:" + code);
    cmd.addArgument("-e");
    cmd.addArgument("${location}");
    cmd.setSubstitutionMap(kvp);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWatchdog(new ExecuteWatchdog(60000));
    executor.setStreamHandler(new PumpStreamHandler(System.out));

    int exitValue = executor.execute(cmd);
    return location;
}