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

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

Introduction

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

Prototype

public boolean isFailure(final int exitValue) 

Source Link

Usage

From source file:org.geoserver.importer.transform.AbstractCommandLineTransform.java

@Override
public void apply(ImportTask task, ImportData data) throws Exception {
    boolean inline = isInline();
    File executable = getExecutable();
    File inputFile = getInputFile(data);
    Map<String, File> substitutions = new HashMap<>();
    substitutions.put("input", inputFile);
    File outputDirectory = null;//from   w  w w .ja  v  a 2 s. c o m
    File outputFile = null;
    if (!inline) {
        outputDirectory = getOutputDirectory(data);
        outputFile = new File(outputDirectory, inputFile.getName());
        substitutions.put("output", outputFile);
    }

    // setup the options
    CommandLine cmd = new CommandLine(executable);
    cmd.setSubstitutionMap(substitutions);

    setupCommandLine(inline, cmd);

    // prepare to run
    DefaultExecutor executor = new DefaultExecutor();
    // make sure we don't try to execute for too much time
    executor.setWatchdog(new ExecuteWatchdog(DEFAULT_TIMEOUT));

    // grab at least some part of the outputs
    int limit = 16 * 1024;
    try {
        try (OutputStream os = new BoundedOutputStream(new ByteArrayOutputStream(), limit);
                OutputStream es = new BoundedOutputStream(new ByteArrayOutputStream(), limit)) {
            PumpStreamHandler streamHandler = new PumpStreamHandler(os, es);
            executor.setStreamHandler(streamHandler);
            try {
                int result = executor.execute(cmd);

                if (executor.isFailure(result)) {
                    // toString call is routed to ByteArrayOutputStream, which does the right string
                    // conversion
                    throw new IOException(
                            "Failed to execute command " + cmd.toString() + "\nStandard output is:\n"
                                    + os.toString() + "\nStandard error is:\n" + es.toString());
                }
            } catch (Exception e) {
                throw new IOException("Failure to execute command " + cmd.toString() + "\nStandard output is:\n"
                        + os.toString() + "\nStandard error is:\n" + es.toString(), e);
            }
        }

        // if not inline, replace inputs with output
        if (!inline) {
            List<String> names = getReplacementTargetNames(data);
            File inputParent = inputFile.getParentFile();
            for (String name : names) {
                File output = new File(outputDirectory, name);
                File input = new File(inputParent, name);
                if (output.exists()) {
                    // uses atomic rename on *nix, delete and copy on Windows
                    IOUtils.rename(output, input);
                } else if (input.exists()) {
                    input.delete();
                }
            }
        }
    } finally {
        if (outputDirectory != null) {
            FileUtils.deleteQuietly(outputDirectory);
        }
    }
}

From source file:org.moe.cli.utils.Utils.java

public static String[] execute(File dir, String command, Map<String, String> environment) {

    Map<String, String> current = null;
    try {// w  w w.j av a 2s.  co  m
        current = EnvironmentUtils.getProcEnvironment();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    if (environment != null && current != null) {
        current.putAll(environment);
    }

    CommandLine cmdLine = CommandLine.parse(command);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(dir);

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    PumpStreamHandler stHandler = new PumpStreamHandler(stdout, stderr);

    executor.setStreamHandler(stHandler);
    int exitValue = Executor.INVALID_EXITVALUE;

    try {
        exitValue = executor.execute(cmdLine, current);
    } catch (IOException e) {
    }

    return new String[] { stdout.toString(), executor.isFailure(exitValue) ? stderr.toString() : null };
}

From source file:org.mule.test.infrastructure.process.MuleUtils.java

public static int executeCommand(String command, String... envVars) throws IOException {
    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    Map<String, String> env = addEnvProperties(envVars);
    ExecuteWatchdog watchDog = new ExecuteWatchdog(TIMEOUT);
    executor.setWatchdog(watchDog);//  w  w w  .j  a  va 2s .com
    executor.setStreamHandler(new PumpStreamHandler());
    int result = executor.execute(cmdLine, env);
    if (executor.isFailure(result)) {
        if (watchDog.killedProcess()) {
            throw new RuntimeException("Reached timeout while running: " + cmdLine);
        }
        throw new RuntimeException("Process failed with return code [" + result + "]: " + cmdLine);
    }
    return result;
}

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

@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    answered = false;//  ww  w .  j  a v  a 2  s. co 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.openr66.context.task.ExecMoveTask.java

@Override
public void run() {
    /*/* w  ww  .j a  v a2s.c  o 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());
}

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

@Override
public void run() {
    /*/*from www  .  j  ava  2s  . c o  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. In case of
     * an error (> 0), all the line from output will be send back to the partner with the Error
     * code. No change is made to the file.
     */
    logger.info("ExecOutput 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();
            finalize(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);
    }
    AllLineReader allLineReader = new AllLineReader(inputStream);
    Thread thread = new Thread(allLineReader, "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) {
                finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status,
                        commandLine);
                return;
            } catch (IOException e1) {
                try {
                    outputStream.flush();
                } catch (IOException e2) {
                }
                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 {
            finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status,
                    commandLine);
            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 = allLineReader.getLastLine().toString();
    }
    finalize(status, newname, commandLine.toString());
}

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

@Override
public void run() {
    /*// w  w w.java  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. No change
     * should be done in the FILENAME
     */
    logger.debug("Exec with " + argRule + ":" + argTransfer + " and {}", session);
    String finalname = argRule;
    finalname = getReplacedValue(finalname, argTransfer.split(" "));
    // Check if the execution will be done through LocalExec daemon
    if (Configuration.configuration.isUseLocalExec() && useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion);
            localExecClient.disconnect();
            return;
        } // else continue
    }
    // Execution is done internally
    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();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null);
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    int[] correctValues = { 0, 1 };
    defaultExecutor.setExitValues(correctValues);
    ExecuteWatchdog watchdog = null;
    if (delay > 0 && waitForValidation) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    if (!waitForValidation) {
        // Do not wait for validation
        futureCompletion.setSuccess();
        logger.info("Exec will start but no WAIT with {}", commandLine);
    }
    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 {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
                if (waitForValidation) {
                    futureCompletion.setFailure(e);
                }
                return;
            } catch (IOException e1) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
                if (waitForValidation) {
                    futureCompletion.setFailure(e);
                }
                return;
            }
        } else {
            try {
                pumpStreamHandler.stop();
            } catch (IOException e2) {
            }
            logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
            if (waitForValidation) {
                futureCompletion.setFailure(e);
            }
            return;
        }
    } catch (IOException e) {
        try {
            pumpStreamHandler.stop();
        } catch (IOException e2) {
        }
        logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
        if (waitForValidation) {
            futureCompletion.setFailure(e);
        }
        return;
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e2) {
    }
    if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        logger.error("Exec is in Time Out");
        status = -1;
    }
    if (status == 0) {
        if (waitForValidation) {
            futureCompletion.setSuccess();
        }
        logger.info("Exec OK with {}", commandLine);
    } else if (status == 1) {
        logger.warn("Exec in warning with " + commandLine.toString());
        if (waitForValidation) {
            futureCompletion.setSuccess();
        }
    } else {
        logger.error("Status: " + status + " Exec in error with " + commandLine.toString());
        if (waitForValidation) {
            futureCompletion.cancel();
        }
    }
}

From source file:sce.ProcessExecutor.java

public String executeProcess(String[] processParameters) throws JobExecutionException {
    try {// w  w  w  .  ja  v a  2  s .c  o m
        //Command to be executed
        CommandLine command = new CommandLine(processParameters[0]);

        String[] params = new String[processParameters.length - 1];
        for (int i = 0; i < processParameters.length - 1; i++) {
            params[i] = processParameters[i + 1];
        }

        //Adding its arguments
        command.addArguments(params);

        //set timeout in seconds
        ExecuteWatchdog watchDog = new ExecuteWatchdog(
                this.timeout == 0 ? ExecuteWatchdog.INFINITE_TIMEOUT : this.timeout * 1000);
        this.watchdog = watchDog;

        //Result Handler for executing the process in a Asynch way
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        //MyResultHandler resultHandler = new MyResultHandler();

        //Using Std out for the output/error stream
        //ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        //This is used to end the process when the JVM exits
        ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer();

        //Our main command executor
        DefaultExecutor executor = new DefaultExecutor();

        //Setting the properties
        executor.setStreamHandler(new PumpStreamHandler(null, null));
        executor.setWatchdog(watchDog);
        //executor.setExitValue(1); // this has to be set if the java code contains System.exit(1) to avoid a FAILED status

        //Setting the working directory
        //Use of recursion along with the ls makes this a long running process
        //executor.setWorkingDirectory(new File("/home"));
        executor.setProcessDestroyer(processDestroyer);

        //if set, use the java environment variables when running the command
        if (!this.environment.equals("")) {
            Map<String, String> procEnv = EnvironmentUtils.getProcEnvironment();
            EnvironmentUtils.addVariableToEnvironment(procEnv, this.environment);
            //Executing the command
            executor.execute(command, procEnv, resultHandler);
        } else {
            //Executing the command
            executor.execute(command, resultHandler);
        }

        //The below section depends on your need
        //Anything after this will be executed only when the command completes the execution
        resultHandler.waitFor();

        /*int exitValue = resultHandler.getExitValue();
         System.out.println(exitValue);
         if (executor.isFailure(exitValue)) {
         System.out.println("Execution failed");
         } else {
         System.out.println("Execution Successful");
         }
         System.out.println(outputStream.toString());*/
        //return outputStream.toString();
        if (watchdog.killedProcess()) {
            throw new JobExecutionException("Job Interrupted", new InterruptedException());
        }
        if (executor.isFailure(resultHandler.getExitValue())) {
            ExecuteException ex = resultHandler.getException();
            throw new JobExecutionException(ex.getMessage(), ex);
        }
        return "1";
    } catch (ExecuteException ex) {
        throw new JobExecutionException(ex.getMessage(), ex);
    } catch (IOException | InterruptedException | JobExecutionException ex) {
        throw new JobExecutionException(ex.getMessage(), ex);
    }
}