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 void execute(final CommandLine command, final ExecuteResultHandler handler)
        throws ExecuteException, IOException 

Source Link

Usage

From source file:com.jredrain.startup.AgentProcessor.java

@Override
public Response execute(final Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }//from www  .j a  v  a 2 s.c  o m

    String command = request.getParams().get("command") + EXITCODE_SCRIPT;

    String pid = request.getParams().get("pid");
    //??
    Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L);

    boolean timeoutFlag = timeout > 0;

    logger.info("[redrain]:execute:{},pid:{}", command, pid);

    File shellFile = CommandUtils.createShellFile(command, pid);

    Integer exitValue;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    final Response response = Response.response(request);

    final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE);

    final Timer timer = new Timer();

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath());
        final DefaultExecutor executor = new DefaultExecutor();

        ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream);
        executor.setStreamHandler(stream);
        response.setStartTime(new Date().getTime());
        //?0,shell
        executor.setExitValue(0);

        if (timeoutFlag) {
            //...
            executor.setWatchdog(watchdog);
            //
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //,kill...
                    if (watchdog.isWatching()) {
                        /**
                         * watchdogdestroyProcesskill...
                         * watchdog.destroyProcess();
                         */
                        timer.cancel();
                        watchdog.stop();
                        //call  kill...
                        request.setAction(Action.KILL);
                        try {
                            kill(request);
                            response.setExitCode(RedRain.StatusCode.TIME_OUT.getValue());
                        } catch (TException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }, timeout * 60 * 1000);

            //
            resultHandler = new DefaultExecuteResultHandler() {
                @Override
                public void onProcessComplete(int exitValue) {
                    super.onProcessComplete(exitValue);
                    timer.cancel();
                }

                @Override
                public void onProcessFailed(ExecuteException e) {
                    super.onProcessFailed(e);
                    timer.cancel();
                }
            };
        }

        executor.execute(commandLine, resultHandler);

        resultHandler.waitFor();

    } catch (Exception e) {
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        } else {
            exitValue = RedRain.StatusCode.ERROR_EXEC.getValue();
        }
        if (RedRain.StatusCode.KILL.getValue().equals(exitValue)) {
            if (timeoutFlag) {
                timer.cancel();
                watchdog.stop();
            }
            logger.info("[redrain]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[redrain]:job execute error:{}", e.getCause().getMessage());
        }
    } finally {

        exitValue = resultHandler.getExitValue();

        if (CommonUtils.notEmpty(outputStream.toByteArray())) {
            try {
                outputStream.flush();
                String text = outputStream.toString();
                if (notEmpty(text)) {
                    try {
                        text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), "");
                        response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY)));
                        exitValue = Integer.parseInt(text
                                .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim());
                    } catch (IndexOutOfBoundsException e) {
                        response.setMessage(text);
                    }
                }
                outputStream.close();
            } catch (Exception e) {
                logger.error("[redrain]:error:{}", e);
            }
        }

        if (RedRain.StatusCode.TIME_OUT.getValue() == response.getExitCode()) {
            response.setSuccess(false).end();
        } else {
            response.setExitCode(exitValue)
                    .setSuccess(response.getExitCode() == RedRain.StatusCode.SUCCESS_EXIT.getValue()).end();
        }

        if (shellFile != null) {
            shellFile.delete();//
        }
    }
    logger.info("[redrain]:execute result:{}", response.toString());
    watchdog.stop();

    return response;
}

From source file:net.test.aliyun.z7.Zip7Object.java

public static int extract(final String extToosHome, final String extractFile, final String toDir)
        throws Throwable {
    String cmdLine = String.format("%s\\7z.exe x \"%s\" -aoa -y \"-o%s\"", extToosHome, extractFile, toDir);
    CommandLine commandline = CommandLine.parse(cmdLine);
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    DefaultExecutor executor = new DefaultExecutor();
    int extValue = -1;
    try {//from  w ww.j a  v  a 2  s . c o  m
        executor.execute(commandline, resultHandler);
        resultHandler.waitFor(300 * 1000);
        extValue = resultHandler.getExitValue();
        if (extValue == 0) {
            new File(extractFile).delete();
        }
    } catch (Exception e) {
        //
    } finally {
        if (extValue != 0) {
            FileUtils.deleteDir(new File(toDir));
            return extValue;
        }
    }
    //
    Iterator<File> itFile = FileUtils.iterateFiles(new File(toDir), FileFilterUtils.fileFileFilter(),
            FileFilterUtils.directoryFileFilter());
    while (itFile.hasNext()) {
        File it = itFile.next();
        if (it.isDirectory())
            continue;
        for (String com : compression) {
            if (StringUtils.endsWithIgnoreCase(it.getName(), com)) {
                String itPath = it.getAbsolutePath();
                String subToDir = itPath.substring(0, itPath.length() - com.length());
                extract(extToosHome, itPath, subToDir);
            }
        }
    }
    return 0;
}

From source file:org.apache.hcatalog.templeton.ExecServiceImpl.java

private ExecBean auxRun(String program, List<String> args, Map<String, String> env)
        throws NotAuthorizedException, ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);//from   w  w w.  j a  v  a2s . co m

    // Setup stdout and stderr
    int nbytes = appConf.getInt(AppConfig.EXEC_MAX_BYTES_NAME, -1);
    ByteArrayOutputStream outStream = new MaxByteArrayOutputStream(nbytes);
    ByteArrayOutputStream errStream = new MaxByteArrayOutputStream(nbytes);
    executor.setStreamHandler(new PumpStreamHandler(outStream, errStream));

    // Only run for N milliseconds
    int timeout = appConf.getInt(AppConfig.EXEC_TIMEOUT_NAME, 0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);

    CommandLine cmd = makeCommandLine(program, args);

    LOG.info("Running: " + cmd);
    ExecBean res = new ExecBean();
    res.exitcode = executor.execute(cmd, execEnv(env));
    String enc = appConf.get(AppConfig.EXEC_ENCODING_NAME);
    res.stdout = outStream.toString(enc);
    res.stderr = errStream.toString(enc);

    return res;
}

From source file:org.apache.hive.hcatalog.templeton.StreamOutputWriter.java

private ExecBean auxRun(String program, List<String> args, Map<String, String> env)
        throws NotAuthorizedException, ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);//  w w  w.j a  va2s .  com

    // Setup stdout and stderr
    int nbytes = appConf.getInt(AppConfig.EXEC_MAX_BYTES_NAME, -1);
    ByteArrayOutputStream outStream = new MaxByteArrayOutputStream(nbytes);
    ByteArrayOutputStream errStream = new MaxByteArrayOutputStream(nbytes);
    executor.setStreamHandler(new PumpStreamHandler(outStream, errStream));

    // Only run for N milliseconds
    int timeout = appConf.getInt(AppConfig.EXEC_TIMEOUT_NAME, 0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);

    CommandLine cmd = makeCommandLine(program, args);

    LOG.info("Running: " + cmd);
    ExecBean res = new ExecBean();

    res.exitcode = executor.execute(cmd, execEnv(env));

    String enc = appConf.get(AppConfig.EXEC_ENCODING_NAME);
    res.stdout = outStream.toString(enc);
    res.stderr = errStream.toString(enc);
    try {
        watchdog.checkException();
    } catch (Exception ex) {
        LOG.error("Command: " + cmd + " failed. res=" + res, ex);
    }
    if (watchdog.killedProcess()) {
        String msg = " was terminated due to timeout(" + timeout + "ms).  See " + AppConfig.EXEC_TIMEOUT_NAME
                + " property";
        LOG.warn("Command: " + cmd + msg + " res=" + res);
        res.stderr += " Command " + msg;
    }
    if (res.exitcode != 0) {
        LOG.info("Command: " + cmd + " failed. res=" + res);
    }
    return res;
}

From source file:org.apache.stratos.cartridge.agent.test.JavaCartridgeAgentTest.java

/**
 * Execute shell command/*w w  w .j av a  2 s .  c o m*/
 *
 * @param commandText
 */
private ByteArrayOutputStreamLocal executeCommand(final String commandText, File workingDir) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        if (workingDir != null) {
            exec.setWorkingDirectory(workingDir);
        }
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        log.info("Executing command: " + commandText
                + (workingDir == null ? "" : " at " + workingDir.getCanonicalPath()));
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.python.cartridge.agent.integration.tests.PythonAgentIntegrationTest.java

/**
 * Execute shell command//from  w  w  w . j a  v a  2 s  .  c om
 *
 * @param commandText Command string to be executed
 */
protected ByteArrayOutputStreamLocal executeCommand(final String commandText, int timeout) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(PythonAgentIntegrationTest.class.getResource(PATH_SEP).getPath()
                + PATH_SEP + ".." + PATH_SEP + PYTHON_AGENT_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.python.cartridge.agent.test.PythonAgentTestManager.java

/**
 * Execute shell command//from  www .  j av a  2s  .  c  om
 *
 * @param commandText
 */
protected ByteArrayOutputStreamLocal executeCommand(final String commandText) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(PythonAgentTestManager.class.getResource(PATH_SEP).getPath()
                + PATH_SEP + ".." + PATH_SEP + PYTHON_AGENT_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.python.cartridge.agent.test.PythonCartridgeAgentTest.java

/**
 * Execute shell command/* w w w .j  a v a  2s. co  m*/
 *
 * @param commandText
 */
private ByteArrayOutputStreamLocal executeCommand(final String commandText) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.tika.parser.geo.topic.GeoParser.java

public HashMap<String, ArrayList<String>> searchGeoNames(ArrayList<String> locationNameEntities)
        throws ExecuteException, IOException {
    CommandLine cmdLine = new CommandLine("lucene-geo-gazetteer");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    cmdLine.addArgument("-s");
    for (String name : locationNameEntities) {
        cmdLine.addArgument(name);// w ww  .  jav a2 s .c om
    }

    LOG.fine("Executing: " + cmdLine);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    exec.setWatchdog(watchdog);
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment());
    String outputJson = outputStream.toString("UTF-8");
    JSONArray json = (JSONArray) JSONValue.parse(outputJson);

    HashMap<String, ArrayList<String>> returnHash = new HashMap<String, ArrayList<String>>();
    for (int i = 0; i < json.size(); i++) {
        JSONObject obj = (JSONObject) json.get(i);
        for (Object key : obj.keySet()) {
            String theKey = (String) key;
            JSONArray vals = (JSONArray) obj.get(theKey);
            ArrayList<String> stringVals = new ArrayList<String>(vals.size());
            for (int j = 0; j < vals.size(); j++) {
                String val = (String) vals.get(j);
                stringVals.add(val);
            }

            returnHash.put(theKey, stringVals);
        }
    }

    return returnHash;

}

From source file:org.apache.tika.parser.pot.PooledTimeSeriesParser.java

private String computePoT(File input) throws IOException, TikaException {

    CommandLine cmdLine = new CommandLine("pooled-time-series");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    cmdLine.addArgument("-f");
    cmdLine.addArgument(input.getAbsolutePath());
    LOG.trace("Executing: {}", cmdLine);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValue(0);//  w ww.ja  v  a2s.  c om
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    exec.setWatchdog(watchdog);
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment());
    return outputStream.toString("UTF-8");

}