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

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

Introduction

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

Prototype

public void setExitValues(final int[] values) 

Source Link

Usage

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

@Override
public void run() {
    /*//from w  w  w .jav  a 2 s . c om
     * 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  ww.j a  va  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. 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:org.wisdom.maven.utils.WisdomExecutor.java

/**
 * Launches the Wisdom server. This method blocks until the wisdom server shuts down.
 * It uses the {@literal Java} executable directly.
 *
 * @param mojo        the mojo//ww w. j a v  a2 s.c o  m
 * @param interactive enables the shell prompt
 * @param debug       the debug port (0 to disable it)
 * @param jvmArgs     JVM arguments to add to the `java` command (before the -jar argument).
 * @param destroyer   a process destroyer that can be used to destroy the process, if {@code null}
 *                    a {@link org.apache.commons.exec.ShutdownHookProcessDestroyer} is used.
 * @throws MojoExecutionException if the Wisdom instance cannot be started or has thrown an unexpected status
 *                                while being stopped.
 */
public void execute(AbstractWisdomMojo mojo, boolean interactive, int debug, String jvmArgs,
        ProcessDestroyer destroyer) throws MojoExecutionException {
    // Get java
    File java = ExecUtils.find("java", new File(mojo.javaHome, "bin"));
    if (java == null) {
        throw new MojoExecutionException("Cannot find the java executable");
    }

    CommandLine cmdLine = new CommandLine(java);

    if (debug != 0) {
        cmdLine.addArgument("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=" + debug, false);
    }

    if (!Strings.isNullOrEmpty(jvmArgs)) {
        cmdLine.addArguments(jvmArgs, false);
    }

    cmdLine.addArgument("-jar");
    cmdLine.addArgument("bin/chameleon-core-" + CHAMELEON_VERSION + ".jar");
    if (interactive) {
        cmdLine.addArgument("--interactive");
    }

    appendSystemPropertiesToCommandLine(mojo, cmdLine);

    DefaultExecutor executor = new DefaultExecutor();
    if (destroyer != null) {
        executor.setProcessDestroyer(destroyer);
    } else {
        executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    }

    executor.setWorkingDirectory(mojo.getWisdomRootDirectory());
    if (interactive) {
        executor.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in)); //NOSONAR
        // Using the interactive mode the framework should be stopped using the 'exit' command,
        // and produce a '0' status.
        executor.setExitValue(0);
    } else {
        executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); // NOSONAR
        // As the execution is intended to be interrupted using CTRL+C, the status code returned is expected to be 1
        // 137 or 143 is used when stopped by the destroyer.
        executor.setExitValues(new int[] { 1, 137, 143 });
    }
    try {
        mojo.getLog().info("Launching Wisdom Server");
        mojo.getLog().debug("Command Line: " + cmdLine.toString());
        // The message is different whether or not we are in the interactive mode.
        if (interactive) {
            mojo.getLog().info("You are in interactive mode");
            mojo.getLog().info("Hit 'exit' to shutdown");
        } else {
            mojo.getLog().info("Hit CTRL+C to exit");
        }
        if (debug != 0) {
            mojo.getLog().info("Wisdom launched with remote debugger interface enabled on port " + debug);
        }
        // Block execution until ctrl+c
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot execute Wisdom", e);
    }
}

From source file:org.zanata.rest.service.VirusScanner.java

/**
 * Builds an Executor which will output to the specified OutputStream.
 * <p>/*from w  w  w  .  jav a  2 s.co m*/
 * The Executor will be configured to return exit values as int, rather than
 * throwing ExecuteException.
 *
 * @param output
 * @return a configured Executor
 */
private Executor buildExecutor(OutputStream output) {
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    ExecuteStreamHandler psh = new PumpStreamHandler(output);
    executor.setStreamHandler(psh);
    // We want to handle all exit values directly (not as ExecuteException).
    executor.setExitValues(null);
    return executor;
}

From source file:processing.app.debug.Compiler.java

/**
 * Either succeeds or throws a RunnerException fit for public consumption.
 *//* w w w  . j  a  v a  2s .  c  o  m*/
private void execAsynchronously(String[] command) throws RunnerException {

    // eliminate any empty array entries
    List<String> stringList = new ArrayList<String>();
    for (String string : command) {
        string = string.trim();
        if (string.length() != 0)
            stringList.add(string);
    }
    command = stringList.toArray(new String[stringList.size()]);
    if (command.length == 0)
        return;

    if (verbose) {
        for (String c : command)
            System.out.print(c + " ");
        System.out.println();
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler() {

        @Override
        protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) {
            final Thread result = new Thread(new MyStreamPumper(is, Compiler.this));
            result.setDaemon(true);
            return result;

        }
    });

    CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i], false);
    }

    int result;
    executor.setExitValues(null);
    try {
        result = executor.execute(commandLine);
    } catch (IOException e) {
        RunnerException re = new RunnerException(e.getMessage());
        re.hideStackTrace();
        throw re;
    }
    executor.setExitValues(new int[0]);

    // an error was queued up by message(), barf this back to compile(),
    // which will barf it back to Editor. if you're having trouble
    // discerning the imagery, consider how cows regurgitate their food
    // to digest it, and the fact that they have five stomaches.
    //
    //System.out.println("throwing up " + exception);
    if (exception != null)
        throw exception;

    if (result > 1) {
        // a failure in the tool (e.g. unable to locate a sub-executable)
        System.err.println(I18n.format(_("{0} returned {1}"), command[0], result));
    }

    if (result != 0) {
        RunnerException re = new RunnerException(_("Error compiling."));
        re.hideStackTrace();
        throw re;
    }
}

From source file:processing.app.debug.OldCompiler.java

/**
 * Either succeeds or throws a RunnerException fit for public consumption.
 *//*  w  ww. j av  a  2  s.co  m*/
private void execAsynchronously(String[] command) throws RunnerException {

    // eliminate any empty array entries
    List<String> stringList = new ArrayList<String>();
    for (String string : command) {
        string = string.trim();
        if (string.length() != 0)
            stringList.add(string);
    }
    command = stringList.toArray(new String[stringList.size()]);
    if (command.length == 0)
        return;

    if (verbose) {
        for (String c : command)
            System.out.print(c + " ");
        System.out.println();
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler() {

        @Override
        protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) {
            final Thread result = new Thread(new MyStreamPumper(is, OldCompiler.this));
            result.setDaemon(true);
            return result;

        }
    });

    CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i], false);
    }

    int result;
    executor.setExitValues(null);
    try {
        result = executor.execute(commandLine);
    } catch (IOException e) {
        RunnerException re = new RunnerException(e.getMessage());
        re.hideStackTrace();
        throw re;
    }
    executor.setExitValues(new int[0]);

    // an error was queued up by message(), barf this back to compile(),
    // which will barf it back to Editor. if you're having trouble
    // discerning the imagery, consider how cows regurgitate their food
    // to digest it, and the fact that they have five stomaches.
    //
    //System.out.println("throwing up " + exception);
    if (exception != null)
        throw exception;

    if (result > 1) {
        // a failure in the tool (e.g. unable to locate a sub-executable)
        System.err.println(I18n.format(tr("{0} returned {1}"), command[0], result));
    }

    if (result != 0) {
        RunnerException re = new RunnerException(tr("Error compiling."));
        re.hideStackTrace();
        throw re;
    }
}