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:eu.learnpad.verification.plugin.pn.modelcheckers.LOLA.java

public static String sync_getVerificationOutput(String lolaBinPath, String modelToVerify,
        String propertyToVerify, boolean useCoverabilitySearch, final int timeoutInSeconds) throws Exception {

    int cores = Runtime.getRuntime().availableProcessors();
    String filePath = System.getProperty("java.io.tmpdir") + "/" + java.util.UUID.randomUUID() + ".lola";
    IOUtils.writeFile(modelToVerify.getBytes(), filePath, false);
    //IOUtils.writeFile(propertyToVerify.getBytes(), filePath+".ctl", false);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = new CommandLine(lolaBinPath);

    cmdLine.addArgument("--nolog");

    //cmdLine.addArgument("--formula="+filePath+".ctl", false);
    cmdLine.addArgument("--formula=" + propertyToVerify, false);
    cmdLine.addArgument("--threads=" + cores);
    if (useCoverabilitySearch)
        cmdLine.addArgument("--search=cover");
    cmdLine.addArgument("-p");
    //cmdLine.addArgument("--path=\""+filePath+".out\"", false);
    //cmdLine.addArgument("--state=\""+filePath+".out\"", false);
    cmdLine.addArgument(filePath, false);

    DefaultExecutor exec = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(1000 * timeoutInSeconds);

    exec.setWatchdog(watchdog);//from  ww w.ja  v  a  2  s . co  m
    exec.setStreamHandler(streamHandler);
    exec.setExitValues(new int[] { 0, 1, 2, 139, 35584 });
    int exitVal = exec.execute(cmdLine);

    String output = outputStream.toString();

    if (watchdog.killedProcess())
        throw new Exception("ERROR: Timeout occurred. LOLA has reached the execution time limit of "
                + timeoutInSeconds + " seconds, so it has been aborted.\nPartial Output:\n" + output);

    if (exitVal != 0 || output.equals("") || output.contains("aborting [#"))
        throw new Exception("ERROR: LOLA internal error\nExit code:" + exitVal + "\nExec: " + cmdLine.toString()
                + "\nOutput:\n" + output);
    new File(filePath).delete();
    return output;
}

From source file:de.pawlidi.openaletheia.utils.exec.ProcessExecutor.java

/**
 * Creates executor with system watchdog for given output stream.
 * /* w  ww  . ja va2 s  . c  o  m*/
 * @param outputStream
 * @return
 */
private static Executor createExecutor(OutputStream outputStream) {

    // create process watchdog with timeout 60000 milliseconds
    ExecuteWatchdog watchdog = new ExecuteWatchdog(WATCHDOG_TIMEOUT);

    // set watchdog and stream handler
    Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new PumpStreamHandler(outputStream, outputStream));
    return executor;
}

From source file:com.stratio.explorer.shell.ShellInterpreter.java

@Override
public InterpreterResult interpret(String cmd) {
    logger.info("Run shell command '" + cmd + "'");
    long start = System.currentTimeMillis();
    CommandLine cmdLine = CommandLine.parse("bash");
    cmdLine.addArgument("-c", false);
    cmdLine.addArgument(cmd, false);/*w  w  w.  jav  a  2  s  .c  o m*/
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outputStream));

    executor.setWatchdog(new ExecuteWatchdog(CMD_TIMEOUT));
    try {
        int exitValue = executor.execute(cmdLine);
        return new InterpreterResult(InterpreterResult.Code.SUCCESS, outputStream.toString());
    } catch (ExecuteException e) {
        logger.error("Can not run " + cmd, e);
        return new InterpreterResult(Code.ERROR, e.getMessage());
    } catch (IOException e) {
        logger.error("Can not run " + cmd, e);
        return new InterpreterResult(Code.ERROR, e.getMessage());
    }
}

From source file:com.vmware.bdd.usermgmt.job.ChangeLocalAccountStateExecutor.java

private void changeLocalAccountState(String argument) {
    //String chefCmd = "sudo /opt/serengeti/sbin/set-password L";
    String sudoCmd = CommonUtil.getCustomizedSudoCmd();
    CommandLine cmdLine = new CommandLine(sudoCmd).addArgument(SET_PASSWORD_COMMAND).addArgument(argument);

    DefaultExecutor executor = new DefaultExecutor();

    executor.setStreamHandler(new PumpStreamHandler(new ExecOutputLogger(LOGGER, false), //output logger
            new ExecOutputLogger(LOGGER, true)) //error logger
    );/*from   ww w .j a v  a 2s.  c  o  m*/

    executor.setWatchdog(new ExecuteWatchdog(1000l * TIMEOUT));

    try {
        int exitVal = executor.execute(cmdLine);
        if (exitVal != 0) {
            throw new UserMgmtExecException("CHANGE_LOCAL_ACCOUNT_STATE_FAIL", null);
        }
    } catch (IOException e) {
        throw new UserMgmtExecException("CHANGE_LOCAL_ACCOUNT_STATE_FAIL", e);
    }
}

From source file:com.nts.alphamale.shell.AdbShellExecutor.java

/**
 * @param cmd adb /*ww  w.j a va 2  s .com*/
 * @param synch   ? ? true: synchronous, false: asynchronous
 * @param  (ms)
 * @return Executor Standard Output? Map
 */
public Map<String, Object> execute(CommandLine cmd, boolean synch, long timeoutMilliseconds) {
    Map<String, Object> executorMap = new HashMap<String, Object>();
    DefaultExecutor executor = new DefaultExecutor();
    PipedOutputStream pos = new PipedOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(pos, System.err);
    streamHandler.setStopTimeout(timeoutMilliseconds);
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(new PipedInputStream(pos));
    } catch (IOException e) {
        //log.error(e.getCause() + " : " + e.getMessage());
    }
    executor.setStreamHandler(streamHandler);
    ExecuteWatchdog watchDog = new ExecuteWatchdog(timeoutMilliseconds);
    executor.setWatchdog(watchDog);
    try {
        if (synch)
            executor.execute(cmd);
        else
            executor.execute(cmd, new DefaultExecuteResultHandler());

        log.debug(cmd.toString());
        LineIterator li = IOUtils.lineIterator(dis, "UTF-8");
        if (li != null) {
            executorMap.put("executor", executor);
            executorMap.put("stdOut", li);
        }
    } catch (Exception e) {
        log.error(e.getCause() + ":" + e.getMessage() + "[" + cmd + "]");
    }
    return executorMap;
}

From source file:de.akquinet.innovation.play.maven.Play2TestMojo.java

public void execute() throws MojoExecutionException {

    if (isSkipExecution()) {
        getLog().info("Test phase skipped");
        return;// w  w  w . jav  a  2 s .c  o m
    }

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("test");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);
    }

    executor.setWorkingDirectory(project.getBasedir());

    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        if (testFailureIgnore) {
            getLog().error("Test execution failures ignored");
        } else {
            throw new MojoExecutionException("Error during compilation", e);
        }
    }
}

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

/**
 * Execute an external command/*www .  j  a  va  2 s  . c o  m*/
 * @param cmd
 * @param tempDelay
 * @param correctValues
 * @param showOutput
 * @param realCommand
 * @return correctValues if ok, < 0 if an execution error occurs, or other error values
 */
public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput,
        String realCommand) {
    // Create command with parameters
    CommandLine commandLine = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        commandLine.addArgument(cmd.get(i));
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    ByteArrayOutputStream outputStream;
    outputStream = new ByteArrayOutputStream();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
    defaultExecutor.setStreamHandler(pumpStreamHandler);

    defaultExecutor.setExitValues(correctValues);
    AtomicBoolean isFinished = new AtomicBoolean(false);
    ExecuteWatchdog watchdog = null;
    Timer timer = null;
    if (tempDelay > 0) {
        // If delay (max time), then setup Watchdog
        timer = new Timer(true);
        watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        defaultExecutor.setWatchdog(watchdog);
        CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand);
        timer.schedule(endOfExecute, tempDelay);
    }
    int status = -1;
    try {
        // Execute the command
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            } catch (IOException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            }
        } else {
            pumpStreamHandler.stop();
            System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                    + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
            status = -2;
            try {
                outputStream.close();
            } catch (IOException e2) {
            }
            return status;
        }
    } catch (IOException e) {
        pumpStreamHandler.stop();
        System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
        status = -2;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
        return status;
    } finally {
        isFinished.set(true);
        if (timer != null) {
            timer.cancel();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e1) {
        }
    }
    pumpStreamHandler.stop();
    if (defaultExecutor.isFailure(status) && watchdog != null) {
        if (watchdog.killedProcess()) {
            // kill by the watchdoc (time out)
            if (showOutput) {
                System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out");
            }
        }
        status = -3;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    } else {
        if (showOutput) {
            System.out.println("Exec: " + outputStream.toString());
        }
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    }
    return status;
}

From source file:it.sonarlint.cli.tools.CommandExecutor.java

public int execute(String[] args, @Nullable Path workingDir, Map<String, String> addEnv) throws IOException {
    if (!Files.isExecutable(file)) {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    }//from  w  w  w  .ja v  a  2 s.c  om

    ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
        exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    Map<String, String> env = new HashMap<>(System.getenv());
    env.putAll(addEnv);
    return exec.execute(cmd, env);
}

From source file:hoot.services.nativeinterfaces.CommandRunnerImpl.java

@Override
public CommandResult exec(String[] command) throws IOException {
    logger.debug("Executing the following command: {}", Arrays.toString(command));

    try (OutputStream stdout = new ByteArrayOutputStream(); OutputStream stderr = new ByteArrayOutputStream()) {

        this.stdout = stdout;
        this.stderr = stderr;

        CommandLine cmdLine = new CommandLine(command[0]);
        for (int i = 1; i < command.length; i++) {
            cmdLine.addArgument(command[i], false);
        }/*from   www.j  a v  a 2 s.  c  o m*/

        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(stdout, stderr);
        DefaultExecutor executor = new DefaultExecutor();
        this.watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        executor.setWatchdog(this.watchDog);
        executor.setStreamHandler(executeStreamHandler);

        int exitValue;
        try {
            exitValue = executor.execute(cmdLine);

            if (executor.isFailure(exitValue) && this.watchDog.killedProcess()) {
                // it was killed on purpose by the watchdog
                logger.info("Process for '{}' command was killed!", cmdLine);
            }
        } catch (Exception e) {
            exitValue = -1;
            logger.warn("Error executing: {}", cmdLine, e);
        }

        CommandResult commandResult = new CommandResult(cmdLine.toString(), exitValue, stdout.toString(),
                stderr.toString());

        logger.debug("Finished executing: {}", commandResult);

        return commandResult;
    }
}

From source file:com.meltmedia.cadmium.blackbox.test.CliCommitCloneTest.java

/**
 * <p>Runs the Cadmium CLI command commit from Apache Commons Exec library. Then uses {@link CadmiumAssertions#assertContentDeployed(String, java.io.File, String)} to assert that the content deployed properly.</p>
 * <p>To override the site url, pass <code>-Dcom.meltmedia.cadmium.test.site.url=[URL]</code> to the jvm that this test case will be running in. The site url defaults to <code>http://localhost</code> if not set.</p>
 * @throws IOException See {@link DefaultExecutor#execute(CommandLine)} for more information.
 * @throws ExecuteException See {@link DefaultExecutor#execute(CommandLine)} for more information.
 * @throws InterruptedException // w ww.  ja  v  a  2 s. com
 * 
 * @see <a href="http://commons.apache.org/exec">Apache Commons Exec</a>
 */
@Test
public void testCommit() throws ExecuteException, IOException {
    String deployUrl = System.getProperty("com.meltmedia.cadmium.test.site.url", DEPLOY_URL);
    CommandLine commitCmd = CommandLine
            .parse("cadmium commit -m \"Testing commit command\" " + TEST_CONTENT_LOCATION + " " + deployUrl);

    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValue(0);
    ExecuteWatchdog watchDog = new ExecuteWatchdog(60000);
    exec.setWatchdog(watchDog);

    int exitValue = exec.execute(commitCmd);

    assertEquals("Commit command returned with an error status.", exitValue, 0);

    assertContentDeployed("Failed to commit content to remote site.", new File(TEST_CONTENT_LOCATION),
            DEPLOY_URL);
}