Example usage for java.lang ProcessBuilder ProcessBuilder

List of usage examples for java.lang ProcessBuilder ProcessBuilder

Introduction

In this page you can find the example usage for java.lang ProcessBuilder ProcessBuilder.

Prototype

public ProcessBuilder(String... command) 

Source Link

Document

Constructs a process builder with the specified operating system program and arguments.

Usage

From source file:com.haulmont.yarg.formatters.impl.doc.connector.LinuxProcessManager.java

protected List<String> execute(String... args) throws IOException {
    Process process = new ProcessBuilder(args).start();
    @SuppressWarnings("unchecked")
    List<String> lines = IOUtils.readLines(process.getInputStream());
    return lines;
}

From source file:de.fhg.iais.asc.xslt.binaries.scale.ImageMagickScaler.java

private boolean scale(File source, File target, List<String> command) {
    File incomplete = target;/*from w w  w.  ja va 2s . c om*/

    // Execute convert
    try {
        ParentDirectoryUtils.forceCreateParentDirectoryOf(target);

        Process process = new ProcessBuilder(command).redirectErrorStream(true).start();

        IOUtils.copyLarge(process.getInputStream(), NULL_OUTPUT_STREAM);

        if (process.waitFor() == 0) {
            incomplete = null;
            if (target.isFile()) {
                return true;
            } else {
                System.out.println(target);
            }
        }

        LOG.error(createErrorPrefix(source, target) + ": convert failed");
    } catch (IOException e) {
        LOG.error(createErrorPrefix(source, target), e);
    } catch (InterruptedException e) {
        throw new RuntimeException();
    } finally {
        if (incomplete != null) {
            incomplete.delete();
        }
    }

    return false;
}

From source file:com.twitter.bazel.checkstyle.CppCheckstyle.java

private static void runLinter(List<String> command) throws IOException {
    LOG.fine("checkstyle command: " + command);

    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
    Process cpplint = processBuilder.start();

    try {//from  w ww.  java  2  s .com
        cpplint.waitFor();
    } catch (InterruptedException e) {
        throw new RuntimeException("cpp checkstyle command was interrupted: " + command, e);
    }

    if (cpplint.exitValue() == 1) {
        LOG.warning("cpp checkstyle detected bad styles.");
        // SUPPRESS CHECKSTYLE RegexpSinglelineJava
        System.exit(1);
    }

    if (cpplint.exitValue() != 0) {
        throw new RuntimeException("cpp checkstyle command failed with status " + cpplint.exitValue());
    }
}

From source file:de.jcup.egradle.core.process.SimpleProcessExecutor.java

@Override
public int execute(ProcessConfiguration wdProvider, EnvironmentProvider envProvider,
        ProcessContext processContext, String... commands) throws IOException {
    notNull(wdProvider, "'wdProvider' may not be null");
    notNull(envProvider, "'envProvider' may not be null");
    String wd = wdProvider.getWorkingDirectory();
    /* Working directory */
    File workingDirectory = null;
    if (StringUtils.isNotBlank(wd)) {
        workingDirectory = new File(wd);
    }/* w  w w  .ja v a2  s  . co m*/
    if (workingDirectory != null) {
        if (!workingDirectory.exists()) {
            throw new FileNotFoundException("Working directory does not exist:" + workingDirectory);
        }
    }
    /* Create process with dedicated environment */
    ProcessBuilder pb = new ProcessBuilder(commands);
    Map<String, String> env = envProvider.getEnvironment();
    /* init environment */
    if (env != null) {
        Map<String, String> pbEnv = pb.environment();
        for (String key : env.keySet()) {
            pbEnv.put(key, env.get(key));
        }
    }
    /* init working directory */
    pb.directory(workingDirectory);
    pb.redirectErrorStream(true);

    Date started = new Date();
    Process p = startProcess(pb);
    ProcessTimeoutTerminator timeoutTerminator = null;
    if (timeOutInSeconds != ENDLESS_RUNNING) {
        timeoutTerminator = new ProcessTimeoutTerminator(p, outputHandler, timeOutInSeconds);
        timeoutTerminator.start();
    }
    ProcessCancelTerminator cancelTerminator = new ProcessCancelTerminator(p,
            processContext.getCancelStateProvider());
    Thread cancelCheckThread = new Thread(cancelTerminator, "process-cancel-terminator");
    cancelCheckThread.start();

    handleProcessStarted(envProvider, p, started, workingDirectory, commands);

    handleOutputStreams(p, timeoutTerminator, processContext.getCancelStateProvider());

    /* wait for execution */
    try {
        while (isAlive(p)) {
            waitFor(p);
        }
    } catch (InterruptedException e) {
        /* ignore */
    }
    /* done */
    int exitValue = p.exitValue();
    handleProcessEnd(p);
    return exitValue;
}

From source file:com.migratebird.script.runner.impl.Application.java

protected ProcessBuilder createProcessBuilder(List<String> commandWithArguments) {
    ProcessBuilder processBuilder = new ProcessBuilder(commandWithArguments);
    Map<String, String> processEnvironment = processBuilder.environment();
    processEnvironment.putAll(environmentVariables);
    processBuilder.redirectErrorStream(true);
    return processBuilder;
}

From source file:com.synflow.cx.tests.codegen.CodegenPassTests.java

/**
 * Executes a command in the path given by the location, and returns its exit code.
 * //from  w w  w .ja  v  a  2 s. c  o  m
 * @param directory
 *            a directory
 * @param command
 *            a list of String
 * @return the return code of the process
 * @throws IOException
 * @throws InterruptedException
 */
protected final Process executeCommand(File directory, String... command)
        throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(command).directory(directory);
    Process process = pb.start();
    new StreamCopier(process.getErrorStream(), System.err).start();
    return process;
}

From source file:name.milesparker.gerrit.analysis.CollectGit.java

protected static void execOuput(String command, String directory, String outputFile) {
    try {/*from w ww. j a v a2s. com*/
        Process process = new ProcessBuilder(StringUtils.split(command)).directory(new File(directory))
                .redirectError(Redirect.INHERIT).redirectOutput(new File(outputFile)).start();
        process.waitFor();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.chris54721.infinitycubed.utils.Utils.java

public static void restart() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override//ww  w  .j a v a 2  s  . c  o  m
        public void run() {
            try {
                File executable = new File(URLDecoder.decode(
                        (Launcher.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()),
                        "UTF-8"));
                List<String> command = new ArrayList<String>();
                command.add(getJavaPath());
                command.add("-jar");
                command.add(executable.getAbsolutePath());
                ProcessBuilder builder = new ProcessBuilder(command);
                builder.start();
            } catch (Exception e) {
                LogHelper.error("Failed restarting launcher, shutting down", e);
                System.exit(-1);
            }
        }
    });
    System.exit(0);
}

From source file:com.temetra.vroomapi.RouteController.java

@RequestMapping(value = "/route", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public JsonNode route(@RequestParam(value = "loc") String[] locs,
        @RequestParam(value = "startAtFirst", defaultValue = "true") boolean startAtFirst,
        @RequestParam(value = "endAtLast", defaultValue = "false") boolean endAtLast,
        @RequestParam(value = "includeGeometry", defaultValue = "false") boolean includeGeometry)
        throws Exception {
    long millis = System.currentTimeMillis();

    File vroomBinFile = new File(vroomBinary);
    if (!vroomBinFile.exists()) {
        log.error("Vroom binary file doesn't exist");
        throw new Exception("Vroom binary file doesn't exist");
    }//from   w w w  .j  a  va2s  .  c o  m

    if (!vroomBinFile.canExecute()) {
        log.error("Cannot execute Vroom binary file");
        throw new Exception("Cannot execute Vroom binary file");
    }

    if (locs.length < 2) {
        log.error("Zero or one location sent");
        throw new Exception("Must send more than one location");
    }

    List<String> progArgs = new ArrayList<>();
    progArgs.add("./" + vroomBinFile.getName());
    if (startAtFirst) {
        progArgs.add("-s");
    }
    if (endAtLast) {
        progArgs.add("-e");
    }
    if (includeGeometry) {
        progArgs.add("-g");
    }

    progArgs.add("loc=" + Joiner.on("&loc=").join(locs) + "");
    log.info("Run (" + millis + "): " + Joiner.on(' ').join(progArgs));

    StringBuilder output = new StringBuilder();
    ProcessBuilder builder = new ProcessBuilder(progArgs);
    builder.directory(vroomBinFile.getParentFile());
    builder.redirectErrorStream(true);
    Process process = builder.start();

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line);
        }
        process.waitFor();
    }

    log.info("Output (" + millis + "): " + output.toString());
    return jsonMapper.readTree(output.toString());
}

From source file:edu.illinois.cs.cogcomp.CleanMojo.java

public void execute() throws MojoExecutionException {
    dFlag = FileUtils.getPlatformIndependentFilePath(dFlag);
    gspFlag = FileUtils.getPlatformIndependentFilePath(gspFlag);
    sourcepathFlag = FileUtils.getPlatformIndependentFilePath(sourcepathFlag);

    classpath.add(dFlag);/*from  ww  w.  java  2s . c om*/
    classpath.add(gspFlag);

    String newpath = StringUtils.join(classpath, File.pathSeparator);

    // We need to reverse the order we do the cleaning since there might be dependencies across
    // files
    List<String> fileList = Arrays.asList(lbjavaInputFileList);
    Collections.reverse(fileList);
    for (String lbjInputFile : fileList) {
        if (StringUtils.isEmpty(lbjInputFile)) {
            // making the optional-compile-step parameter happy.
            continue;
        }

        getLog().info("Calling Java edu.illinois.cs.cogcomp.lbjava.Main with the -x flag (for cleaning)...");

        lbjInputFile = FileUtils.getPlatformIndependentFilePath(lbjInputFile);

        try {
            // The -x flag makes all the difference.
            String[] args = new String[] { "java", "-cp", newpath, "edu.illinois.cs.cogcomp.lbjava.Main", "-x",
                    "-d", dFlag, "-gsp", gspFlag, "-sourcepath", sourcepathFlag, lbjInputFile };

            ProcessBuilder pr = new ProcessBuilder(args);
            pr.inheritIO();
            Process p = pr.start();
            p.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Yeah, an error.");
        }
    }

}