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

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

Introduction

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

Prototype

public int getExitValue() 

Source Link

Document

Gets the exit value returned by the failed process

Usage

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

/**
 * Execute an external command/*from   ww w .  jav  a2  s.  co  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(//from  w  ww  . j  a  v a 2s.c o  m
            new PumpStreamHandler(new WriterOutputStream(stdOutWriter), new WriterOutputStream(stdErrWriter)));
    final int exitCode = Try.of(() -> {
        try {
            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

@DescribeProcess(title = "GRASS Version", description = "Retreive the version of GRASS used for computation")
@DescribeResult(description = "Version")
public static String version() {
    if (EXEC == null) {
        return "unavailable";
    }//from  www .  ja  va 2s  . c  o m
    CommandLine cmd = new CommandLine(EXEC);
    cmd.addArgument("-v");

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        executor.setStreamHandler(new PumpStreamHandler(outputStream));

        LOGGER.info("exec: " + cmd.toString());
        int exitValue = executor.execute(cmd);
        return outputStream.toString();
    } catch (ExecuteException huh) {
        return "exit code: " + huh.getExitValue() + " (" + huh.getMessage() + ")";
    } catch (IOException e) {
        return "unavailable: " + e.getClass().getSimpleName() + ":" + e.getMessage();
    }
}

From source file:com.taobao.ad.es.common.job.executor.ShellHttpJobExecutor.java

@Override
public JobResult execute(JobData jobData) throws IOException {
    JobResult jobResult = JobResult.succcessResult();
    CommandLine cmdLine = CommandLine.parse(jobData.getData().get(JobData.JOBDATA_DATA_JOBCOMMAND));
    Executor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(1200000);
    executor.setExitValue(0);//w  w  w .  ja  v  a 2s.  c om
    executor.setWatchdog(watchdog);
    int exitValue = -1;
    try {
        exitValue = executor.execute(cmdLine);
    } catch (ExecuteException e) {
        exitValue = e.getExitValue();
    }
    if (exitValue != 0) {
        jobResult = JobResult.errorResult(JobResult.RESULTCODE_OTHER_ERR,
                "Shell?");
        jobResult.setResultCode(exitValue);
        return jobResult;
    }
    jobResult.setResultCode(exitValue);
    return jobResult;
}

From source file:com.creactiviti.piper.plugin.ffmpeg.Ffmpeg.java

@Override
public Object handle(Task aTask) throws Exception {
    List<String> options = aTask.getList("options", String.class);
    CommandLine cmd = new CommandLine("ffmpeg");
    options.forEach(o -> cmd.addArgument(o));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        int exitValue = exec.execute(cmd);
        return exitValue != 0 ? FileUtils.readFileToString(tempFile) : cmd.toString();
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {/*from   w ww .  j  av  a2s .c  om*/
        FileUtils.deleteQuietly(tempFile);
    }
}

From source file:com.github.mjeanroy.maven.plugins.node.commands.CommandExecutor.java

/**
 * Execute command line and return the result status.
 *
 * @param workingDirectory Working directory (i.e where the command line is executed).
 * @param command Command, containing executable path with arguments.
 * @param logger Logger to use to log command output.
 * @return Command result object./*from  w w  w .ja  v  a 2  s.  co m*/
 */
public CommandResult execute(File workingDirectory, Command command, Log logger) {
    CommandLine commandLine = new CommandLine(command.getExecutable());
    for (String argument : command.getArguments()) {
        commandLine.addArgument(argument);
    }

    try {
        Executor executor = new DefaultExecutor();
        executor.setWorkingDirectory(workingDirectory);
        executor.setExitValue(0);

        // Define custom output stream
        LogStreamHandler stream = new LogStreamHandler(logger);
        PumpStreamHandler handler = new PumpStreamHandler(stream);
        executor.setStreamHandler(handler);

        int status = executor.execute(commandLine);
        return new CommandResult(status);
    } catch (ExecuteException ex) {
        return new CommandResult(ex.getExitValue());
    } catch (IOException ex) {
        throw new CommandException(ex);
    }
}

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  w  w  w . jav  a 2  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.creactiviti.piper.plugin.ffmpeg.Mediainfo.java

@Override
public Map<String, Object> handle(Task aTask) throws Exception {
    CommandLine cmd = new CommandLine("mediainfo");
    cmd.addArgument(aTask.getRequiredString("input"));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        exec.execute(cmd);/*from ww w. j ava  2 s .c o  m*/
        return parse(FileUtils.readFileToString(tempFile));
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {
        FileUtils.deleteQuietly(tempFile);
    }
}

From source file:com.creactiviti.piper.plugin.ffmpeg.Ffprobe.java

@Override
public Map<String, Object> handle(Task aTask) throws Exception {
    CommandLine cmd = new CommandLine("ffprobe");
    cmd.addArgument("-v").addArgument("quiet").addArgument("-print_format").addArgument("json")
            .addArgument("-show_error").addArgument("-show_format").addArgument("-show_streams")
            .addArgument(aTask.getRequiredString("input"));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        exec.execute(cmd);/*from w ww  .  j  av a  2 s . com*/
        return parse(FileUtils.readFileToString(tempFile));
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {
        FileUtils.deleteQuietly(tempFile);
    }
}

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

protected boolean loadIntoRam(String executable, File ramFile, String comPort) {
    try {// w  ww  . ja v  a  2  s.c om
        Map map = new HashMap();
        map.put("ramFile", ramFile);

        CommandLine cmdLine = new CommandLine(executable);
        cmdLine.addArgument("-r");
        if (comPort != null) {
            cmdLine.addArgument("-p").addArgument(comPort);
        }
        cmdLine.addArgument("${ramFile}");

        cmdLine.setSubstitutionMap(map);
        DefaultExecutor executor = new DefaultExecutor();
        //executor.setExitValues(new int[]{451, 301});

        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 {
            output = outputStream.toString();
        }

        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}