Example usage for org.apache.commons.exec CommandLine toString

List of usage examples for org.apache.commons.exec CommandLine toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Stringify operator returns the command line as a string.

Usage

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

public static void reset() throws IOException {
    CommandLine cmdLine = new CommandLine(ADB);
    cmdLine.addArgument("kill-server");
    LOG.debug("{}", cmdLine.toString());
    Executor executor = new DefaultExecutor();
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }/* w  ww. j av a 2  s . c o m*/
    cmdLine = new CommandLine(ADB);
    cmdLine.addArgument("devices");
    LOG.debug("{}", cmdLine.toString());
    executor = new DefaultExecutor();
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }
}

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

private static void loadAllSerials() {
    SERIALS.clear();//from  w  ww . j  a va  2 s .  c o m
    String serials = SystemConfiguration.getInstance().getProperty(SYSPROP_SERIALS);
    if (null != serials) {
        LOG.info("Use specified devices from system property {}={}", SYSPROP_SERIALS, serials);
        SERIALS.addAll(Lists.newArrayList(serials.split(",")));
    } else {
        CommandLine cmdLine = new CommandLine(ADB);
        cmdLine.addArgument("devices");
        LOG.debug("{}", cmdLine.toString());
        List<String> output = new ArrayList<>();
        Executor executor = new DefaultExecutor();
        executor.setStreamHandler(new ESH(output));
        try {
            if (executor.execute(cmdLine) != 0) {
                throw new RuntimeException(cmdLine + " failed");
            }
        } catch (IOException ex) {
            throw new RuntimeException(cmdLine + " failed", ex);
        }
        output.stream().filter((line) -> (line.endsWith("device"))).forEach((line) -> {
            String s = line.split("\\t")[0];
            LOG.info("serial {}", s);
            SERIALS.add(s);
        });
    }
    if (SERIALS.isEmpty()) {
        throw new RuntimeException("No device detected.");
    }
}

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

private static void loadSerialProductMap() {
    SERIAL_PRODUCT.clear();//w  w w .ja  v a  2s.c o m
    String serials = SystemConfiguration.getInstance().getProperty(SYSPROP_SERIALS);
    if (null != serials) {
        LOG.info("Use specified devices from system property {}={}", SYSPROP_SERIALS, serials);
        Lists.newArrayList(serials.split(",")).forEach(s -> SERIAL_PRODUCT.put(s, "na"));
    } else {
        CommandLine cmdLine = new CommandLine(ADB);
        cmdLine.addArgument("devices");
        cmdLine.addArgument("-l");
        LOG.debug("{}", cmdLine.toString());
        List<String> output = new ArrayList<>();
        Executor executor = new DefaultExecutor();
        executor.setStreamHandler(new ESH(output));
        try {
            if (executor.execute(cmdLine) != 0) {
                throw new RuntimeException(cmdLine + " failed");
            }
        } catch (IOException ex) {
            throw new RuntimeException(cmdLine + " failed", ex);
        }
        output.stream().map(line -> StringUtils.split(line, " ", 3))
                .filter(ss -> ss.length == 3 && ss[1].equals("device")).forEach(ss -> {
                    LOG.info("device {} -> {}", ss[0], ss[2]);
                    SERIAL_PRODUCT.put(ss[0], ss[2]);
                });
    }
    if (SERIAL_PRODUCT.isEmpty()) {
        throw new RuntimeException("No device detected.");
    }
    SERIALS.addAll(SERIAL_PRODUCT.keySet());
}

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//  ww w .jav  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.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   ww  w .  j a va2s.  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(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:latexstudio.editor.runtime.CommandLineExecutor.java

public static synchronized void executeGeneratePDF(CommandLineBuilder cmd) {
    String outputDirectory = "--output-directory=" + cmd.getOutputDirectory();
    String outputFormat = "--output-format=pdf";
    String job = cmd.getJobname() == null ? "" : "--jobname=" + cmd.getJobname().replaceAll(" ", "_");
    ByteArrayOutputStream outputStream = null;

    try {/* w w w . j  ava 2s  . c o m*/
        String[] command = new String[] { outputDirectory, outputFormat, job, cmd.getPathToSource() };

        CommandLine cmdLine = new CommandLine(ApplicationUtils.getPathToTEX(cmd.getLatexPath()));
        //For windows, we set handling quoting to true
        cmdLine.addArguments(command, ApplicationUtils.isWindows());

        outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        EXECUTOR.setStreamHandler(streamHandler);

        if (cmd.getWorkingFile() != null) {
            EXECUTOR.setWorkingDirectory(cmd.getWorkingFile().getParentFile().getAbsoluteFile());
        }

        EXECUTOR.execute(cmdLine);

        if (cmd.getLogger() != null) {
            cmd.getLogger().log(cmdLine.toString());
            cmd.getLogger().log(outputStream.toString());
        }

    } catch (IOException e) {
        if (cmd.getLogger() != null) {
            cmd.getLogger().log("The path to the pdflatex tool is incorrect or has not been set.");
        }
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

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

@DescribeProcess(title = "r.viewshed", description = "Computes the viewshed of a point on an elevation raster map.")
@DescribeResult(description = "area visible from provided location")
public static GridCoverage2D viewshed(
        @DescribeParameter(name = "dem", description = "digitial elevation model") GridCoverage2D dem,
        @DescribeParameter(name = "x", description = "x location in map units") double x,
        @DescribeParameter(name = "y", description = "y location in map units") double y) throws Exception {

    String COMMAND = "viewshed";
    //Stage files in a temporary location
    File geodb = Files.createTempDirectory("grassdata").toFile();
    geodb.deleteOnExit();//  w  w w.ja  va 2s  .com
    File location = new File(geodb, COMMAND + Long.toString(random.nextLong()) + "location");

    // stage dem file
    File file = new File(geodb, "dem.tif");
    //The file must exist for FileImageOutputStreamExtImplSpi to create the output stream
    if (!file.exists()) {
        file.getParentFile().mkdirs();
        file.createNewFile();
    }
    final GeoTiffFormat format = new GeoTiffFormat();
    GridCoverageWriter writer = format.getWriter(file);
    writer.write(dem, null);
    LOGGER.info("Staging file:" + file);

    // use file to create location with (returns PERMANENT mapset)
    File mapset = location(location, file);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWatchdog(new ExecuteWatchdog(60000));
    executor.setStreamHandler(new PumpStreamHandler(System.out));
    executor.setWorkingDirectory(mapset);

    Map<String, String> env = customEnv(geodb, location, mapset);

    // EXPORT IMPORT DEM
    // r.in.gdal input=~/grassdata/viewshed/PERMANENT/dem.tif output=dem --overwrite

    File r_in_gdal = bin("r.in.gdal");
    CommandLine cmd = new CommandLine(r_in_gdal);
    cmd.addArgument("input=${file}");
    cmd.addArgument("output=dem");
    cmd.addArgument("--overwrite");
    cmd.setSubstitutionMap(new KVP("file", file));
    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_in_gdal.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // EXECUTE VIEWSHED
    File r_viewshed = bin("r.viewshed");
    cmd = new CommandLine(r_viewshed);
    cmd.addArgument("input=dem");
    cmd.addArgument("output=viewshed");
    cmd.addArgument("coordinates=${x},${y}");
    cmd.addArgument("--overwrite");
    cmd.setSubstitutionMap(new KVP("x", x, "y", y));

    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_viewshed.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // EXECUTE EXPORT VIEWSHED
    // r.out.gdal --overwrite input=viewshed@PERMANENT output=/Users/jody/grassdata/viewshed/viewshed.tif format=GTiff
    File viewshed = new File(location, "viewshed.tif");

    File r_out_gdal = bin("r.out.gdal");
    cmd = new CommandLine(r_out_gdal);
    cmd.addArgument("input=viewshed");
    cmd.addArgument("output=${viewshed}");
    cmd.addArgument("--overwrite");
    cmd.addArgument("format=GTiff");
    cmd.setSubstitutionMap(new KVP("viewshed", viewshed));

    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_out_gdal.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // STAGE RESULT

    if (!viewshed.exists()) {
        throw new IOException("Generated viweshed.tif not found");
    }
    GeoTiffReader reader = format.getReader(viewshed);
    GridCoverage2D coverage = reader.read(null);
    cleanup(new File(env.get("GISRC")));
    return coverage;
}

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  .  j a v a  2 s.  c om
    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.abiquo.nodecollector.service.impl.StonithServiceImpl.java

protected boolean executeCommand(final CommandLine command) {
    try {/*from ww  w .ja  v a 2 s.  c  om*/
        LOGGER.debug(String.format("Executing '%s'", command.toString()));

        DefaultExecutor executor = new DefaultExecutor();

        return executor.execute(command) == 0;
    } catch (Exception e) {
        LOGGER.error(String.format("While executing '%s'", command.toString()), e);
        return false;
    }
}

From source file:com.cip.crane.agent.exec.TaurusExecutorTest.java

public void testExecute() throws IOException {
    //        Executor exec = new TaurusExecutor();
    //        exec.execute("test", System.out, System.err, "C:/1.bat");
    String cmd = "sudo -u hadoop bash -c \"kinit\";  ";
    CommandLine cmd1 = new CommandLine(cmd);
    CommandLine cmdLine = new CommandLine("bash");
    cmdLine.addArgument("-c");
    cmdLine.addArgument(cmd);//from   w w w .  ja v  a  2 s. com
    System.out.println(cmd1);
    System.out.println(cmdLine.toString());
}