Example usage for org.apache.commons.exec ExecuteWatchdog ExecuteWatchdog

List of usage examples for org.apache.commons.exec ExecuteWatchdog ExecuteWatchdog

Introduction

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

Prototype

public ExecuteWatchdog(final long timeout) 

Source Link

Document

Creates a new watchdog with a given timeout.

Usage

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

@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    answered = false;//from  ww w  . ja v  a  2 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 ww  .ja v  a  2s.  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() {
    /*/*from   w  ww .  j a v  a2  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. 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() {
    /*//w w  w .  j a va2 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. 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() {
    /*//from  ww  w.ja v  a 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.wso2.ppaas.configurator.tests.ConfiguratorTestManager.java

/**
 * Execute shell command//from ww w .j ava  2s  . com
 *
 * @param commandText
 */
protected int executeCommand(final String commandText, Map<String, String> environment) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    int result;
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(ConfiguratorTestManager.class.getResource(PATH_SEP).getPath() + ".."
                + PATH_SEP + CONFIGURATOR_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        result = exec.execute(commandline, environment);

    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.xdi.util.process.ProcessHelper.java

/**
 * /* w  w  w.j a v  a 2  s .co  m*/
 * @param printJobTimeout
 *            the printJobTimeout (ms) before the watchdog terminates the
 *            print process
 * @param printInBackground
 *            printing done in the background or blocking
 * @param streamHandler
 * @return a print result handler (implementing a future)
 * @throws IOException
 *             the test failed
 */
public static PrintResultHandler executeProgram(CommandLine commandLine, String workingDirectory,
        long printJobTimeout, boolean printInBackground, int successExitValue,
        ExecuteStreamHandler streamHandler) throws IOException {
    ExecuteWatchdog watchdog = null;
    PrintResultHandler resultHandler;

    // Create the executor and consider the successExitValue as success
    Executor executor = new DefaultExecutor();
    executor.setExitValue(successExitValue);

    if (StringHelper.isNotEmpty(workingDirectory)) {
        executor.setWorkingDirectory(new File(workingDirectory));
    }

    // Redirect streams if needed
    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    // Create a watchdog if requested
    if (printJobTimeout > 0) {
        watchdog = new ExecuteWatchdog(printJobTimeout);
        executor.setWatchdog(watchdog);
    }

    // Pass a "ExecuteResultHandler" when doing background printing
    if (printInBackground) {
        log.debug(String.format("Executing non-blocking process %s", commandLine.toString()));
        resultHandler = new PrintResultHandler(watchdog);
        executor.execute(commandLine, resultHandler);
    } else {
        log.debug(String.format("Executing blocking process %s", commandLine.toString()));
        successExitValue = executor.execute(commandLine);
        resultHandler = new PrintResultHandler(successExitValue);
    }

    return resultHandler;
}

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

/**
 * Builds an Executor which will output to the specified OutputStream.
 * <p>//from  w  w w  .j a v  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:org.zanata.sync.jobs.utils.ProcessUtils.java

public static List<String> runNativeCommand(Path workingDir, long timeoutInMilli, String... commands) {
    Preconditions.checkArgument(commands != null && commands.length > 0, "You must provide commands to run");

    CommandLine commandLine = CommandLine.parse(commands[0]);
    ImmutableList<String> args = ImmutableList.copyOf(commands).subList(1, commands.length);
    for (String arg : args) {
        commandLine.addArgument(arg);// w  w  w .j  a  v  a  2 s. c  om
    }

    Executor executor = new DefaultExecutor();

    ImmutableList.Builder<String> output = ImmutableList.builder();
    executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
        @Override
        protected void processLine(String line, int logLevel) {
            log.info(line);
            output.add(line);
        }
    }));
    ExecuteWatchdog watchDog = new ExecuteWatchdog(timeoutInMilli);
    executor.setWatchdog(watchDog);
    executor.setWorkingDirectory(workingDir.toFile());
    executor.setProcessDestroyer(PROCESS_DESTROYER);

    try {
        int exitCode = executor.execute(commandLine);
        if (Execute.isFailure(exitCode) && watchDog.killedProcess()) {
            // it was killed on purpose by the watchdog
            log.error("process {} taking too long to run and killed by watchdog", commandLine);
        }
    } catch (IOException e) {
        log.error("error running:{}", commandLine);
        throw Throwables.propagate(e);
    }

    return output.build();
}

From source file:ro.cosu.vampires.client.executors.fork.ForkExecutor.java

@Override
public Result execute(Computation computation) {

    acquireResources();/*from ww w .  j  a v a  2  s. c  o m*/

    CommandLine commandLine = getCommandLine(computation.command());

    CollectingLogOutputStream collectingLogOutputStream = new CollectingLogOutputStream();
    PumpStreamHandler handler = new PumpStreamHandler(collectingLogOutputStream);
    executor.setStreamHandler(handler);
    executor.setWatchdog(new ExecuteWatchdog(TIMEOUT_IN_MILIS));
    executor.setWorkingDirectory(Paths.get("").toAbsolutePath().toFile());

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    LocalDateTime start = LocalDateTime.now();
    int exitCode;
    try {
        executor.execute(commandLine, resultHandler);
    } catch (IOException e) {
        LOG.error("failed to exec", resultHandler.getException());
    }

    try {
        resultHandler.waitFor();
    } catch (InterruptedException e) {
        LOG.error("failed to exec", resultHandler.getException());
    }

    exitCode = resultHandler.hasResult() ? resultHandler.getExitValue() : -1;

    //TODO take different action for failed commands so we can collect the output (stderr or java exception)

    LocalDateTime stop = LocalDateTime.now();

    long duration = Duration.between(start, stop).toMillis();

    releaseResources();
    return Result.builder().duration(duration).exitCode(exitCode).trace(getTrace(start, stop))
            .output(collectingLogOutputStream.getLines()).build();

}