Example usage for org.apache.commons.exec DefaultExecutor execute

List of usage examples for org.apache.commons.exec DefaultExecutor execute

Introduction

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

Prototype

public int execute(final CommandLine command) throws ExecuteException, IOException 

Source Link

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);/*ww  w  .  j  a 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:com.sds.acube.ndisc.mts.xserver.XNDiscServer.java

/**
 * Console clear //from   ww w. j a  v a  2 s  .  c  o  m
 */
private static void clearConsoleOutput() {
    try {
        String os = System.getProperty("os.name").toLowerCase();
        String ostype = (os.contains("windows")) ? "W" : "U";
        if (ostype.equals("W")) {
            CommandLine cmdLine = CommandLine.parse("cls");
            DefaultExecutor executor = new DefaultExecutor();
            executor.execute(cmdLine);
            System.out.printf("%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n", new Object[0]);
        } else {
            CommandLine cmdLine = CommandLine.parse("clear");
            DefaultExecutor executor = new DefaultExecutor();
            executor.execute(cmdLine);
            System.out.print(CLEAR_TERMINAL_ANSI_CMD);
            System.out.flush();
        }
    } catch (IOException e) {
    }
}

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/*from w  w  w .  j  a v  a  2  s.c  o 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.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//www .  j a v 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(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.mooregreatsoftware.gitprocess.lib.Pusher.java

private static ThePushResult doGitProgPush(GitLib gitLib, Branch localBranch, String remoteBranchName,
        boolean forcePush, String remoteName) {
    String cmd = String.format("git push --porcelain %s %s %s:%s", remoteName, forcePush ? "--force" : "",
            localBranch.shortName(), remoteBranchName);
    CommandLine commandLine = CommandLine.parse(cmd);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(gitLib.workingDirectory());
    final StringWriter stdOutWriter = new StringWriter();
    final StringWriter stdErrWriter = new StringWriter();
    executor.setStreamHandler(//from w ww. ja v a  2  s  . com
            new PumpStreamHandler(new WriterOutputStream(stdOutWriter), new WriterOutputStream(stdErrWriter)));
    final int exitCode = Try.of(() -> {
        try {
            return executor.execute(commandLine);
        } catch (ExecuteException e) {
            return e.getExitValue();
        } catch (IOException e) {
            final String message = e.getMessage();
            if (message != null && message.contains("No such file or directory")) {
                return 1;
            }
            e.printStackTrace();
            return -1;
        }
    }).get();

    return new ProcPushResult(stdOutWriter, stdErrWriter, exitCode);
}

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 .  ja  v a  2s .c  o 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(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:com.sds.acube.ndisc.mts.xserver.XNDiscServer.java

/**
 * XNDisc Server  ? ?  ?//from ww  w . jav  a 2 s.  c  o m
 * 
 * @return ?? true,  false
 */
private static boolean isXNDiscServerAlive() {
    boolean isAlive = false;

    String HOST = XNDiscConfig.getString(XNDiscConfig.HOST, XNDiscConfig.LOCAL_HOST);
    String PORT = XNDiscConfig.getString(XNDiscConfig.PORT);

    Scanner scanner = null;
    ByteArrayOutputStream baos = null;
    try {
        String os = System.getProperty("os.name").toLowerCase();
        String ostype = (os.contains("windows")) ? "W" : "U";
        CommandLine cmdline = new CommandLine("netstat");
        cmdline.addArgument("-an");
        if (ostype.equals("W")) {
            cmdline.addArgument("-p");
            cmdline.addArgument("\"TCP\"");
        } else { // UNIX ? ? -an ? ?  ?  
            if (XNDiscUtils.isSolaris()) {
                cmdline.addArgument("-P");
                cmdline.addArgument("tcp");
            } else if (XNDiscUtils.isAix()) {
                cmdline.addArgument("-p");
                cmdline.addArgument("TCP");
            }
        }
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        baos = new ByteArrayOutputStream();
        PumpStreamHandler sh = new PumpStreamHandler(baos);
        executor.setStreamHandler(sh);
        executor.execute(cmdline);
        String str = baos.toString();
        if (str != null && str.length() > 0) { // ?  XNDisc alive ?(XNDisc Server ? ?)
            scanner = new Scanner(str);
            while (scanner.hasNextLine()) {
                String readline = scanner.nextLine();
                if (readline.contains(HOST) && readline.contains(PORT)
                        && readline.contains(XNDISC_LISTEN_STATUS)) {
                    isAlive = true;
                    break;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        isAlive = false;
    } finally {
        try {
            if (scanner != null) {
                scanner.close();
            }
            if (baos != null) {
                baos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return isAlive;
}

From source file:at.treedb.util.Execute.java

public static ExecResult execute(String command, String[] param, Map<String, File> map) {
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = null;/*from w  w  w .  jav  a  2  s  .  c om*/
    int exitValue = 0;
    try {
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        cmdLine = new CommandLine(command);
        if (param != null) {
            for (String s : param) {
                s = s.trim();
                if (s.isEmpty()) {
                    continue;
                }
                cmdLine.addArgument(s);
            }
        }
        cmdLine.setSubstitutionMap(map);
        executor.setStreamHandler(streamHandler);
        exitValue = executor.execute(cmdLine);

        return new ExecResult(exitValue, outputStream.toString(), null);
    } catch (Exception e) {
        return new ExecResult(-1, outputStream.toString(), e);
    }

}

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

@DescribeProcess(title = "GRASS Version", description = "Retreive the version of GRASS used for computation")
@DescribeResult(description = "Version")
public static String version() {
    if (EXEC == null) {
        return "unavailable";
    }/*from  w w  w .ja  v a  2 s.  c o m*/
    CommandLine cmd = new CommandLine(EXEC);
    cmd.addArgument("-v");

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        executor.setStreamHandler(new PumpStreamHandler(outputStream));

        LOGGER.info("exec: " + cmd.toString());
        int exitValue = executor.execute(cmd);
        return outputStream.toString();
    } catch (ExecuteException huh) {
        return "exit code: " + huh.getExitValue() + " (" + huh.getMessage() + ")";
    } catch (IOException e) {
        return "unavailable: " + e.getClass().getSimpleName() + ":" + e.getMessage();
    }
}

From source file:com.github.nbyl.xfdcontrol.plugins.notification.blink1.Blink1ToolCommand.java

public void run() throws IOException {
    LOGGER.debug("Running command: {}", this.commandLine.toString());

    DefaultExecutor executor = new DefaultExecutor();
    executor.execute(this.commandLine);
}