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

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

Introduction

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

Prototype

public DefaultExecutor() 

Source Link

Document

Default constructor creating a default PumpStreamHandler and sets the working directory of the subprocess to the current working directory.

Usage

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

/**
 * Execute an external command/* w  w w.  j  a 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.k42b3.aletheia.filter.request.Process.java

public void exec(Request request) {
    String cmd = getConfig().getProperty("cmd");

    try {// ww w.ja  v a 2 s.c o  m
        logger.info("Execute: " + cmd);

        CommandLine commandLine = CommandLine.parse(cmd);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        DefaultExecutor executor = new DefaultExecutor();

        this.baos = new ByteArrayOutputStream();
        this.baosErr = new ByteArrayOutputStream();
        this.bais = new ByteArrayInputStream(request.getContent().getBytes());

        executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr, this.bais));
        executor.setWatchdog(watchdog);
        executor.execute(commandLine);

        logger.info("Output: " + this.baos.toString());

        request.setContent(this.baos.toString());
    } catch (Exception e) {
        logger.warning(e.getMessage());
    }
}

From source file:de.woq.osgi.java.itestsupport.ContainerRunner.java

public ContainerRunner(String profile) throws Exception {
    this.profile = profile;

    executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(new ContainerOutputStream(), System.err));
    watchdog = new ExecuteWatchdog(-1);

    executor.setWatchdog(watchdog);//from w ww. ja v  a2s .co m
}

From source file:com.zxy.commons.exec.CmdExecutor.java

/**
 * //w  ww.  ja  va  2  s.c  om
 * 
 * @param workHome workHome
 * @param command command
 * @return ???
 * @throws InterruptedException InterruptedException
 * @throws IOException IOException
 */
public static ExecutorResult exec(String workHome, String command) throws InterruptedException, IOException {
    CommandLine cmdLine = CommandLine.parse(PRE_CMD + command);
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File(workHome));

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
    executor.setStreamHandler(streamHandler);

    int code = executor.execute(cmdLine, EnvironmentUtils.getProcEnvironment());
    String successMsg = outputStream.toString(ENCODING);
    String errorMsg = errorStream.toString(ENCODING);
    return new ExecutorResult(code, successMsg, errorMsg);
}

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);//  ww  w .  j a v  a 2 s  .com
    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:eu.creatingfuture.propeller.webLoader.propeller.OpenSpin.java

/**
 * https://code.google.com/p/open-source-spin-compiler/wiki/CommandLine
 *
 * @param executable/*from   www  .j a va  2 s  .  c  o m*/
 * @param sourceFile
 * @return
 */
protected boolean compile(String executable, File sourceFile) {
    try {
        File temporaryDestinationFile = File.createTempFile("blocklyapp", ".binary");
        File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-lib");
        Map map = new HashMap();
        map.put("sourceFile", sourceFile);
        map.put("destinationFile", temporaryDestinationFile);
        map.put("libDirectory", libDirectory);

        CommandLine cmdLine = new CommandLine(executable);
        cmdLine.addArgument("-o").addArgument("${destinationFile}");
        cmdLine.addArgument("-L").addArgument("${libDirectory}");
        cmdLine.addArgument("${sourceFile}");
        cmdLine.setSubstitutionMap(map);
        DefaultExecutor executor = new DefaultExecutor();
        //  executor.setExitValues(new int[]{402, 101});

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        try {
            exitValue = executor.execute(cmdLine);
        } catch (ExecuteException ee) {
            exitValue = ee.getExitValue();
            logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue);
            success = false;
            return false;
        } finally {
            temporaryDestinationFile.delete();
            output = outputStream.toString();
        }

        //            System.out.println("output: " + output);
        /*
         Scanner scanner = new Scanner(output);
                
                
         Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?");
         Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$");
         while (scanner.hasNextLine()) {
         String portLine = scanner.nextLine();
         if (chipFoundPattern.matcher(portLine).matches()) {
         Matcher portMatch = pattern.matcher(portLine);
         if (portMatch.find()) {
         //   String port = portMatch.group("comport");
                
         }
         }
         }
         */
        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}

From source file:eu.creatingfuture.propeller.blocklyprop.propeller.OpenSpin.java

/**
 * https://code.google.com/p/open-source-spin-compiler/wiki/CommandLine
 *
 * @param executable/*from  w w w  .j a  v  a  2 s.c  om*/
 * @param sourceFile
 * @return
 */
protected boolean compile(String executable, File sourceFile) {
    try {
        File temporaryDestinationFile = File.createTempFile("blocklyapp", ".binary");
        File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-lib");
        Map map = new HashMap();
        map.put("sourceFile", sourceFile);
        map.put("destinationFile", temporaryDestinationFile);
        map.put("libDirectory", libDirectory);

        CommandLine cmdLine = new CommandLine(executable);
        cmdLine.addArgument("-o").addArgument("${destinationFile}");
        cmdLine.addArgument("-L").addArgument("${libDirectory}");
        cmdLine.addArgument("${sourceFile}");
        cmdLine.setSubstitutionMap(map);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValues(new int[] { 0, 1 });

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        try {
            exitValue = executor.execute(cmdLine);
        } catch (ExecuteException ee) {
            exitValue = ee.getExitValue();
            logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue);
            success = false;
            return false;
        } finally {
            temporaryDestinationFile.delete();
            output = outputStream.toString();
        }

        //            System.out.println("output: " + output);
        /*
         Scanner scanner = new Scanner(output);
                
                
         Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?");
         Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$");
         while (scanner.hasNextLine()) {
         String portLine = scanner.nextLine();
         if (chipFoundPattern.matcher(portLine).matches()) {
         Matcher portMatch = pattern.matcher(portLine);
         if (portMatch.find()) {
         //   String port = portMatch.group("comport");
                
         }
         }
         }
         */
        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}

From source file:com.abiquo.nodecollector.service.impl.StonithServiceImpl.java

protected boolean executeCommand(final CommandLine command) {
    try {//from   w w w.j  a  v  a2s.  c o m
        LOGGER.debug(String.format("Executing '%s'", command.toString()));

        DefaultExecutor executor = new DefaultExecutor();

        return executor.execute(command) == 0;
    } catch (Exception e) {
        LOGGER.error(String.format("While executing '%s'", command.toString()), e);
        return false;
    }
}

From source file:com.creactiviti.piper.core.taskhandler.script.Bash.java

@Override
public String handle(Task aTask) throws Exception {
    File scriptFile = File.createTempFile("_script", ".sh");
    File logFile = File.createTempFile("log", null);
    FileUtils.writeStringToFile(scriptFile, aTask.getRequiredString("script"));
    try (PrintStream stream = new PrintStream(logFile);) {
        Process chmod = Runtime.getRuntime().exec(String.format("chmod u+x %s", scriptFile.getAbsolutePath()));
        int chmodRetCode = chmod.waitFor();
        if (chmodRetCode != 0) {
            throw new ExecuteException("Failed to chmod", chmodRetCode);
        }//from   ww w  .j a  v a2  s. c om
        CommandLine cmd = new CommandLine(scriptFile.getAbsolutePath());
        logger.debug("{}", cmd);
        DefaultExecutor exec = new DefaultExecutor();
        exec.setStreamHandler(new PumpStreamHandler(stream));
        exec.execute(cmd);
        return FileUtils.readFileToString(logFile);
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(logFile)));
    } finally {
        FileUtils.deleteQuietly(logFile);
        FileUtils.deleteQuietly(scriptFile);
    }
}

From source file:com.tribuneqa.utilities.FrameworkUtilities.java

public static void appiumStop() throws IOException {
    // Add different arguments In command line which requires to stop appium server. 
    CommandLine command = new CommandLine("cmd");
    command.addArgument("/c");
    command.addArgument("taskkill");
    command.addArgument("/F");
    command.addArgument("/IM");
    command.addArgument("node.exe");

    // Execute command line arguments to stop appium server. 
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(1);/* www  . ja va  2 s  .c om*/
    executor.execute(command, resultHandler);
}