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.selendroid.standalone.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 w w  .ja v a2  s.c  om
    try {
        exec.execute(command, new DefaultExecuteResultHandler());
        logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        exec.setWatchdog(logcatWatchdog);
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:com.github.cshubhamrao.MediaConverter.MainUI.java

/** Runs ffmpeg -version */
@Override/*  w  w  w  .  ja v  a  2  s  . com*/
protected Void doInBackground() {
    ffmpeg = FFMpegLoader.getFFMpegExecutable();
    if (ffmpeg != null) {
        try {
            cmd = new CommandLine(ffmpeg);
            cmd.addArgument("-version");
            OutputStream outputStream = new ByteArrayOutputStream();
            DefaultExecutor exec = new DefaultExecutor();
            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
            exec.setStreamHandler(streamHandler);
            ExecuteWatchdog watchdog = new ExecuteWatchdog(10000);
            exec.setWatchdog(watchdog);
            exec.execute(cmd);
            publish(outputStream.toString());
        } catch (ExecuteException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

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//w  w w .j  ava2  s.  co  m
 *            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(String operation, GridCoverage2D dem) throws Exception {
    File geodb = new File(System.getProperty("user.home"), "grassdata");
    //File location = Files.createTempDirectory(geodb.toPath(),operation).toFile();
    File location = new File(geodb, operation);
    File mapset = new File(location, "PERMANENT");
    File file = new File(geodb, "dem.tif");

    final GeoTiffFormat format = new GeoTiffFormat();
    GridCoverageWriter writer = format.getWriter(file);
    writer.write(dem, null);
    System.out.println("Staging file:" + file);

    // grass70 + ' -c ' + myfile + ' -e ' + location_path
    CommandLine cmd = new CommandLine(EXEC);
    cmd.addArgument("-c");
    cmd.addArgument("${file}");
    cmd.addArgument("-e");
    cmd.addArgument("${location}");
    cmd.setSubstitutionMap(new KVP("file", file, "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));
    int exitValue = executor.execute(cmd);

    File origional = file;
    file = new File(mapset, file.getName());
    Files.move(origional.toPath(), file.toPath());
    return new File[] { geodb, location, mapset, file };
}

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

/**
 * Define a GISBASE/LOCATION_NAME for the provided dem.
 *
 * @param operation Name used for the location on disk
 * @param dem File used to establish CRS and Bounds for the location
 * @return/*w  w  w.  j a v a2s  .co m*/
 * @throws Exception
 */
static File location(CoordinateReferenceSystem crs) throws Exception {
    String code = CRS.toSRS(crs, true);
    File geodb = new File(System.getProperty("user.home"), "grassdata");
    File location = Files.createTempDirectory(geodb.toPath(), code).toFile();
    KVP kvp = new KVP("geodb", geodb, "location", location);

    // grass70 + ' -c epsg:' + myepsg + ' -e ' + location_path
    CommandLine cmd = new CommandLine(EXEC);
    cmd.addArgument("-c");
    cmd.addArgument("epsg:" + code);
    cmd.addArgument("-e");
    cmd.addArgument("${location}");
    cmd.setSubstitutionMap(kvp);

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

    int exitValue = executor.execute(cmd);
    return location;
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Invoke TG admin synchronously. /*from   w  ww .  java 2 s  .co m*/
 * Admin operation blocks until it is completed.
 * 
 * @param tgHome TG admin home
 * @param url Url to connect to TG server
 * @param user System User name
 * @param pwd System User password
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param cmd TG admin command file or command string
 * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB)
 * @param timeout Number of milliseconds allowed to complete admin operation
 * 
 * @return Output console of admin operation 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String invoke(String tgHome, String url, String user, String pwd, String logFile, String logLevel,
        String cmd, int memSize, long timeout) throws TGAdminException {
    if (tgHome == null)
        throw new TGAdminException("TGAdmin - TGDB home is not defined");
    File ftgHome = new File(tgHome);
    if (!ftgHome.exists())
        throw new TGAdminException("TGAdmin - TGDB home '" + tgHome + "' does not exist");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(tgHome + "/bin"));

    CommandLine tgCL = new CommandLine((new File(tgHome + "/bin/" + process)).getAbsolutePath());

    // Define arguments
    List<String> args = new ArrayList<String>();
    if (url != null) {
        args.add("--url");
        args.add(url);
    }
    if (user != null) {
        args.add("--uid");
        args.add(user);
    }
    if (pwd != null) {
        args.add("--pwd");
        args.add(pwd);
    }
    if (logFile != null) {
        args.add("--log");
        args.add(logFile);
    }
    if (logLevel != null) {
        args.add("--log-level");
        args.add(logLevel);
    }
    if (memSize >= 0) {
        args.add("--max-memory");
        args.add(Integer.toString(memSize));
    }

    File cmdFile = null;
    if (cmd == null)
        throw new TGAdminException("TGAdmin - Command is required.");
    if (cmd.matches(
            "(?s)^(kill|show|describe|create|stop|info|checkpoint|dump|set|connect|disconnect|export|import|exit).*$")) {
        try {
            cmdFile = new File(tgHome + "/invokeAdminScript.txt");
            Files.write(Paths.get(cmdFile.toURI()), cmd.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ioe) {
            throw new TGAdminException("TGAdmin - " + ioe.getMessage());
        }
    } else {
        cmdFile = new File(cmd);
    }

    if (!cmdFile.exists()) {
        throw new TGAdminException("TGAdmin - Command file '" + cmdFile + "' does not exist");
    }
    args.add("--file");
    args.add(cmdFile.getAbsolutePath());

    tgCL.addArguments((String[]) args.toArray(new String[args.size()]));

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " "));

    long endProcTime = 0;
    long totalProcTime = 0;
    try {
        TGAdmin.startProcTime = System.currentTimeMillis();
        tgExec.execute(tgCL);
        endProcTime = System.currentTimeMillis();
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms",
                    output.toString());
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up
            } catch (InterruptedException ie) {
                ;
            }
            throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString());
        }
    }
    if (url != null && !output.toString().contains("Successfully connected to server"))
        throw new TGAdminException("TGAdmin - Admin could not connect to server " + url + " with user " + user,
                output.toString());
    if (endProcTime != 0)
        totalProcTime = endProcTime - TGAdmin.startProcTime;
    if (TGAdmin.showOperationBanner)
        System.out.println(
                "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    return output.toString();
}

From source file:com.datastax.driver.core.CCMBridge.java

private String execute(String command, Object... args) {
    String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
    Closer closer = Closer.create();//from ww  w . j  a  va2 s  . c om
    // 10 minutes timeout
    ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.MINUTES.toMillis(10));
    StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);
    closer.register(pw);
    try {
        logger.trace("Executing: " + fullCommand);
        CommandLine cli = CommandLine.parse(fullCommand);
        Executor executor = new DefaultExecutor();
        LogOutputStream outStream = new LogOutputStream() {
            @Override
            protected void processLine(String line, int logLevel) {
                String out = "ccmout> " + line;
                logger.debug(out);
                pw.println(out);
            }
        };
        LogOutputStream errStream = new LogOutputStream() {
            @Override
            protected void processLine(String line, int logLevel) {
                String err = "ccmerr> " + line;
                logger.error(err);
                pw.println(err);
            }
        };
        closer.register(outStream);
        closer.register(errStream);
        ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream);
        executor.setStreamHandler(streamHandler);
        executor.setWatchdog(watchDog);
        int retValue = executor.execute(cli, ENVIRONMENT_MAP);
        if (retValue != 0) {
            logger.error("Non-zero exit code ({}) returned from executing ccm command: {}", retValue,
                    fullCommand);
            pw.flush();
            throw new CCMException(
                    String.format("Non-zero exit code (%s) returned from executing ccm command: %s", retValue,
                            fullCommand),
                    sw.toString());
        }
    } catch (IOException e) {
        if (watchDog.killedProcess())
            logger.error("The command {} was killed after 10 minutes", fullCommand);
        pw.flush();
        throw new CCMException(String.format("The command %s failed to execute", fullCommand), sw.toString(),
                e);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            Throwables.propagate(e);
        }
    }
    return sw.toString();
}

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

private File tabulate() throws IOException {
    EnvironmentUtils.addVariableToEnvironment(EnvironmentUtils.getProcEnvironment(), "LC_ALL=C");
    File tmpAwk = File.createTempFile("ridireAWK", ".awk");
    String awk = this.createAWKString();
    FileUtils.writeStringToFile(tmpAwk, awk);
    File tmpTabulate = File.createTempFile("ridireTAB", ".tab");
    String tabulate = this.createTabulateString(tmpAwk, tmpTabulate);
    File tempSh = File.createTempFile("ridireSH", ".sh");
    FileUtils.writeStringToFile(tempSh, tabulate);
    tempSh.setExecutable(true);//from w ww. j  a  v a 2 s  . com
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBCollocatesExtractor.CWB_COLLOCATES_EXTRACTOR_TIMEOUT);
    executor.setWatchdog(watchdog);
    CommandLine commandLine = new CommandLine(this.cqpExecutable);
    commandLine.addArgument("-f").addArgument(tempSh.getAbsolutePath()).addArgument("-D")
            .addArgument(this.cqpCorpusName).addArgument("-r").addArgument(this.cqpRegistry);
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tmpAwk);
    FileUtils.deleteQuietly(tempSh);
    return tmpTabulate;
}

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

private Integer getCQPQueryResultsSize(File queryFile, String cqpSizeQuery)
        throws ExecuteException, IOException {
    EnvironmentUtils.addVariableToEnvironment(EnvironmentUtils.getProcEnvironment(), "LC_ALL=C");
    Executor executor = new DefaultExecutor();
    File tempSize = File.createTempFile("ridireSZ", ".size");
    File tempSh = File.createTempFile("ridireSH", ".sh");
    CommandLine commandLine = new CommandLine(this.cqpExecutable);
    commandLine.addArgument("-f").addArgument(queryFile.getAbsolutePath()).addArgument("-D")
            .addArgument(this.cqpCorpusName).addArgument("-r").addArgument(this.cqpRegistry);
    String commLineString = commandLine.toString() + " > " + tempSize.getAbsolutePath();
    FileUtils.writeStringToFile(tempSh, commLineString);
    tempSh.setExecutable(true);/*from   w ww  .  j av a 2 s . c o  m*/
    executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBPatternSearcher.TIMEOUT);
    executor.setWatchdog(watchdog);
    commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    Integer size = 0;
    List<String> lines = FileUtils.readLines(tempSize);
    if (lines.size() > 0) {
        size = Integer.parseInt(lines.get(0).trim());
    }
    FileUtils.deleteQuietly(tempSh);
    FileUtils.deleteQuietly(tempSize);
    return size;
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Initialize the TG server synchronously. This Init operation blocks until
 * it is completed.//from   w ww  .  j  a  va2  s.c om
 * 
 * @param initFile
 *            TG server init config file
 * @param forceCreation
 *            Force creation. Delete all the data in the db directory first.
 * @param timeout
 *            Number of milliseconds allowed to initialize the server
 * @return the output stream of init operation 
 * @throws TGInitException
 *             Init operation fails or timeout occurs 
 */
public String init(String initFile, boolean forceCreation, long timeout) throws TGInitException {

    File initF = new File(initFile);
    if (!initF.exists())
        throw new TGInitException("TGServer - Init file '" + initFile + "' does not exist");
    try {
        this.setInit(initF);
    } catch (TGGeneralException e) {
        throw new TGInitException(e.getMessage());
    }

    //ByteArrayOutputStream output = new ByteArrayOutputStream();

    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    if (forceCreation)
        tgCL.addArguments(new String[] { "-i", "-f", "-Y", "-c", initFile, "-l", this.initLogFileBase });
    else
        tgCL.addArguments(new String[] { "-i", "-Y", "-c", initFile, "-l", this.initLogFileBase });

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGServer - Initializing " + StringUtils.toString(tgCL.toStrings(), " "));
    String output = "";
    try {
        tgExec.execute(tgCL);
        output = new String(Files.readAllBytes(Paths.get(this.getInitLogFile().toURI())));
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGInitException("TGServer - Init did not complete within " + timeout + " ms");
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up

            } catch (InterruptedException ie) {
                ;
            }
            throw new TGInitException("TGServer - Init failed: " + ee.getMessage(), output);
        }
    }
    try {
        this.setBanner(output);
    } catch (TGGeneralException tge) {
        throw new TGInitException(tge.getMessage());
    }

    if (output.contains("TGSuccess")) {
        System.out.println("TGServer - Initialized successfully");
        return output;
    } else
        throw new TGInitException("TGServer - Init failed", output);
}

From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java

/**
 * This calls a TIBCO binary.//from w  w w.j  a  v  a2  s  . c  om
 * 
 * @param binary, the TIBCO binary file to execute
 * @param tras, the TRA files associated with the TIBCO binary
 * @param arguments, command-line arguments
 * @param workingDir, working directory from where the binary is launched
 * @param errorMsg, error message to display in case of a failure
 * @param fork, if true the chiild process will be detached from the caller
 * 
 * @throws IOException
 * @throws MojoExecutionException
 */
protected int launchTIBCOBinary(File binary, List<File> tras, ArrayList<String> arguments, File workingDir,
        String errorMsg, boolean fork, boolean synchronous) throws IOException, MojoExecutionException {
    Integer result = 0;

    if (tras == null) { // no value specified as Mojo parameter, we use the .tra in the same directory as the binary
        String traPathFileName = binary.getAbsolutePath();
        traPathFileName = FilenameUtils.removeExtension(traPathFileName);
        traPathFileName += ".tra";
        tras = new ArrayList<File>();
        tras.add(new File(traPathFileName));
    }

    HashMap<File, File> trasMap = new HashMap<File, File>();
    for (File tra : tras) {
        // copy of ".tra" file in the working directory
        File tmpTRAFile = new File(directory, tra.getName());
        trasMap.put(tra, tmpTRAFile);
        copyFile(tra, tmpTRAFile);
    }

    for (File tra : trasMap.keySet()) {
        if (trasMap.containsKey(tibcoDesignerTRAPath)
                && ((tibcoBuildEARUseDesignerTRA && tra == tibcoBuildEARTRAPath)
                        || (tibcoBuildLibraryUseDesignerTRA && tra == tibcoBuildLibraryTRAPath))) {
            if (tras.size() > 1) {
                ReplaceRegExp replaceRegExp = new ReplaceRegExp();
                replaceRegExp.setFile(trasMap.get(tra));
                replaceRegExp.setMatch("tibco.include.tra (.*/designer.tra)");
                replaceRegExp.setReplace(
                        "tibco.include.tra " + trasMap.get(tibcoDesignerTRAPath).toString().replace('\\', '/'));
                replaceRegExp.setByLine(true);

                replaceRegExp.execute();
            }
        }

        if (tra == tibcoBuildEARTRAPath || tra == tibcoDesignerTRAPath || tra == tibcoBWEngineTRAPath) { // FIXME: should check more properly
            // append user.home at the end to force the use of custom Designer5.prefs
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(trasMap.get(tra), true)));
            out.println("");
            out.println("java.property.user.home=" + directory.getAbsolutePath().replace("\\", "/"));
            out.close();
        }
    }

    CommandLine cmdLine = new CommandLine(binary);

    for (String argument : arguments) {
        cmdLine.addArgument(argument);
    }
    getLog().debug("launchTIBCOBinary command line : " + cmdLine.toString());
    getLog().debug("working dir : " + workingDir);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(workingDir);

    if (timeOut > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut * 1000);
        executor.setWatchdog(watchdog);
    }

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    ByteArrayOutputStream stdOutAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdOutAndErr));

    if (fork) {
        CommandLauncher commandLauncher = CommandLauncherFactory.createVMLauncher();
        commandLauncher.exec(cmdLine, null, workingDir);
    } else {
        try {
            if (synchronous) {
                result = executor.execute(cmdLine);
            } else {
                executor.execute(cmdLine, new DefaultExecuteResultHandler());
            }
        } catch (ExecuteException e) {
            // TODO : grer erreurs des excutables (ventuellement parser les erreurs classiques)
            getLog().info(cmdLine.toString());
            getLog().info(stdOutAndErr.toString());
            getLog().info(result.toString());
            throw new MojoExecutionException(errorMsg, e);
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }

    return result;
}