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:io.vertx.config.vault.utils.VaultProcess.java

public void runAndProcess(String command, Consumer<String> processor) {
    String cli = executable.getAbsolutePath() + " " + command;
    System.out.println(">> " + cli);
    CommandLine parse = CommandLine.parse(cli);
    DefaultExecutor executor = new DefaultExecutor();
    PumpStreamHandler pump = new PumpStreamHandler(new VaultOutputStream().addExtractor(processor), System.err);

    ExecuteWatchdog watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchDog);//w  w w  . j  a  v  a  2s.  c o m
    executor.setStreamHandler(pump);
    try {
        executor.execute(parse);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.tascape.qa.th.android.comm.Adb.java

public ExecuteWatchdog adbAsync(final List<Object> arguments, long timeoutMillis) throws IOException {
    CommandLine cmdLine = new CommandLine(ADB);
    if (!this.serial.isEmpty()) {
        cmdLine.addArgument("-s");
        cmdLine.addArgument(serial);/*from w w w .j  a va  2  s  .  com*/
    }
    arguments.forEach((arg) -> {
        cmdLine.addArgument(arg + "");
    });
    LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " "));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis);
    Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new ESH());
    executor.execute(cmdLine, new DefaultExecuteResultHandler());

    return watchdog;
}

From source file:com.jaeksoft.searchlib.ocr.OcrManager.java

private final int run(CommandLine cmdLine, int secTimeOut, Integer expectedExitValue,
        StringBuilder returnedText) throws IOException, SearchLibException {
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//from   ww w  .j  a  v a2 s . co  m
        Logging.info("LOG OCR: " + cmdLine);
        PumpStreamHandler streamHandler = new PumpStreamHandler(baos);
        executor.setStreamHandler(streamHandler);
        if (expectedExitValue != null)
            executor.setExitValue(expectedExitValue);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(secTimeOut * 1000);
        executor.setWatchdog(watchdog);
        int ev = executor.execute(cmdLine);
        if (expectedExitValue != null)
            if (ev != expectedExitValue)
                throw new SearchLibException("Bad exit value (" + ev + ") ");
        if (returnedText != null)
            returnedText.append(baos.toString("UTF-8"));
        return ev;
    } finally {
        if (baos != null)
            IOUtils.closeQuietly(baos);
    }
}

From source file:io.selendroid.android.impl.AbstractDevice.java

private void startLogging() {
    logoutput = new ByteArrayOutputStream();
    DefaultExecutor exec = new DefaultExecutor();
    exec.setStreamHandler(new PumpStreamHandler(logoutput));
    CommandLine command = adbCommand("logcat", "ResourceType:S", "dalvikvm:S", "Trace:S", "SurfaceFlinger:S",
            "StrictMode:S", "ExchangeService:S", "SVGAndroid:S", "skia:S", "LoaderManager:S",
            "ActivityThread:S", "-v", "time");
    log.info("starting logcat:");
    log.fine(command.toString());/*from  w ww. ja  va  2  s  .  c o  m*/
    try {
        exec.execute(command, new DefaultExecuteResultHandler());
        logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        exec.setWatchdog(logcatWatchdog);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:hr.fer.zemris.vhdllab.service.impl.GhdlSimulator.java

private List<String> executeProcess(CommandLine cl, java.io.File tempDirectory)
        throws ExecuteException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Executing process: " + cl.toString());
    }//from w w  w  . j  a  va2s .co  m

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ExecuteStreamHandler handler = new PumpStreamHandler(bos);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(PROCESS_TIMEOUT);
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(tempDirectory);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(handler);
    /*
     * It seems that when ExecuteWatchdog terminates process by invoking
     * destroy method, process terminates with exit code 143. And since we
     * manually ask watchdog if he killed the process, exit code 143 is
     * marked as successful (just so our code can be executed).
     * 
     * Exit code 1 in case of compilation error(s).
     */
    executor.setExitValues(new int[] { 0, 1, 143 });
    try {
        executor.execute(cl);
    } catch (ExecuteException e) {
        LOG.warn("Process output dump:\n" + bos.toString());
        throw e;
    }

    if (watchdog.killedProcess()) {
        throw new SimulatorTimeoutException(PROCESS_TIMEOUT);
    }
    String output;
    try {
        output = bos.toString(IOUtil.DEFAULT_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new UnhandledException(e);
    }
    if (StringUtils.isBlank(output)) {
        return Collections.emptyList();
    }
    return Arrays.asList(StringUtil.splitToNewLines(output));
}

From source file:edu.stolaf.cs.wmrserver.TransformProcessor.java

private File compile(SubnodeConfiguration languageConf, String transformTypeString, File srcTransformFile,
        File jobTransformDir) throws CompilationException, IOException {
    // Determine correct compiler, returning if none specified
    String compiler = languageConf.getString("compiler-" + transformTypeString, "");
    if (compiler.isEmpty())
        compiler = languageConf.getString("compiler", "");
    if (compiler.isEmpty())
        return srcTransformFile;

    // Determine destination filename
    File compiledTransformFile = new File(jobTransformDir, "compiled-job-" + transformTypeString);

    // Create map to replace ${wmr:...} variables.
    // NOTE: Commons Configuration's built-in interpolator does not work here
    //  for some reason.
    File jobTempDir = getJobTempDir();
    Hashtable<String, String> variableMap = new Hashtable<String, String>();
    File libDir = getLibraryDirectory(languageConf);
    variableMap.put("wmr:lib.dir", (libDir != null) ? libDir.toString() : "");
    variableMap.put("wmr:src.dir", relativizeFile(srcTransformFile.getParentFile(), jobTempDir).toString());
    variableMap.put("wmr:src.file", relativizeFile(srcTransformFile, jobTempDir).toString());
    variableMap.put("wmr:dest.dir", relativizeFile(jobTransformDir, jobTempDir).toString());
    variableMap.put("wmr:dest.file", relativizeFile(compiledTransformFile, jobTempDir).toString());

    // Replace variables in compiler string
    compiler = StrSubstitutor.replace(compiler, variableMap);

    // Run the compiler

    CommandLine compilerCommand = CommandLine.parse(compiler);
    DefaultExecutor exec = new DefaultExecutor();
    ExecuteWatchdog dog = new ExecuteWatchdog(60000); // 1 minute
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler pump = new PumpStreamHandler(output);
    exec.setWorkingDirectory(jobTempDir);
    exec.setWatchdog(dog);//from   www. j  av a2s. com
    exec.setStreamHandler(pump);
    exec.setExitValues(null); // Can't get the exit code if it throws exception

    int exitStatus = -1;
    try {
        exitStatus = exec.execute(compilerCommand);
    } catch (IOException ex) {
        // NOTE: Exit status is still -1 in this case, since exception was thrown
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));
    }

    // Check for successful exit

    if (exitStatus != 0)
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));

    // Check that output exists and is readable, and make it executable

    if (!compiledTransformFile.isFile())
        throw new CompilationException(
                "Compiler did not output a " + transformTypeString
                        + " executable (or it was not a regular file).",
                exitStatus, new String(output.toByteArray()));

    if (!compiledTransformFile.canRead())
        throw new IOException(StringUtils.capitalize(transformTypeString)
                + " executable output from compiler was not readable: " + compiledTransformFile.toString());

    if (!compiledTransformFile.canExecute())
        compiledTransformFile.setExecutable(true, false);

    return compiledTransformFile;
}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private DefaultExecuteResultHandler executeFFmpeg(final CommandLine command, final int timeoutSeconds,
        final PumpStreamHandler streamHandler) throws IOException {
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutSeconds * 1000);
    final Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);/* w  ww .j  av a  2  s.c o  m*/

    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(command, resultHandler);

    return resultHandler;
}

From source file:com.boundlessgeo.wps.grass.GrassProcesses.java

/**
 * Define a GISBASE/LOCATION_NAME/PERMANENT for the provided dem.
 *
 * The dem is staged in GISBASE/dem.tif and then moved to
 * GISBASE/LOCATION_NAME/PERMANENT/dem.tif
 *
 * @param operation//from   w  w  w .j av  a 2 s  .c  om
 *            Name used for the location on disk
 * @param dem
 *            File used to establish CRS and Bounds for the location
 * @return Array of files consisting of {GISBASE, LOCATION, MAPSET, dem.tif}
 * @throws Exception
 */
static File location(File location, File raster) throws Exception {
    // grass70 + ' -c ' + myfile + ' -e ' + location_path
    CommandLine cmd = new CommandLine(EXEC);
    cmd.addArgument("-c");
    cmd.addArgument("${raster}");
    cmd.addArgument("-e");
    cmd.addArgument("${location}");
    cmd.setSubstitutionMap(new KVP("raster", raster, "location", location));
    LOGGER.info(cmd.toString());

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new PumpStreamHandler(System.out));

    LOGGER.info(cmd.toString());
    try {
        int exitValue = executor.execute(cmd);
    } catch (ExecuteException fail) {
        LOGGER.warning("grass70:" + fail.getLocalizedMessage());
        throw fail;
    }

    File mapset = new File(location, "PERMANENT");
    if (!mapset.exists()) {
        throw new IllegalStateException("Did not create mapset " + mapset);
    }
    return location;
}

From source file:it.drwolf.ridire.index.cwb.CWBFrequencyList.java

private String getFrequencyList(boolean deleteFLFile, List<String> semDescription, List<String> funDescription,
        int quantityP, String type, Integer threshold, boolean sorted) {
    CommandLine commandLine = CommandLine.parse(this.cwbscanExecutable);
    commandLine.addArgument("-q");
    if (threshold != null && threshold > 0) {
        commandLine.addArgument("-f");
        commandLine.addArgument(threshold + "");
    }//  ww  w.j a  v a 2 s . c  o  m
    commandLine.addArgument("-r").addArgument(this.cqpRegistry);
    commandLine.addArgument("-C");
    commandLine.addArgument(this.cqpCorpusName);
    if (type.equals("forma")) {
        commandLine.addArgument("word+0");
    } else if (type.equals("PoS")) {
        commandLine.addArgument("pos+0");
    } else if (type.equals("easypos")) {
        commandLine.addArgument("easypos+0");
    } else if (type.equals("lemma")) {
        commandLine.addArgument("lemma+0");
    } else if (type.equals("PoS-forma")) {
        commandLine.addArgument("pos+0");
        commandLine.addArgument("word+0");
    } else if (type.equals("PoS-lemma")) {
        commandLine.addArgument("pos+0");
        commandLine.addArgument("lemma+0");
    }
    String semFuncParam = "";
    if (funDescription != null && funDescription.size() > 0 && funDescription.get(0) != null
            && funDescription.get(0).trim().length() > 0
            || semDescription != null && semDescription.size() > 0 && semDescription.get(0) != null
                    && semDescription.get(0).trim().length() > 0) {
        semFuncParam = "?";
        if (funDescription != null && funDescription.size() > 0 && funDescription.get(0) != null
                && funDescription.get(0).trim().length() > 0) {
            String fd = StringUtils.join(funDescription, "\\|");
            semFuncParam += "text_functional=/\\(" + fd + "\\)/ ";
        }
        if (semDescription != null && semDescription.size() > 0 && semDescription.get(0) != null
                && semDescription.get(0).trim().length() > 0) {
            String sd = StringUtils.join(semDescription, "\\|");
            semFuncParam += "text_semantic=/\\(" + sd + "\\)/ ";

        }
        commandLine.addArgument(semFuncParam);
    }
    if (sorted) {
        commandLine.addArgument("|");
        commandLine.addArgument("sort");
        commandLine.addArgument("-nr");
        commandLine.addArgument("-k");
        commandLine.addArgument("1");
    }
    if (quantityP > 0) {
        commandLine.addArgument("|");
        commandLine.addArgument("head");
        commandLine.addArgument("-" + quantityP);
    }
    File flTempFile = null;
    try {
        flTempFile = File.createTempFile("ridireFL", null);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    commandLine.addArgument(" > ");
    commandLine.addArgument(flTempFile.getAbsolutePath());
    String c = commandLine.toString();
    try {
        File tempSh = File.createTempFile("ridireSH", ".sh");
        FileUtils.writeStringToFile(tempSh, c);
        tempSh.setExecutable(true);
        commandLine = CommandLine.parse(tempSh.getAbsolutePath());
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBFrequencyList.TIMEOUT);
        executor.setWatchdog(watchdog);
        ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
        ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream(1024);
        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, baosStdErr, null);
        executor.setStreamHandler(executeStreamHandler);
        int exitValue = 0;
        exitValue = executor.execute(commandLine);
        FileUtils.deleteQuietly(tempSh);
        if (exitValue == 0) {
            StrTokenizer strTokenizer = new StrTokenizer();
            this.frequencyList = new ArrayList<FrequencyItem>();
            List<String> lines = FileUtils.readLines(flTempFile);
            for (String line : lines) {
                strTokenizer.reset(line);
                String[] tokens = strTokenizer.getTokenArray();
                if (tokens.length == 2) {
                    FrequencyItem frequencyItem = new FrequencyItem(tokens[1],
                            Integer.parseInt(tokens[0].trim()));
                    this.frequencyList.add(frequencyItem);
                } else if (tokens.length == 3) {
                    FrequencyItem frequencyItem = new FrequencyItem(tokens[2], tokens[1],
                            Integer.parseInt(tokens[0].trim()));
                    this.frequencyList.add(frequencyItem);
                }
            }
            if (deleteFLFile) {
                FileUtils.deleteQuietly(flTempFile);
            }
        }
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return flTempFile.getAbsolutePath();
}

From source file:it.drwolf.ridire.session.async.Mapper.java

private StringWithEncoding createPlainTextResource(File f, CrawledResource cr, EntityManager entityManager)
        throws SAXException, TikaException, IOException, TransformerConfigurationException,
        InterruptedException {//w w  w  .  jav a 2 s  . c o  m
    File resourceDir = new File(FilenameUtils.getFullPath(f.getCanonicalPath().replaceAll("__\\d+", ""))
            + JobMapperMonitor.RESOURCESDIR);
    String alchemyKey = entityManager.find(Parameter.class, Parameter.ALCHEMY_KEY.getKey()).getValue();
    String readabilityKey = entityManager.find(Parameter.class, Parameter.READABILITY_KEY.getKey()).getValue();
    String resourceFileName = cr.getDigest() + ".gz";
    File resourceFile = new File(resourceDir, resourceFileName);
    StringWithEncoding rawContentAndEncoding = null;
    String contentType = cr.getContentType();
    // long t1 = System.currentTimeMillis();
    if (contentType != null && contentType.contains("application/msword")) {
        rawContentAndEncoding = this.transformDOC2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("application/rtf")) {
        rawContentAndEncoding = this.transformRTF2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("text/plain")) {
        // txt -> html -> txt is for txt cleaning
        rawContentAndEncoding = this.transformTXT2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("pdf")) {
        rawContentAndEncoding = this.transformPDF2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("html")) {
        rawContentAndEncoding = this.getGuessedEncodingAndSetRawContentFromGZFile(resourceFile);
    }
    // long t2 = System.currentTimeMillis();
    // System.out.println("Transformation: " + (t2 - t1));
    if (rawContentAndEncoding != null) {
        if (rawContentAndEncoding.getEncoding() == null) {
            rawContentAndEncoding = new StringWithEncoding(rawContentAndEncoding.getString(), "UTF8");
        }
        // t1 = System.currentTimeMillis();
        String cleanText = this.replaceUnsupportedChars(rawContentAndEncoding.getString());
        rawContentAndEncoding = new StringWithEncoding(cleanText, rawContentAndEncoding.getEncoding());
        File tmpFile = File.createTempFile("ridire", null);
        FileUtils.writeStringToFile(tmpFile, rawContentAndEncoding.getString(), "UTF-8");
        String ridireCleanerJar = entityManager
                .find(CommandParameter.class, CommandParameter.RIDIRE_CLEANER_EXECUTABLE_KEY).getCommandValue();
        String host = entityManager.find(Parameter.class, Parameter.READABILITY_HOSTAPP.getKey()).getValue();
        CommandLine commandLine = CommandLine
                .parse("java -Xmx128m -Djava.io.tmpdir=" + this.tempDir + " -jar " + ridireCleanerJar);
        commandLine.addArgument("-f");
        commandLine.addArgument(tmpFile.getPath());
        commandLine.addArgument("-e");
        commandLine.addArgument("UTF-8");
        commandLine.addArgument("-h");
        commandLine.addArgument(host);
        commandLine.addArgument("-k");
        commandLine.addArgument(alchemyKey);
        commandLine.addArgument("-r");
        commandLine.addArgument(readabilityKey);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.READABILITY_TIMEOUT);
        executor.setWatchdog(watchdog);
        ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
        ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream(1024);
        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, baosStdErr, null);
        executor.setStreamHandler(executeStreamHandler);
        int exitValue = executor.execute(commandLine);
        if (exitValue == 0) {
            rawContentAndEncoding = new StringWithEncoding(baosStdOut.toString(), "UTF-8");
            // TODO filter real errors
            rawContentAndEncoding.setCleaner(baosStdErr.toString().trim());
        }
        FileUtils.deleteQuietly(tmpFile);
    }
    return rawContentAndEncoding;
}