Example usage for org.apache.commons.exec DefaultExecuteResultHandler getExitValue

List of usage examples for org.apache.commons.exec DefaultExecuteResultHandler getExitValue

Introduction

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

Prototype

public int getExitValue() 

Source Link

Document

Get the exitValue of the process.

Usage

From source file:com.tupilabs.pbs.PBS.java

/**
 * PBS qstat command.// w w  w .ja v  a  2s  .  c om
 * <p>
 * Equivalent to qstat -Q -f [name]
 *
 * @param name queue name
 * @return list of queues
 */
public static List<Queue> qstatQueues(String name) {
    final CommandLine cmdLine = new CommandLine(COMMAND_QSTAT);
    cmdLine.addArgument(PARAMETER_FULL_STATUS);
    cmdLine.addArgument(PARAMETER_QUEUE);
    if (StringUtils.isNotBlank(name)) {
        cmdLine.addArgument(name);
    }

    final OutputStream out = new ByteArrayOutputStream();
    final OutputStream err = new ByteArrayOutputStream();

    DefaultExecuteResultHandler resultHandler;
    try {
        resultHandler = execute(cmdLine, null, out, err);
        resultHandler.waitFor(DEFAULT_TIMEOUT);
    } catch (ExecuteException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    }

    final int exitValue = resultHandler.getExitValue();
    LOGGER.info("qstat exit value: " + exitValue);

    final List<Queue> queues;
    try {
        queues = QSTAT_QUEUES_PARSER.parse(out.toString());
    } catch (ParseException pe) {
        throw new PBSException("Failed to parse qstat queues output: " + pe.getMessage(), pe);
    }

    return (queues == null ? new ArrayList<Queue>(0) : queues);
}

From source file:com.tupilabs.pbs.PBS.java

/**
 * PBS qsub command./* w  w w.  j  a v  a 2 s .c om*/
 * <p>
 * Equivalent to qsub [param]
 *
 * @param inputs job input file
 * @param environment environment variables
 * @return job id
 */
public static String qsub(String[] inputs, Map<String, String> environment) {
    final CommandLine cmdLine = new CommandLine(COMMAND_QSUB);
    for (int i = 0; i < inputs.length; ++i) {
        cmdLine.addArgument(inputs[i]);
    }

    final OutputStream out = new ByteArrayOutputStream();
    final OutputStream err = new ByteArrayOutputStream();

    DefaultExecuteResultHandler resultHandler;
    try {
        resultHandler = execute(cmdLine, environment, out, err);
        resultHandler.waitFor(DEFAULT_TIMEOUT);
    } catch (ExecuteException e) {
        throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
    }

    final int exitValue = resultHandler.getExitValue();
    LOGGER.info("qsub exit value: " + exitValue);
    LOGGER.fine("qsub output: " + out.toString());

    if (exitValue != 0) {
        throw new PBSException("Failed to submit job script with command line '" + cmdLine.toString()
                + "'. Error output: " + err.toString());
    }

    String jobId = out.toString();
    return jobId.trim();
}

From source file:com.tupilabs.pbs.PBS.java

/**
 * PBS qnodes command.//from w ww .ja  va2s.  c om
 * <p>
 * Get information about the cluster nodes.
 *
 * @param name node name
 * @return list of nodes
 * @throws PBSException if an error communicating with the PBS occurs
 */
public static List<Node> qnodes(String name) {
    final List<Node> nodes;

    final CommandLine cmdLine = new CommandLine(COMMAND_QNODES);
    cmdLine.addArgument(PARAMETER_XML);
    if (StringUtils.isNotBlank(name)) {
        cmdLine.addArgument(name);
    }

    final OutputStream out = new ByteArrayOutputStream();
    final OutputStream err = new ByteArrayOutputStream();

    DefaultExecuteResultHandler resultHandler;
    try {
        resultHandler = execute(cmdLine, null, out, err);
        resultHandler.waitFor(DEFAULT_TIMEOUT);
    } catch (ExecuteException e) {
        throw new PBSException("Failed to execute qnodes command: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PBSException("Failed to execute qnodes command: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new PBSException("Failed to execute qnodes command: " + e.getMessage(), e);
    }

    final int exitValue = resultHandler.getExitValue();
    LOGGER.info("qnodes exit value: " + exitValue);

    try {
        nodes = NODE_XML_PARSER.parse(out.toString());
    } catch (ParseException pe) {
        throw new PBSException("Failed to parse node XML: " + pe.getMessage(), pe);
    }

    return nodes;
}

From source file:com.tupilabs.pbs.PBS.java

/**
 * PBS tracejob command.//from   ww  w  .j  a  v a2  s  .  c o  m
 * <p>
 * Equivalent to tracejob -n [numberOfDays] [jobId]
 *
 * @param jobId job id
 * @param numberOfDays number of days to look for the job
 * @param quiet quiet mode flag
 * @return tracejob output
 */
public static CommandOutput traceJob(String jobId, int numberOfDays, boolean quiet) {
    final CommandLine cmdLine = new CommandLine(COMMAND_TRACEJOB);
    cmdLine.addArgument(PARAMETER_NUMBER_OF_DAYS);
    cmdLine.addArgument(Integer.toString(numberOfDays));
    if (quiet) {
        cmdLine.addArgument(PARAMETER_QUIET_MODE);
    }
    cmdLine.addArgument(jobId);

    final OutputStream out = new ByteArrayOutputStream();
    final OutputStream err = new ByteArrayOutputStream();

    DefaultExecuteResultHandler resultHandler;
    try {
        resultHandler = execute(cmdLine, null, out, err);
        resultHandler.waitFor(DEFAULT_TIMEOUT);
    } catch (ExecuteException e) {
        throw new PBSException("Failed to execute tracejob command: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PBSException("Failed to execute tracejob command: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new PBSException("Failed to execute tracejob command: " + e.getMessage(), e);
    }

    final int exitValue = resultHandler.getExitValue();
    LOGGER.info("tracejob exit value: " + exitValue);
    LOGGER.fine("tracejob output: " + out.toString());

    return new CommandOutput(out.toString(), err.toString());
}

From source file:com.anrisoftware.mongoose.buildins.execbuildin.ExecBuildin.java

/**
 * @throws IllegalStateException/*from   ww  w.  j  av  a  2  s.  com*/
 *             if the handler is not of type
 *             {@link DefaultExecuteResultHandler}.
 */
@Override
public int getTheExitValue() {
    if (handler instanceof DefaultExecuteResultHandler) {
        DefaultExecuteResultHandler h = (DefaultExecuteResultHandler) handler;
        return h.getExitValue();
    } else {
        throw log.notExitValueAvailable(this);
    }
}

From source file:edu.emory.cci.aiw.neo4jetl.Neo4jHome.java

private void controlServer(String command) throws IOException, InterruptedException, CommandFailedException {
    LOGGER.debug("Executing neo4j command {}...", command);
    CommandLine serverControlCommand = new CommandLine(new File(this.home, SERVER_CONTROL_COMMAND));
    serverControlCommand.addArgument("${command}");
    Map<String, String> map = new HashMap<>();
    map.put("command", command);
    serverControlCommand.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);//from   w ww .java 2 s  .com
    executor.setWatchdog(watchdog);
    executor.execute(serverControlCommand, resultHandler);
    LOGGER.debug("Neo4j command {} is completed, checking exit value...", command);
    resultHandler.waitFor();
    int exitValue = resultHandler.getExitValue();
    if (exitValue != 0) {
        ExecuteException exception = resultHandler.getException();
        throw new CommandFailedException(exitValue, "Neo4j command '" + command + "' failed", exception);
    }
    LOGGER.debug("Neo4j command {} was successful", command);
}

From source file:com.netflix.spinnaker.clouddriver.jobs.local.JobExecutorLocal.java

private <T> JobResult<T> executeStreaming(JobRequest jobRequest, ReaderConsumer<T> consumer)
        throws IOException {
    PipedOutputStream stdOut = new PipedOutputStream();
    ByteArrayOutputStream stdErr = new ByteArrayOutputStream();

    Executor executor = buildExecutor(new PumpStreamHandler(stdOut, stdErr, jobRequest.getInputStream()));
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(jobRequest.getCommandLine(), jobRequest.getEnvironment(), resultHandler);

    T result = consumer.consume(new BufferedReader(new InputStreamReader(new PipedInputStream(stdOut))));

    try {//from w  w w.  j a  v a  2 s.  c om
        resultHandler.waitFor();
    } catch (InterruptedException e) {
        executor.getWatchdog().destroyProcess();
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }

    return JobResult.<T>builder()
            .result(resultHandler.getExitValue() == 0 ? JobResult.Result.SUCCESS : JobResult.Result.FAILURE)
            .killed(executor.getWatchdog().killedProcess()).output(result).error(stdErr.toString()).build();
}

From source file:com.netflix.spinnaker.halyard.deploy.job.v1.JobExecutorLocal.java

@Override
public JobStatus updateJob(String jobId) {
    try {//from   w  w w . ja v a2 s . c o  m
        log.info("Polling state for " + jobId + "...");
        ExecutionHandler handler = jobIdToHandlerMap.get(jobId);

        if (handler == null) {
            return null;
        }

        JobStatus jobStatus = new JobStatus().setId(jobId);

        DefaultExecuteResultHandler resultHandler;
        ByteArrayOutputStream stdOutStream;
        ByteArrayOutputStream stdErrStream;

        stdOutStream = handler.getStdOut();
        stdErrStream = handler.getStdErr();
        resultHandler = handler.getResultHandler();

        jobStatus.setStdOut(new String(stdOutStream.toByteArray()));
        jobStatus.setStdErr(new String(stdErrStream.toByteArray()));

        if (resultHandler.hasResult()) {
            jobStatus.setState(State.COMPLETED);

            int exitValue = resultHandler.getExitValue();
            log.info(jobId + " has terminated with exit code " + exitValue);

            if (exitValue == 0) {
                jobStatus.setResult(Result.SUCCESS);
            } else {
                jobStatus.setResult(Result.FAILURE);
            }

            jobIdToHandlerMap.remove(jobId);
        } else {
            jobStatus.setState(State.RUNNING);
        }

        return jobStatus;
    } catch (Exception e) {
        log.warn("Failed to retrieve status of " + jobId);
        return null;
    }
}

From source file:com.stratio.ingestion.IngestionInterpreter.java

@Override
public InterpreterResult interpret(String st) {

    if (ingestionHome.isEmpty()) {
        open();/*from ww  w . ja  v a 2 s  . c  o m*/
        if (ingestionHome.isEmpty()) {
            return new InterpreterResult(InterpreterResult.Code.ERROR,
                    "%text Ingestion is not installed correctly. " + "INGESTION_HOME Is not set");
        }
    }

    IngestionSyntaxParser parser = new IngestionSyntaxParser();
    IngestionParserResult parserResult = null;
    try {
        parserResult = parser.parse(st);
    } catch (IngestionParserException e) {
        return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage());
    }

    StringBuilder shellCommand = new StringBuilder();
    StringBuilder interpreterResult = new StringBuilder();
    String bashResult;
    interpreterResult.append("%text ");

    switch (parserResult.getCommand()) {
    case AGENT_START:

        try {
            IngestionAgent agentStart = parserResult.getAgent();
            String agentName = agentStart.getName();
            String agentFilepath = agentStart.getFilepath();
            int agentPort = agentStart.getPort();

            logger.info("Ingestion interpreter @ agent start $INGESTION_HOME -> " + ingestionHome);
            logger.info("Ingestion interpreter @ agent start agent filepath -> " + agentFilepath);
            logger.info("Ingestion interpreter @ agent start agent name -> " + agentName);
            logger.info("Ingestion interpreter @ agent start agent port -> " + agentPort);

            shellCommand.append("exec \"").append(ingestionHome).append("/bin/flume-ng\" agent --conf ")
                    .append(ingestionHome).append("/conf --conf-file ").append(agentFilepath).append(" --name ")
                    .append(agentName).append(" -Dflume.monitoring.type=http -Dflume.monitoring.port=")
                    .append(String.valueOf(agentPort)).append("> /dev/null & ");

            logger.info("Ingestion interpreter @ agent start command -> " + shellCommand.toString());
            DefaultExecuteResultHandler handler = IngestionUtils.executeBash(shellCommand.toString());
            long initTime = System.currentTimeMillis();
            while (!handler.hasResult()) {
                if (System.currentTimeMillis() > (initTime + CMD_TIMEOUT)) {
                    handler.onProcessComplete(999);
                }
            }
            if (handler.getException() != null) {
                return new InterpreterResult(InterpreterResult.Code.ERROR,
                        "%text " + handler.getExitValue() + " " + handler.getException().getMessage());
            }
            bashResult = "Agent started";
            return new InterpreterResult(InterpreterResult.Code.SUCCESS, bashResult);
        } catch (IOException e) {
            return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage());
        }
    case AGENT_STOP:
        try {
            IngestionAgent agentStop = parserResult.getAgent();
            shellCommand.append("ps auxww | grep flume | grep ").append(agentStop.getPort())
                    .append("| awk '{ print $2 }' | xargs kill -15 ");
            IngestionUtils.executeBash(shellCommand.toString());
            return new InterpreterResult(InterpreterResult.Code.SUCCESS,
                    interpreterResult.append("Agent " + "apparently stopped ").toString());

        } catch (IOException e) {
            if (e.getMessage().contains("143")) { //after kill a process always 143 exit code
                return new InterpreterResult(InterpreterResult.Code.SUCCESS,
                        interpreterResult.append("Agent " + "apparently stopped ").toString());
            } else {
                return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage());
            }
        }
    case CHANNELS_STATUS:
        try {
            String json = IngestionUtils.getAgentStatus(parserResult.getAgent().getPort());
            if (json.length() > 3) {
                Map<String, String> channelsStatus = IngestionUtils.getChannelsStatus(json);
                String channelStatusResult = "";
                for (String channel : channelsStatus.keySet()) {
                    channelStatusResult += "Channel ".concat(channel).concat(": ")
                            .concat(channelsStatus.get(channel)).concat("\n");
                }
                return new InterpreterResult(InterpreterResult.Code.SUCCESS, "%text " + channelStatusResult);
            }
        } catch (IOException e) {
            return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage());
        }
        break;
    case LIST_PROPERTIES:
        List<String> files = new ArrayList<>();
        StringBuilder listResult = new StringBuilder();
        IngestionUtils.getIngestionPropertiesFiles(files, ingestionHome);
        if (!files.isEmpty()) {
            for (String file : files) {
                listResult.append(file).append("\n");
            }
            return new InterpreterResult(InterpreterResult.Code.SUCCESS,
                    "%text ".concat(listResult.toString()));
        }
        return new InterpreterResult(InterpreterResult.Code.ERROR, "%text No .properties files found");
    case HELP:
        return new InterpreterResult(InterpreterResult.Code.SUCCESS,
                interpreterResult.append(IngestionUtils.help()).toString());
    }

    return new InterpreterResult(InterpreterResult.Code.ERROR,
            "%text Ingestion command not recognized, type help" + " for more info");
}

From source file:com.netflix.spinnaker.halyard.core.job.v1.JobExecutorLocal.java

@Override
public JobStatus updateJob(String jobId) {
    try {/*from   w  w  w  .j a va 2 s .co  m*/
        log.debug("Polling state for " + jobId + "...");
        ExecutionHandler handler = jobIdToHandlerMap.get(jobId);

        if (handler == null) {
            return null;
        }

        JobStatus jobStatus = new JobStatus().setId(jobId);

        DefaultExecuteResultHandler resultHandler;
        ByteArrayOutputStream stdOutStream;
        ByteArrayOutputStream stdErrStream;

        stdOutStream = handler.getStdOut();
        stdErrStream = handler.getStdErr();
        resultHandler = handler.getResultHandler();

        stdOutStream.flush();
        stdErrStream.flush();

        jobStatus.setStdOut(new String(stdOutStream.toByteArray()));
        jobStatus.setStdErr(new String(stdErrStream.toByteArray()));

        if (resultHandler.hasResult()) {
            jobStatus.setState(JobStatus.State.COMPLETED);

            int exitValue = resultHandler.getExitValue();
            log.info(jobId + " has terminated with exit code " + exitValue);

            if (exitValue == 0) {
                jobStatus.setResult(JobStatus.Result.SUCCESS);
            } else {
                jobStatus.setResult(JobStatus.Result.FAILURE);
            }

            jobIdToHandlerMap.remove(jobId);
        } else {
            jobStatus.setState(JobStatus.State.RUNNING);
        }

        return jobStatus;
    } catch (Exception e) {
        log.warn("Failed to retrieve status of " + jobId);
        return null;
    }
}