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

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

Introduction

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

Prototype

public int execute(final CommandLine command) throws ExecuteException, IOException 

Source Link

Usage

From source file:org.owasp.goatdroid.gui.emulator.EmulatorWorker.java

static public String pushAppOntoDevice(String appPath, String deviceSerial) {

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    CommandLine cmdLine = new CommandLine(sdkPath + getSlash() + "platform-tools" + getSlash() + "adb");
    Map<String, String> map = new HashMap<String, String>();
    map.put("deviceSerial", deviceSerial);
    cmdLine.addArgument("-s", false);
    cmdLine.addArgument("${deviceSerial}", false);
    cmdLine.addArgument("install", false);
    cmdLine.addArgument(appPath, false);
    cmdLine.setSubstitutionMap(map);/*from  w  w  w  .j  a  va2 s  .c o  m*/
    DefaultExecutor executor = new DefaultExecutor();
    try {
        executor.setStreamHandler(psh);
        executor.execute(cmdLine);
        return stdout.toString();
    } catch (ExecuteException e) {
        return Constants.UNEXPECTED_ERROR;
    } catch (IOException e) {
        return Constants.UNEXPECTED_ERROR;
    }
}

From source file:org.rbr8.script_runner.util.BatchScriptRunner.java

public void processFile(File file) throws IOException {

    CommandLine cmdLine = new CommandLine(executable);
    cmdLine.addArguments(arguments);// ww  w. j ava  2s . c o  m

    Map<String, Object> map = new HashMap<>();
    map.put(SubstitutionHelper.FILE, file);
    cmdLine.setSubstitutionMap(map);

    DefaultExecutor executor = new DefaultExecutor();
    //        executor.setExitValue(1);

    //        NotifierLogOutputStream outputLog = new NotifierLogOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(logOutputStream);
    executor.setStreamHandler(psh);

    //        ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    //        executor.setWatchdog(watchdog);
    int exitValue = executor.execute(cmdLine);
}

From source file:org.sakuli.actions.environment.CommandLineUtil.java

static public CommandLineResult runCommand(String command, boolean throwException) throws SakuliException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream error = new ByteArrayOutputStream();
    CommandLineResult result = new CommandLineResult();
    try {/*from ww w. j  a  v a2s.com*/
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(outputStream, error));
        int exitCode = executor.execute(CommandLine.parse(command));
        result.setExitCode(exitCode);
        result.setOutput(error.toString() + outputStream.toString());
    } catch (Exception e) {
        if (throwException) {
            throw new SakuliException(e,
                    String.format("Error during execution of command '%s': %s", command, error.toString()));
        }
        result.setExitCode(resolveExitCode(e.getMessage()));
        result.setOutput(e.getMessage());
    }
    return result;
}

From source file:org.sikuli.natives.CommandExecutorHelper.java

public static CommandExecutorResult execute(String commandString, int expectedExitValue) throws Exception {
    ByteArrayOutputStream error = new ByteArrayOutputStream();
    ByteArrayOutputStream stout = new ByteArrayOutputStream();
    CommandLine cmd = CommandLine.parse(commandString);
    try {/*from  w  ww .  ja  v a 2  s .  c  o m*/
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(expectedExitValue);
        executor.setStreamHandler(new PumpStreamHandler(stout, error));
        //if exit value != expectedExitValue => Exception
        int exitValue = executor.execute(cmd);
        return new CommandExecutorResult(exitValue, stout.toString(), error.toString());

    } catch (Exception e) {
        int exitValue = -1;
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        }
        throw new CommandExecutorException("error in command " + cmd.toString(),
                new CommandExecutorResult(exitValue, stout.toString(), error.toString()));
    }
}

From source file:org.sikuli.natives.LinuxUtil.java

@Override
public void checkLibAvailability() {
    List<CommandLine> commands = Arrays.asList(CommandLine.parse("wmctrl -m"),
            CommandLine.parse("xdotool version"), CommandLine.parse("killall --version"));
    String msg = "";
    for (CommandLine cmd : commands) {
        try {// w  w  w  .ja  v  a  2  s  .c  o m
            DefaultExecutor executor = new DefaultExecutor();
            executor.setExitValue(0);
            //suppress system output
            executor.setStreamHandler(new PumpStreamHandler(null));
            executor.execute(cmd);
        } catch (IOException e) {
            String executable = cmd.toStrings()[0];
            if (executable.equals("wmctrl")) {
                wmctrlAvail = false;
            }
            if (executable.equals("xdotool")) {
                xdoToolAvail = false;
            }
            msg += "command '" + executable + "' is not executable\n";
        }
    }
    if (!msg.isEmpty()) {
        msg += "Please check the availability - some features might not work without!";
        Debug.error(msg);
    }
}

From source file:org.sonar.plugins.ideainspections.IdeaExecutor.java

/**
 * Execute Idea Inspections and return the generated XML report.
 * @return File a directory with the inspection results or null if the project was not found
 *//*from   w w  w.  ja  va  2  s .c om*/
public File execute() {
    if (!project.exists()) {
        LOG.info("Cannot find: " + project + ". Skipping...");
        return null;
    }

    TimeProfiler profiler = new TimeProfiler().start("Execute Idea Inspections " + IdeaVersion.getVersion());

    CommandLine cmdLine = new CommandLine(jdkHome + "/bin/java");

    cmdLine.addArgument("-XX:-UseGCOverheadLimit");
    cmdLine.addArgument("-Xmx" + memory);
    cmdLine.addArgument("-XX:MaxPermSize=" + permSize);
    cmdLine.addArgument("-Xbootclasspath/a:" + bootJar.getPath());

    cmdLine.addArgument("-Djdk." + jdkName + "=" + jdkHome);
    cmdLine.addArgument("-cp");
    cmdLine.addArgument(buildClassPath());
    cmdLine.addArgument(IDEA_MAIN_CLASS_NAME);
    cmdLine.addArgument("inspect");
    cmdLine.addArgument(project.getPath());
    cmdLine.addArgument(profile.getPath());
    cmdLine.addArgument(reportDirectory.getPath());
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);

    //ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    //executor.setWatchdog(watchdog);
    try {
        LOG.info("About to execute: \n" + cmdLine.toString());
        executor.execute(cmdLine);
    } catch (Exception e) {
        throw new SonarException("Can not execute Idea Inspections", e);
    } finally {
        profiler.stop();
    }
    return reportDirectory;
}

From source file:org.sonatype.nexus.yum.internal.task.CommandLineExecutor.java

public int exec(String command) throws IOException {
    LOG.debug("Execute command : {}", command);

    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler());

    int exitValue = executor.execute(cmdLine);
    LOG.debug("Execution finished with exit code : {}", exitValue);
    return exitValue;
}

From source file:org.waarp.commandexec.server.LocalExecServerHandler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    answered = false;//from   ww w .  jav  a 2  s.c  o m
    String request = msg;

    // Generate and write a response.
    String response;
    response = LocalExecDefaultResult.NoStatus.status + " " + LocalExecDefaultResult.NoStatus.result;
    ExecuteWatchdog watchdog = null;
    try {
        if (request.length() == 0) {
            // No command
            response = LocalExecDefaultResult.NoCommand.status + " " + LocalExecDefaultResult.NoCommand.result;
        } else {
            String[] args = request.split(" ");
            int cpt = 0;
            long tempDelay;
            try {
                tempDelay = Long.parseLong(args[0]);
                cpt++;
            } catch (NumberFormatException e) {
                tempDelay = delay;
            }
            if (tempDelay < 0) {
                // Shutdown Order
                isShutdown = true;
                logger.warn("Shutdown order received");
                response = LocalExecDefaultResult.ShutdownOnGoing.status + " "
                        + LocalExecDefaultResult.ShutdownOnGoing.result;
                Thread thread = new GGLEThreadShutdown(factory);
                thread.start();
                return;
            }
            String binary = args[cpt++];
            File exec = new File(binary);
            if (exec.isAbsolute()) {
                // If true file, is it executable
                if (!exec.canExecute()) {
                    logger.error("Exec command is not executable: " + request);
                    response = LocalExecDefaultResult.NotExecutable.status + " "
                            + LocalExecDefaultResult.NotExecutable.result;
                    return;
                }
            }
            // Create command with parameters
            CommandLine commandLine = new CommandLine(binary);
            for (; cpt < args.length; cpt++) {
                commandLine.addArgument(args[cpt]);
            }
            DefaultExecutor defaultExecutor = new DefaultExecutor();
            ByteArrayOutputStream outputStream;
            outputStream = new ByteArrayOutputStream();
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
            defaultExecutor.setStreamHandler(pumpStreamHandler);
            int[] correctValues = { 0, 1 };
            defaultExecutor.setExitValues(correctValues);
            if (tempDelay > 0) {
                // If delay (max time), then setup Watchdog
                watchdog = new ExecuteWatchdog(tempDelay);
                defaultExecutor.setWatchdog(watchdog);
            }
            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(LocalExecDefaultResult.RETRYINMS);
                    } catch (InterruptedException e1) {
                    }
                    try {
                        status = defaultExecutor.execute(commandLine);
                    } catch (ExecuteException e1) {
                        try {
                            pumpStreamHandler.stop();
                        } catch (IOException e3) {
                        }
                        logger.error("Exception: " + e.getMessage() + " Exec in error with "
                                + commandLine.toString());
                        response = LocalExecDefaultResult.BadExecution.status + " "
                                + LocalExecDefaultResult.BadExecution.result;
                        try {
                            outputStream.close();
                        } catch (IOException e2) {
                        }
                        return;
                    } catch (IOException e1) {
                        try {
                            pumpStreamHandler.stop();
                        } catch (IOException e3) {
                        }
                        logger.error("Exception: " + e.getMessage() + " Exec in error with "
                                + commandLine.toString());
                        response = LocalExecDefaultResult.BadExecution.status + " "
                                + LocalExecDefaultResult.BadExecution.result;
                        try {
                            outputStream.close();
                        } catch (IOException e2) {
                        }
                        return;
                    }
                } else {
                    try {
                        pumpStreamHandler.stop();
                    } catch (IOException e3) {
                    }
                    logger.error(
                            "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
                    response = LocalExecDefaultResult.BadExecution.status + " "
                            + LocalExecDefaultResult.BadExecution.result;
                    try {
                        outputStream.close();
                    } catch (IOException e2) {
                    }
                    return;
                }
            } catch (IOException e) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e3) {
                }
                logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
                response = LocalExecDefaultResult.BadExecution.status + " "
                        + LocalExecDefaultResult.BadExecution.result;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return;
            }
            try {
                pumpStreamHandler.stop();
            } catch (IOException e3) {
            }
            if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) {
                // kill by the watchdoc (time out)
                logger.error("Exec is in Time Out");
                response = LocalExecDefaultResult.TimeOutExecution.status + " "
                        + LocalExecDefaultResult.TimeOutExecution.result;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
            } else {
                try {
                    response = status + " " + outputStream.toString(WaarpStringUtils.UTF8.name());
                } catch (UnsupportedEncodingException e) {
                    response = status + " " + outputStream.toString();
                }
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
            }
        }
    } finally {
        // We do not need to write a ByteBuf here.
        // We know the encoder inserted at LocalExecInitializer will do the
        // conversion.
        ctx.channel().writeAndFlush(response + "\n");
        answered = true;
        if (watchdog != null) {
            watchdog.stop();
        }
        logger.info("End of Command: " + request + " : " + response);
        ctx.channel().writeAndFlush(LocalExecDefaultResult.ENDOFCOMMAND + "\n");
    }
}

From source file:org.waarp.gateway.kernel.exec.ExecuteExecutor.java

public void run() throws Reply421Exception {
    // Check if the execution will be done through LocalExec daemon
    if (AbstractExecutor.useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(arg, delay, futureCompletion);
            localExecClient.disconnect();
            return;
        } // else continue
    }//from  w ww  . j  ava2  s.co  m
    // Execution is done internally
    File exec = new File(args[0]);
    if (exec.isAbsolute()) {
        if (!exec.canExecute()) {
            logger.error("Exec command is not executable: " + args[0]);
            throw new Reply421Exception("Pre Exec command is not executable");
        }
    }
    CommandLine commandLine = new CommandLine(args[0]);
    for (int i = 1; i < args.length; i++) {
        commandLine.addArgument(args[i]);
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null);
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    int[] correctValues = { 0, 1 };
    defaultExecutor.setExitValues(correctValues);
    ExecuteWatchdog watchdog = null;
    if (delay > 0) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    int status = -1;
    try {
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(10);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e2) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e1) {
                }
                logger.error("System Exception: " + e.getMessage() + "\n    Exec cannot execute command "
                        + commandLine.toString());
                throw new Reply421Exception("Cannot execute Pre command");
            } catch (IOException e2) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e1) {
                }
                logger.error(
                        "Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
                throw new Reply421Exception("Cannot execute Pre command");
            }
            logger.info("System Exception: " + e.getMessage() + " but finally get the command executed "
                    + commandLine.toString());
        } else {
            try {
                pumpStreamHandler.stop();
            } catch (IOException e1) {
            }
            logger.error("Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
            throw new Reply421Exception("Cannot execute Pre command");
        }
    } catch (IOException e) {
        try {
            pumpStreamHandler.stop();
        } catch (IOException e1) {
        }
        logger.error("Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
        throw new Reply421Exception("Cannot execute Pre command");
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e1) {
    }
    if (watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        logger.error("Exec is in Time Out");
        status = -1;
    }
    if (status == 0) {
        futureCompletion.setSuccess();
        logger.info("Exec OK with {}", commandLine);
    } else if (status == 1) {
        logger.warn("Exec in warning with {}", commandLine);
        futureCompletion.setSuccess();
    } else {
        logger.debug("Status: " + status + (status == -1 ? " Tiemout" : "") + " Exec in error with "
                + commandLine.toString());
        throw new Reply421Exception("Pre command executed in error");
    }
}

From source file:org.waarp.openr66.context.task.ExecMoveTask.java

@Override
public void run() {
    /*//from  w ww.j av a 2s.  co m
     * First apply all replacements and format to argRule from context and argTransfer. Will
     * call exec (from first element of resulting string) with arguments as the following value
     * from the replacements. Return 0 if OK, else 1 for a warning else as an error. The last
     * line of stdout will be the new name given to the R66File in case of status 0. The
     * previous file should be deleted by the script or will be deleted in case of status 0. If
     * the status is 1, no change is made to the file.
     */
    logger.info("ExecMove with " + argRule + ":" + argTransfer + " and {}", session);
    String finalname = argRule;
    finalname = getReplacedValue(finalname, argTransfer.split(" "));
    // Force the WaitForValidation
    waitForValidation = true;
    if (Configuration.configuration.isUseLocalExec() && useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion);
            LocalExecResult result = localExecClient.getLocalExecResult();
            move(result.getStatus(), result.getResult(), finalname);
            localExecClient.disconnect();
            return;
        } // else continue
    }
    String[] args = finalname.split(" ");
    File exec = new File(args[0]);
    if (exec.isAbsolute()) {
        if (!exec.canExecute()) {
            logger.error("Exec command is not executable: " + finalname);
            R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner());
            futureCompletion.setResult(result);
            futureCompletion.cancel();
            return;
        }
    }
    CommandLine commandLine = new CommandLine(args[0]);
    for (int i = 1; i < args.length; i++) {
        commandLine.addArgument(args[i]);
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    PipedInputStream inputStream = new PipedInputStream();
    PipedOutputStream outputStream = null;
    try {
        outputStream = new PipedOutputStream(inputStream);
    } catch (IOException e1) {
        try {
            inputStream.close();
        } catch (IOException e) {
        }
        logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1);
        futureCompletion.setFailure(e1);
        return;
    }
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null);
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    int[] correctValues = { 0, 1 };
    defaultExecutor.setExitValues(correctValues);
    ExecuteWatchdog watchdog = null;

    if (delay > 0) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    LastLineReader lastLineReader = new LastLineReader(inputStream);
    Thread thread = new Thread(lastLineReader, "ExecRename" + session.getRunner().getSpecialId());
    thread.setDaemon(true);
    Configuration.configuration.getExecutorService().execute(thread);
    int status = -1;
    try {
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(Configuration.RETRYINMS);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                thread.interrupt();
                try {
                    inputStream.close();
                } catch (IOException e2) {
                }
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error("ExecuteException: " + e.getMessage() + " . Exec in error with "
                        + commandLine.toString());
                futureCompletion.setFailure(e);
                return;
            } catch (IOException e1) {
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                thread.interrupt();
                try {
                    inputStream.close();
                } catch (IOException e2) {
                }
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error(
                        "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
                futureCompletion.setFailure(e);
                return;
            }
        } else {
            try {
                outputStream.close();
            } catch (IOException e1) {
            }
            thread.interrupt();
            try {
                inputStream.close();
            } catch (IOException e1) {
            }
            try {
                pumpStreamHandler.stop();
            } catch (IOException e2) {
            }
            logger.error(
                    "ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
            futureCompletion.setFailure(e);
            return;
        }
    } catch (IOException e) {
        try {
            outputStream.close();
        } catch (IOException e1) {
        }
        thread.interrupt();
        try {
            inputStream.close();
        } catch (IOException e1) {
        }
        try {
            pumpStreamHandler.stop();
        } catch (IOException e2) {
        }
        logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
        futureCompletion.setFailure(e);
        return;
    }
    try {
        outputStream.flush();
    } catch (IOException e) {
    }
    try {
        outputStream.close();
    } catch (IOException e) {
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e2) {
    }
    try {
        if (delay > 0) {
            thread.join(delay);
        } else {
            thread.join();
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    try {
        inputStream.close();
    } catch (IOException e1) {
    }
    String newname = null;
    if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        status = -1;
        newname = "TimeOut";
    } else {
        newname = lastLineReader.getLastLine();
        if (status == 0 && (newname == null || newname.isEmpty())) {
            status = 1;
        }
    }
    move(status, newname, commandLine.toString());
}