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

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

Introduction

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

Prototype

public void setExitValue(final int value) 

Source Link

Usage

From source file:io.rhiot.utils.process.ExecProcessManager.java

@Override
public List<String> executeAndJoinOutput(String... command) {

    CommandLine cmdLine = CommandLine.parse(String.join(" ", command));
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecResultHandler resultHandler = null;

    if (getTimeout() > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(getTimeout());
        executor.setWatchdog(watchdog);/* w  w w.j a  v a 2s . c o  m*/
        resultHandler = new ExecResultHandler(watchdog);
    }
    try {
        CollectingLogOutputStream outAndErr = new CollectingLogOutputStream();
        executor.setStreamHandler(new PumpStreamHandler(outAndErr));
        if (resultHandler != null) {
            executor.execute(cmdLine, resultHandler);
        } else {
            executor.execute(cmdLine);
        }
        resultHandler.waitFor();
        return outAndErr.getLines();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.tribuneqa.utilities.FrameworkUtilities.java

public void appiumStart() throws IOException, InterruptedException {

    // Start command prompt In background.
    CommandLine command = new CommandLine("cmd");

    // Add different arguments In command line which requires to start appium server.
    command.addArgument("/c");

    // Add different arguments In command line which requires to start appium server. 
    command.addArgument("appium");
    command.addArgument("-a");
    command.addArgument("10.20.121.69");
    command.addArgument("-p");
    command.addArgument("8001");
    command.addArgument("-U");
    command.addArgument("4d0081724d5741c7");

    // Execute command line arguments to start appium server. 
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.execute(command, resultHandler);

    Thread.sleep(15000);/*from  w ww .ja v  a  2 s  .  c  o m*/

}

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);
    try {//from w  ww .  ja  v  a  2 s.  co m
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        // Ignore.
    }
}

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);//w  w  w.j a v a2  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:com.oneops.inductor.ProcessRunner.java

/**
 * Creates a process and logs the output
 *
 * @param cmd// w w w . j  a va  2 s  .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: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  w  w  .j  a v  a  2 s.  c o 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:edu.kit.dama.dataworkflow.impl.LocalExecutionHandler.java

/**
 * Execute the user application. This method will start a new process running
 * the prepared user application locally. The method will return as soon as
 * the application has terminated. An asnychronous monitoring task my check
 * whether the process is still running or not via {@link #getTaskStatus(edu.kit.dama.mdm.dataworkflow.DataWorkflowTask)
 * } This method will check the runningIndicator file '.RUNNING', which only
 * exists as long as the application is running.
 *
 * @param pTask The task whose application should be executed.
 *
 * @throws DataWorkflowProcessingException If either the startup or the
 * processing fails for any reason, or if the user application returns an exit
 * code != 0.//  w  w  w  .ja va 2 s  .c o  m
 */
@Override
public void startUserApplication(DataWorkflowTask pTask) throws DataWorkflowProcessingException {
    //simply start the process...monitoring will be connected later
    File runningIndicator = getRunningIndicator(pTask);
    FileOutputStream fout = null;
    FileOutputStream ferr = null;
    File executablePath;

    try {
        executablePath = DataWorkflowHelper.getTaskMainExecutable(pTask);
        File executionBasePath = DataWorkflowHelper.getExecutionBasePath(pTask);
        File workingDirectory = DataWorkflowHelper.getTaskWorkingDirectory(executionBasePath);
        File tempDirectory = DataWorkflowHelper.getTaskTempDirectory(executionBasePath);
        File inputDirectory = DataWorkflowHelper.getTaskInputDirectory(executionBasePath);
        File outputDirectory = DataWorkflowHelper.getTaskOutputDirectory(executionBasePath);

        if (!executablePath.canExecute()) {
            LOGGER.debug("Executable at location {} seems not to be executable. Taking care of this...");
            if (executablePath.setExecutable(true)) {
                LOGGER.debug("Executable was successfully set to be executable.");
            } else {
                LOGGER.warn("Failed to set executable to be executable. Trying to continue.");
            }
        }

        String cmdLineString = executablePath.getAbsolutePath() + " "
                + pTask.getConfiguration().getApplicationArguments() + " " + pTask.getApplicationArguments();
        LOGGER.debug("Building up command array from string '{}'", cmdLineString);

        CommandLine cmdLine = CommandLine.parse(cmdLineString);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        Map<String, String> env = new HashMap<>();
        env.put("WORKING_DIR", workingDirectory.getAbsolutePath());
        env.put("TEMP_DIR", tempDirectory.getAbsolutePath());
        env.put("INPUT_DIR", inputDirectory.getAbsolutePath());
        env.put("OUTPUT_DIR", outputDirectory.getAbsolutePath());

        fout = new FileOutputStream(new File(tempDirectory, "stdout.log"));
        ferr = new FileOutputStream(new File(tempDirectory, "stderr.log"));
        LOGGER.debug("Setting stream handler for stdout and stderr.");
        executor.setStreamHandler(new PumpStreamHandler(fout, ferr));
        LOGGER.debug("Creating .RUNNING file for monitoring.");
        FileUtils.touch(runningIndicator);
        LOGGER.debug("Executing process.");
        int exitCode = executor.execute(cmdLine);
        if (exitCode != 0) {
            throw new DataWorkflowProcessingException(
                    "Execution returned exit code " + exitCode + ". See logfiles for details.");
        } else {
            LOGGER.debug("Process successfully finished with exit code {}", exitCode);
        }
    } catch (IOException | UnsupportedOperatingSystemException e) {
        throw new DataWorkflowProcessingException("Failed to start executable for task " + pTask.getId(), e);
    } finally {
        LOGGER.debug("Removing running indicator file {}", runningIndicator);
        FileUtils.deleteQuietly(runningIndicator);
        if (fout != null) {
            try {
                fout.close();
            } catch (IOException ex) {
            }
        }

        if (ferr != null) {
            try {
                ferr.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:io.vertx.config.vault.utils.VaultProcess.java

public boolean run(String args) {
    String cli = executable.getAbsolutePath() + " " + args;
    System.out.println(">> " + cli);
    CommandLine parse = CommandLine.parse(cli);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    try {// w ww  .  j  ava 2  s. c o  m
        return executor.execute(parse) == 0;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:de.tu_dresden.psy.fca.ConexpCljBridge.java

public ConexpCljBridge() {

    this.b = new byte[1];

    /**/*from   w w w.  j  a v a2 s. c om*/
     * build the command line (see conexp-clj/bin/conexp-clj)
     */

    String java_bin = Launcher.getJavaCommand();

    CommandLine conexp_cmd = new CommandLine(java_bin);
    conexp_cmd.addArgument("-server");
    conexp_cmd.addArgument("-cp");
    conexp_cmd.addArgument("./conexp-clj/lib/conexp-clj-0.0.7-alpha-SNAPSHOT-standalone.jar");
    conexp_cmd.addArgument("clojure.main");
    conexp_cmd.addArgument("-e");
    conexp_cmd.addArgument("");
    conexp_cmd.addArgument("./conexp-clj/lib/conexp-clj.clj");

    /**
     * open the pipes
     */

    this.to_conexp = new PipedOutputStream();
    try {
        this.stream_to_conexp = new PipedInputStream(this.to_conexp, 2048);
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    this.stream_error_conexp = new PipedOutputStream();
    this.stream_from_conexp = new PipedOutputStream();

    try {
        this.from_conexp = new PipedInputStream(this.stream_from_conexp, 2048);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try {
        this.error_conexp = new PipedInputStream(this.stream_error_conexp, 2048);
    } catch (IOException e1) {

        e1.printStackTrace();
    }

    /**
     * setup apache commons exec
     */

    this.result = new DefaultExecuteResultHandler();

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setStreamHandler(
            new PumpStreamHandler(this.stream_from_conexp, this.stream_error_conexp, this.stream_to_conexp));

    /**
     * run in non-blocking mode
     */

    try {
        executor.execute(conexp_cmd, this.result);
    } catch (ExecuteException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.output_buffer = "";

}

From source file:com.devesion.maven.jsr308.CheckersPlugin.java

/**
 * Plugin Entry point./*from w w  w  . j  a va  2 s .  co m*/
 * 
 * @throws MojoExecutionException exception
 * @throws MojoFailureException exception
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    getLog().info("Executing JSR-308 Checkers");

    if (checkers.size() <= 0) {
        getLog().info("No checkers found, omitting checkers execution");
        return;
    }

    final SourceContext sourceCtx = new SourceContext(compileSourceDirs, includes, excludes);
    final List<String> sources = SourceUtils.getProjectSources(sourceCtx);
    if (sources.isEmpty()) {
        getLog().info("The project does not contains any sources, omitting checkers execution");
        return;
    }

    final CommandLine cl = new CommandLine("java");
    if (checkerJar == null || checkerJar.isEmpty()) {
        checkerJar = ArtifactUtils.getArtifactPath(JSR308_ALL_GROUP_ID, JSR308_ALL_ARTIFACT_ID, dependencies);
        if (checkerJar == null) {
            throw new MojoExecutionException("Cannot find " + JSR308_ALL_GROUP_ID + ":" + JSR308_ALL_ARTIFACT_ID
                    + " artifact jar in the local repository.");
        }
    }

    cl.addArgument("-Xbootclasspath/p:" + checkerJar);
    cl.addArgument("-ea:com.sun.tools");
    if (userJavaParams != null) {
        cl.addArgument(userJavaParams);
    }
    cl.addArgument("-jar");
    cl.addArgument(checkerJar);
    cl.addArgument("-proc:only");

    // adding checkers
    for (String checker : checkers) {
        cl.addArgument("-processor");
        cl.addArgument(checker);
    }

    // adding project sources
    cl.addArguments(sources.toArray(new String[sources.size()]));

    // adding classpath
    final StringBuilder sb = new StringBuilder();
    for (String element : compileClasspathElements) {
        sb.append(element);
        sb.append(File.pathSeparator);
    }

    cl.addArgument("-classpath");
    cl.addArgument(sb.toString());
    if (userJavacParams != null) {
        cl.addArgument(userJavacParams);
    }

    // executing compiler
    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(EXIT_CODE_OK);

    try {
        executor.execute(cl);
    } catch (ExecuteException ex) {

        if (failOnError) {
            throw new MojoExecutionException(
                    "Unable to continue because of some errors reported by checkers - " + ex.getMessage());
        } else {
            getLog().error("Some errors has been reported by checkers - " + ex.getMessage());
        }
    } catch (IOException ex) {
        throw new MojoExecutionException("cannot execute checkers", ex);
    }
}