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 void execute(final CommandLine command, final ExecuteResultHandler handler)
        throws ExecuteException, IOException 

Source Link

Usage

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

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

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

    // As where not linked to a project, we can't set the working directory.
    // So it will use the directory where mvn was launched.

    executor.setExitValue(0);/*from w  w w.ja va 2 s . c o m*/
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        // Ignore.
    }
}

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();//from w ww  .  ja v  a 2 s.co m
    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:de.akquinet.innovation.play.maven.Play2CompilationMojo.java

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArgument("compile");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);//from   w  w w.  ja va  2  s. c o m
    }

    executor.setExitValue(0);
    executor.setWorkingDirectory(project.getBasedir());
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        throw new MojoExecutionException("Error during compilation", e);
    }
}

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

public void execute() throws MojoExecutionException {

    if (isSkipExecution()) {
        getLog().info("Test phase skipped");
        return;//from ww  w.j  av a 2 s  .co 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:com.sonar.scanner.api.it.tools.CommandExecutor.java

public int execute(String[] args, Map<String, String> env, @Nullable Path workingDir) 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);
    }/*  ww  w  .  j  a v a2  s.c o m*/

    watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args, false);
    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());
    return exec.execute(cmd, env);
}

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

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArgument("clean");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);/*from  w w w . j  a  va2s  .  c o  m*/
    }

    executor.setWorkingDirectory(project.getBasedir());
    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        throw new MojoExecutionException("Error during cleanup", e);
    }

    // Also delete the dist directory
    File dist = new File(project.getBasedir(), "dist");
    if (dist.exists()) {
        getLog().debug("Deleting " + dist.getAbsolutePath());
        try {
            FileUtils.deleteDirectory(dist);
        } catch (IOException e) {
            throw new MojoExecutionException("Can't delete the dist folder", e);
        }
    } else {
        getLog().debug("'dist' directory not found");
    }

    // Delete the log folder
    File logs = new File(project.getBasedir(), "logs");
    if (logs.exists()) {
        getLog().debug("Deleting " + logs.getAbsolutePath());
        try {
            FileUtils.deleteDirectory(logs);
        } catch (IOException e) {
            throw new MojoExecutionException("Can't delete the logs folder", e);
        }
    } else {
        getLog().debug("'logs' directory not found");
    }

    // Also delete the lib directory if set
    if (cleanLibFolder) {
        File lib = new File(project.getBasedir(), "lib");
        if (lib.exists()) {
            getLog().debug("Deleting " + lib.getAbsolutePath());
            try {
                FileUtils.deleteDirectory(lib);
            } catch (IOException e) {
                throw new MojoExecutionException("Can't delete the " + lib + " folder", e);
            }
        } else {
            getLog().debug("'" + lib + "' directory not found");
        }
    }
}

From source file:com.boulmier.machinelearning.jobexecutor.job.Job.java

public void start() throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final DefaultExecutor exec = new DefaultExecutor();
    final ExecuteWatchdog wd = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    final PumpStreamHandler output = new PumpStreamHandler(out);
    final DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();

    exec.setWatchdog(wd);/*from   ww  w  . j  ava  2s.com*/
    exec.setStreamHandler(output);
    exec.execute(cl, handler);
    JobExecutor.logger.info("Running job " + jobid);

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                handler.waitFor();
                Computer.ComputeProperties properties = Computer.ComputeProperties.buildFromRequest(req);
                new SenderComputer(new StorageComputer(out.toString(), properties)).compute();
                JobExecutor.logger.info("Job complete " + jobid);
            } catch (InterruptedException ex) {
                exec.getWatchdog().destroyProcess();
                JobExecutor.logger.error(
                        "Job (" + jobid + ") has been destroyed due to internal error " + ex.getMessage());
            }
        }

    }).start();

}

From source file:its.tools.CommandExecutor.java

public void execute(String[] args, @Nullable Path workingDir) 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);
    }//  w w w.  j  av  a 2  s  . co m

    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());
    exec.execute(cmd, new ResultHander());
}

From source file:com.oneops.inductor.ProcessRunner.java

/**
 * Creates a process and logs the output
 *
 * @param cmd//from  ww  w. j a va 2s  . c o m
 * @param logKey
 * @param result
 */
private void executeProcess(String[] cmd, String logKey, ProcessResult result) {

    Map<String, String> env = getEnvVars(logKey, cmd);
    logger.info(logKey + " Cmd: " + String.join(" ", cmd) + ", Env: " + env);

    // run the cmd
    try {

        CommandLine cmdLine = new CommandLine(cmd[0]);
        // add rest of cmd string[] as arguments
        for (int i = 1; i < cmd.length; i++) {
            // needs the quote handling=false or else doesn't work
            // http://www.techques.com/question/1-5080109/How-to-execute--bin-sh-with-commons-exec?
            cmdLine.addArgument(cmd[i], false);
        }
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000));
        executor.setStreamHandler(new OutputHandler(logger, logKey, result));
        result.setResultCode(executor.execute(cmdLine, env));

        // set fault to last error if fault map is empty
        if (result.getResultCode() != 0 && result.getFaultMap().keySet().size() < 1) {
            result.getFaultMap().put("ERROR", result.getLastError());
        }

    } catch (ExecuteException ee) {
        logger.error(logKey + ee);
        result.setResultCode(ee.getExitValue());
    } catch (IOException e) {
        logger.error(e);
        result.setResultCode(1);
    }

}

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);
    }/*  www . j  a  v a 2s . co  m*/

    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);
}