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.ng200.openolympus.cerberus.compilers.FPCCompiler.java

@Override
public void compile(final List<Path> inputFiles, final Path outputFile,
        final Map<String, Object> additionalParameters) throws CompilationException {
    FPCCompiler.logger.debug("Compiling {} to {} using FPC", inputFiles, outputFile);

    final CommandLine commandLine = new CommandLine("ppcx64");
    commandLine.setSubstitutionMap(additionalParameters);

    this.arguments.forEach((arg) -> commandLine.addArgument(arg));

    commandLine.addArgument("-o" + outputFile.toAbsolutePath().toString()); // Set
    // outuput//www  . j  a  v  a2 s  .c  o  m
    // file
    commandLine.addArgument("-l-");
    commandLine.addArgument("-v0");
    inputFiles.forEach((file) -> commandLine
            .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add
    // input
    // files

    FPCCompiler.logger.debug("Running FPC with arguments: {}", commandLine.toString());

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(errorStream, null, null));

    executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to
    // compile
    int result;
    try {
        result = executor.execute(commandLine);
    } catch (final IOException e) {
        FPCCompiler.logger.error("Could not execute FPC: {}", e);
        throw new CompilationException("Could not execute FPC", e);
    }
    switch (result) {
    case 0:
        return;
    case 1:
        try {
            final String errorString = errorStream.toString("UTF-8");

            final Pattern pattern = Pattern.compile(
                    "^(" + inputFiles.stream().map(file -> Pattern.quote(file.getFileName().toString()))
                            .collect(Collectors.joining("|")) + ")",
                    Pattern.MULTILINE);

            FPCCompiler.logger.debug("Compilation error: {}", errorString);

            throw new CompilerError("fpc.wrote.stdout", errorString);
        } catch (final UnsupportedEncodingException e) {
            throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e);
        }
    }
}

From source file:org.ng200.openolympus.cerberus.compilers.GNUCompiler.java

@Override
public void compile(final List<Path> inputFiles, final Path outputFile,
        final Map<String, Object> additionalParameters) throws CompilationException {
    GNUCompiler.logger.debug("Compiling {} to {} using GCC", inputFiles, outputFile);

    final CommandLine commandLine = new CommandLine("g++");
    commandLine.setSubstitutionMap(additionalParameters);

    this.arguments.forEach((arg) -> commandLine.addArgument(arg));

    commandLine.addArgument("-w"); // Prohibit warnings because they screw
    // up error detection

    commandLine.addArgument("-o");
    commandLine.addArgument(MessageFormat.format("\"{0}\"", outputFile.toAbsolutePath().toString())); // Set outuput file

    inputFiles.forEach((file) -> commandLine
            .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add
    // input//from ww w. j  av a2  s.c  o  m
    // files

    GNUCompiler.logger.debug("Running GCC with arguments: {}", Arrays.asList(commandLine.getArguments()));

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(null, errorStream, null));

    executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to
    // compile
    int result;
    try {
        result = executor.execute(commandLine);
    } catch (final IOException e) {
        GNUCompiler.logger.error("Could not execute GCC: {}", e);
        throw new CompilationException("Could not execute GCC", e);
    }

    switch (result) {
    case 0:
        return;
    case 1:
        try {
            String errorString = errorStream.toString(StandardCharsets.UTF_8.name());

            final Pattern pattern = Pattern.compile(
                    "^(" + inputFiles.stream().map(file -> Pattern.quote(file.toAbsolutePath().toString()))
                            .collect(Collectors.joining("|")) + "):",
                    Pattern.MULTILINE);
            errorString = pattern.matcher(errorString).replaceAll("");

            GNUCompiler.logger.debug("Compilation error: {}", errorString);
            throw new CompilerError("gcc.wrote.stderr", errorString);
        } catch (final UnsupportedEncodingException e) {
            throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e);
        }
    }
}

From source file:org.ng200.openolympus.cerberus.compilers.JavaCompiler.java

@Override
public void compile(final List<Path> inputFiles, final Path outputFile,
        final Map<String, Object> additionalParameters) throws CompilationException, IOException {

    FileAccess.createDirectories(outputFile);

    final CommandLine commandLine = new CommandLine("javac");
    commandLine.setSubstitutionMap(additionalParameters);

    this.arguments.forEach((arg) -> commandLine.addArgument(arg));

    commandLine.addArgument("-d");
    commandLine.addArgument(outputFile.toAbsolutePath().toString());

    commandLine.addArgument("-nowarn"); // Prohibit warnings because they
    // screw/*ww  w  . ja  v  a 2  s  .c  om*/
    // up error detection

    inputFiles.forEach((file) -> commandLine
            .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add
    // input
    // files

    JavaCompiler.logger.info("Running javac with arguments: {}", Arrays.asList(commandLine.getArguments()));

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(null, errorStream, null));

    executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to
    // compile
    int result;
    try {
        result = executor.execute(commandLine);
    } catch (final IOException e) {
        JavaCompiler.logger.error("Could not execute javac: {}", e);
        throw new CompilationException("Could not execute javac", e);
    }

    switch (result) {
    case 0:
        return;
    case 1:
        try {
            String errorString = errorStream.toString("UTF-8");
            final Pattern pattern = Pattern.compile(
                    "^(" + inputFiles.stream().map(file -> Pattern.quote(file.toAbsolutePath().toString()))
                            .collect(Collectors.joining("|")) + "):",
                    Pattern.MULTILINE);
            errorString = pattern.matcher(errorString).replaceAll("");

            JavaCompiler.logger.debug("Compilation error: {}", errorString);

            throw new CompilerError("javac.wrote.stderr", errorString);
        } catch (final UnsupportedEncodingException e) {
            throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e);
        }
    }
}

From source file:org.ng200.openolympus.cerberus.executors.OpenOlympusWatchdogExecutor.java

private static void ensureUserAndGroupExists() throws IOException {
    if (alreadyEnsuredUserExists)
        return;/*ww  w .  jav  a2  s .  c  o m*/
    final CommandLine commandLine = new CommandLine("sudo");
    commandLine.addArgument("useradd");
    commandLine.addArgument("-U");
    commandLine.addArgument("-M"); // Don't create home directory
    commandLine.addArgument("-s");
    commandLine.addArgument("/bin/false");
    commandLine.addArgument("olympuswatchdogchild");

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, /* Added user */
            9
            /* User already exists */
    });

    executor.setWatchdog(new ExecuteWatchdog(1000));

    try {
        executor.execute(commandLine);
        alreadyEnsuredUserExists = true;
    } catch (final ExecuteException e) {
        throw new ExecuteException(
                "Couldn't find user/group id of the olympuswatchdogchild user/group: does it even exist?",
                e.getExitValue(), e);
    }
}

From source file:org.ng200.openolympus.FileAccess.java

public static void rsync(final Path from, final Path to) throws IOException {
    final CommandLine commandLine = new CommandLine("/usr/bin/rsync");
    commandLine.addArgument("-r");
    commandLine.addArgument("--ignore-errors");
    commandLine.addArgument(from.toAbsolutePath().toString());
    commandLine.addArgument(to.toAbsolutePath().toString());
    final DefaultExecutor executor = new DefaultExecutor();

    executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the
    // sandbox to
    // complete/*  w w  w .  j av a 2s .co m*/
    final ByteArrayOutputStream outAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outAndErr));
    executor.setExitValues(new int[] { 0 });
    try {
        executor.execute(commandLine);
    } catch (final ExecuteException e) {
        throw new IOException("Rsync failed:\n" + outAndErr.toString(), e);
    }
}

From source file:org.nuxeo.webpage.archiver.WebpageToBlob.java

protected Blob buildCommandLineAndRun(String inCommandLine, CmdParameters inParams, String inFileName,
        boolean inUseAllParams) throws IOException, CommandNotAvailable, NuxeoException {

    // Create a temp. File handled by Nuxeo
    Blob resultPdf = Blobs.createBlobWithExtension(".pdf");

    // Build the full, resolved command line
    String resolvedParameterString = CommandLineParameters.buildParameterString(inCommandLine,
            inParams.getParameter(CommandLineParameters.COOKIE_JAR),
            inParams.getParameter(CommandLineParameters.URL), resultPdf.getFile().getAbsolutePath());

    // Mainly during test, we may have uncjecked parameters (safe because everything is hard-coded server side)
    if (inUseAllParams) {
        if (!Framework.isTestModeSet()) {
            throw new NuxeoException("A call to buildCommandLineAndRun(..., true) is for test only.");
        }/* w ww.  j a v a  2 s .c  o  m*/
        Map<String, ParameterValue> allParams = inParams.getParameters();
        String key, value;
        for (Entry<String, ParameterValue> entry : allParams.entrySet()) {
            key = entry.getKey();
            value = entry.getValue().getValue();
            if (!CommandLineParameters.isHandledParameter(key)) {
                resolvedParameterString = StringUtils.replace(resolvedParameterString, "#{" + key + "}", value);
            }
        }
    }

    // Get the exact command line and build the line
    CommandLineDescriptor desc = CommandLineExecutorComponent.getCommandDescriptor(inCommandLine);
    String line = desc.getCommand() + " " + resolvedParameterString;

    // Run the thing
    Exception exception = null;

    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    // We don't want a check on exit values, because a PDF can still be created with errors
    // (can't get a font, ...)
    executor.setExitValues(null);
    executor.setWatchdog(watchdog);
    int exitValue = 0;
    try {
        exitValue = executor.execute(cmdLine);
    } catch (IOException e) {
        exception = e;
    }

    // Even if we had no error catched, we must check if the pdf is valid.
    // Exit value may be 1, or non zero while the pdf was created. But maybe
    // a font could not be correctly rendered, etc. Let's check if we have
    // something in the pdf and it looks valid
    if (!pdfLooksValid(resultPdf.getFile())) {
        resultPdf = null;
        String msg = "Failed to execute the command line [" + cmdLine.toString()
                + " ]. No valid PDF generated. exitValue: " + exitValue;

        if (exitValue == 143) { // On Linux: Timeout, wkhtmltopdf was SIGTERM
            msg += " (time out reached. The timeout was " + timeout + "ms)";
        }
        if (exception == null) {
            throw new NuxeoException(msg);
        } else {
            throw new NuxeoException(msg, exception);
        }
    }

    resultPdf.setMimeType("application/pdf");
    String url = inParams.getParameter(CommandLineParameters.URL);
    // Url parameter can be blank (hard coded url in the command line XML for example)
    if (StringUtils.isBlank(inFileName) && StringUtils.isNotBlank(url)) {
        try {
            URL urlObj = new URL(url);
            inFileName = StringUtils.replace(urlObj.getHost(), ".", "-") + ".pdf";
        } finally {
            // Nothing. Default name has been set by nuxeo
        }
    }
    if (StringUtils.isNotBlank(inFileName)) {
        resultPdf.setFilename(inFileName);
    }

    return resultPdf;
}

From source file:org.opennms.systemreport.SystemReportResourceLocator.java

@Override
public String slurpOutput(final String commandString, final boolean ignoreExitCode) {
    final CommandLine command = CommandLine.parse(commandString);
    LOG.debug("running: {}", commandString);

    final Map<String, String> environment = new HashMap<String, String>(System.getenv());
    environment.put("COLUMNS", "2000");
    DataInputStream input = null;
    PipedInputStream pis = null;/*ww w. ja v  a2  s. c  om*/
    OutputSuckingParser parser = null;
    String outputText = null;
    final DefaultExecutor executor = new DefaultExecutor();

    final PipedOutputStream output = new PipedOutputStream();
    final PumpStreamHandler streamHandler = new PumpStreamHandler(output, output);
    executor.setWatchdog(new ExecuteWatchdog(m_maxProcessWait));
    executor.setStreamHandler(streamHandler);
    if (ignoreExitCode) {
        executor.setExitValues(null);
    }

    try {
        LOG.trace("executing '{}'", commandString);
        pis = new PipedInputStream(output);
        input = new DataInputStream(pis);
        parser = new OutputSuckingParser(input);
        parser.start();
        final int exitValue = executor.execute(command, environment);
        IOUtils.closeQuietly(output);
        parser.join(m_maxProcessWait);
        if (!ignoreExitCode && exitValue != 0) {
            LOG.debug("error running '{}': exit value was {}", commandString, exitValue);
        } else {
            outputText = parser.getOutput();
        }
        LOG.trace("finished '{}'", commandString);
    } catch (final Exception e) {
        LOG.debug("Failed to run '{}'", commandString, e);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(pis);
    }

    return outputText;
}

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

@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    answered = false;/*from   w w  w  .ja  va2  s.c om*/
    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.gateway.kernel.exec.ExecuteExecutor.java

public void run() throws Reply421Exception {
    // Check if the execution will be done through LocalExec daemon
    if (AbstractExecutor.useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(arg, delay, futureCompletion);
            localExecClient.disconnect();
            return;
        } // else continue
    }//from  w w  w .  j  av  a2  s  .  com
    // Execution is done internally
    File exec = new File(args[0]);
    if (exec.isAbsolute()) {
        if (!exec.canExecute()) {
            logger.error("Exec command is not executable: " + args[0]);
            throw new Reply421Exception("Pre Exec command is not executable");
        }
    }
    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) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    int status = -1;
    try {
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(10);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e2) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e1) {
                }
                logger.error("System Exception: " + e.getMessage() + "\n    Exec cannot execute command "
                        + commandLine.toString());
                throw new Reply421Exception("Cannot execute Pre command");
            } catch (IOException e2) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e1) {
                }
                logger.error(
                        "Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
                throw new Reply421Exception("Cannot execute Pre command");
            }
            logger.info("System Exception: " + e.getMessage() + " but finally get the command executed "
                    + commandLine.toString());
        } else {
            try {
                pumpStreamHandler.stop();
            } catch (IOException e1) {
            }
            logger.error("Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
            throw new Reply421Exception("Cannot execute Pre command");
        }
    } catch (IOException e) {
        try {
            pumpStreamHandler.stop();
        } catch (IOException e1) {
        }
        logger.error("Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
        throw new Reply421Exception("Cannot execute Pre command");
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e1) {
    }
    if (watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        logger.error("Exec is in Time Out");
        status = -1;
    }
    if (status == 0) {
        futureCompletion.setSuccess();
        logger.info("Exec OK with {}", commandLine);
    } else if (status == 1) {
        logger.warn("Exec in warning with {}", commandLine);
        futureCompletion.setSuccess();
    } else {
        logger.debug("Status: " + status + (status == -1 ? " Tiemout" : "") + " Exec in error with "
                + commandLine.toString());
        throw new Reply421Exception("Pre command executed in error");
    }
}

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

@Override
public void run() {
    /*/*  w  ww.  ja  v a 2 s.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. 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());
}