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

ProcessBuilder

Source Link

Usage

From source file:org.hawkular.metrics.clients.ptrans.fullstack.CollectdITest.java

private void assertCollectdConfIsValid() throws Exception {
    collectdOut = temporaryFolder.newFile();
    collectdErr = temporaryFolder.newFile();

    collectdProcessBuilder = new ProcessBuilder();
    collectdProcessBuilder.directory(temporaryFolder.getRoot());
    collectdProcessBuilder.redirectOutput(collectdOut);
    collectdProcessBuilder.redirectError(collectdErr);

    collectdProcessBuilder.command(COLLECTD_PATH, "-C", collectdConfFile.getAbsolutePath(), "-t", "-T", "-f");

    collectdProcess = collectdProcessBuilder.start();

    int exitCode = collectdProcess.waitFor();
    assertEquals("Collectd configuration doesn't seem to be valid", 0, exitCode);

    boolean hasErrorInLog = Stream.concat(Files.lines(collectdOut.toPath()), Files.lines(collectdErr.toPath()))
            .anyMatch(l -> l.contains("[error]"));
    assertFalse("Collectd configuration doesn't seem to be valid", hasErrorInLog);
}

From source file:com.thoughtworks.gauge.maven.GaugeExecutionMojo.java

private ProcessBuilder createProcessBuilder() {
    ProcessBuilder builder = new ProcessBuilder();
    builder.command(createGaugeCommand());
    String customClasspath = createCustomClasspath();
    debug("Setting Custom classpath => %s", customClasspath);
    builder.environment().put(GAUGE_CUSTOM_CLASSPATH_ENV, customClasspath);
    return builder;
}

From source file:de.tudarmstadt.ukp.dkpro.core.RSTAnnotator.java

/**
 * Runs the parser on the given text//from   w  ww. j ava  2 s. c  o m
 *
 * @param originalText text
 * @return parse tree
 * @throws IOException exception
 */
public String parseWithRST(String originalText) throws IOException {
    // temporary file in
    File tmpFileIn = File.createTempFile("rst_tmp", ".txt");
    // output of RST parser is a .tree file
    File tmpFileOut = new File(tmpFileIn.getAbsolutePath() + ".tree");
    // tmp log
    File tmpFileLog = new File(tmpFileIn.getAbsolutePath() + ".log");

    try {
        // write the text into a temporary file
        FileUtils.writeStringToFile(tmpFileIn, originalText);

        String tmpDirName = System.getProperty("java.io.tmpdir");

        File rstParserSrcDir = new File(rstParserSrcDirPath);

        // create process
        ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

        // log to file
        processBuilder.redirectErrorStream(true);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.to(tmpFileLog));

        // working dir must be set to the src dir of RST parser
        processBuilder.directory(rstParserSrcDir);

        // run the command
        processBuilder.command("python", new File(rstParserSrcDir, "parse.py").getAbsolutePath(), "-t",
                tmpDirName, tmpFileIn.getAbsolutePath(), "-g");
        Process process = processBuilder.start();

        // and wait
        int returnValue = process.waitFor();

        if (returnValue != 0) {
            throw new RuntimeException("Process exited with code " + returnValue);
        }

        // read the log
        if (this.debugRSTOutput) {
            getLogger().debug(FileUtils.readFileToString(tmpFileLog));
        }

        // read the output
        if (tmpFileOut.exists()) {
            return FileUtils.readFileToString(tmpFileOut);
        }
    } catch (InterruptedException e) {
        throw new IOException(e);
    } finally {
        // clean up
        if (!keepTmpFiles) {
            FileUtils.deleteQuietly(tmpFileIn);
            FileUtils.deleteQuietly(tmpFileOut);
            FileUtils.deleteQuietly(tmpFileLog);
        }
    }

    return null;
}

From source file:com.appcel.core.encoder.executor.FfmpegEncoderExecutor.java

public void execute(MediaRecord record, File directory) throws EncoderException {

    LOGGER.info(" ffmpeg ?  video ...  Ffmpeg  ===>>> " + args);

    final ProcessBuilder pb = new ProcessBuilder().directory(directory);
    pb.redirectErrorStream(true);//w  w  w  .j a  v a 2 s . co m
    if (null != directory) {
        LOGGER.info("ffmpeg ??==========>>>" + directory.toString());
    }

    pb.command(args);

    try {
        final Process process = pb.start();
        inputStream = process.getInputStream();

        MediaInputStreamParser.parseMediaRecord(inputStream, record);

        outputStream = process.getOutputStream();
        errorStream = process.getErrorStream();
        // ???????.
        //         BufferedInputStream in = new BufferedInputStream(inputStream);
        //         BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
        //         String lineStr;
        //         while ((lineStr = inBr.readLine()) != null)
        //            LOGGER.info("process.getInputStream() ===>>> " + lineStr);

        int waitfor = process.waitFor();
        if (waitfor != 0) {
            //p.exitValue()==0?1??
            if (process.exitValue() == 1) {
                LOGGER.info("===>>> ffmpeg ? Failed!");
                throw new EncoderException("ffmpeg ? Failed!");
            } else {
                LOGGER.info("==========>>> ffmpeg ??.");
            }
        } else {
            LOGGER.info("==========>>> ffmpeg ??.");
        }

    } catch (IOException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
    } catch (InterruptedException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
        Thread.currentThread().interrupt();
    } finally {
        destroy();
    }
}

From source file:docs.AbstractGemFireIntegrationTests.java

protected static Process run(Class<?> type, File directory, String... args) throws IOException {
    return new ProcessBuilder().command(createJavaProcessCommandLine(type, args)).directory(directory).start();
}

From source file:io.syndesis.verifier.LocalProcessVerifier.java

private Properties runValidator(String classpath, Verifier.Scope scope, String camelPrefix, Properties request)
        throws IOException, InterruptedException {
    Process java = new ProcessBuilder().command("java", "-classpath", classpath,
            "io.syndesis.connector.ConnectorVerifier", scope.toString(), camelPrefix)
            .redirectError(ProcessBuilder.Redirect.INHERIT).start();

    try (OutputStream os = java.getOutputStream()) {
        request.store(os, null);//ww w  . j a  v a  2  s.  co m
    }
    Properties result = new Properties();
    try (InputStream is = java.getInputStream()) {
        result.load(is);
    }

    if (java.waitFor() != 0) {
        throw new IOException("Verifier failed with exit code: " + java.exitValue());
    }
    return result;
}

From source file:com.streamsets.datacollector.util.SystemProcessImpl.java

@Override
public void start(Map<String, String> env) throws IOException {
    Utils.checkState(output.createNewFile(), Utils.formatL("Could not create output file: {}", output));
    Utils.checkState(error.createNewFile(), Utils.formatL("Could not create error file: {}", error));
    Utils.checkState(delegate == null, "start can only be called once");
    LOG.info("Standard output for process written to file: " + output);
    LOG.info("Standard error for process written to file: " + error);
    ProcessBuilder processBuilder = new ProcessBuilder().redirectInput(input).redirectOutput(output)
            .redirectError(error).directory(tempDir).command(args);
    processBuilder.environment().putAll(env);
    LOG.info("Starting: " + args);
    delegate = processBuilder.start();//  w ww .  j  a  v a2  s  .  c  om
    ThreadUtil.sleep(100); // let it start
    outputTailer = new SimpleFileTailer(output);
    errorTailer = new SimpleFileTailer(error);
}

From source file:es.ehu.si.ixa.qwn.ppv.UKBwrapper.java

public void propagate(String ctxtFile) throws IOException {
    try {//from  ww  w  . j  av a 2 s .c  o  m
        String[] command = { ukbPath + "/ukb_ppv", "-K", this.graph, "-D", this.langDict, "--variants", "-O",
                this.outDir, ctxtFile };
        System.err.println("UKB komandoa: " + Arrays.toString(command));

        ProcessBuilder ukbBuilder = new ProcessBuilder().command(command);
        //.redirectErrorStream(true);
        Process ukb_ppv = ukbBuilder.start();
        int success = ukb_ppv.waitFor();
        System.err.println("ukb_ppv succesful? " + success);
        if (success != 0) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ukb_ppv.getErrorStream()),
                    1);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.err.println(line);
            }
        }
    } catch (Exception e) {
        System.err.println("PropagationUKB class: error when calling ukb_ppv\n.");
        e.printStackTrace();
    }
    //"$UKB_PATH"/bin/ukb_ppv -K "$PROPAGATION_PATH"/lkb_resources/wnet30_enSyn.bin -D "$UKB_PATH"/lkb_sources/30/wnet30_dict.txt --variants -O "$PPV_OUT_DIR" $TMP_DIR/propag_posSeeds_syn.ctx  
    //mv "$PPV_OUT_DIR"/ctx_01.ppv "$PPV_OUT_DIR"/pos_syn.ppv

}

From source file:io.github.retz.executor.FileManager.java

private static void decompress(File file, String dir) throws IOException {
    LOG.info("{} needs decompression: starting", file);
    String[] cmd = { "tar", "xf", file.getAbsolutePath(), "-C", dir };
    ProcessBuilder pb = new ProcessBuilder().command(cmd).inheritIO();
    try {/*  w ww .  j  av a  2s .  com*/
        Process p = pb.start();
        int r = p.waitFor();
        if (r == 0) {
            LOG.info("file {} successfully decompressed", file);
        } else {
            LOG.error("Failed decompression of file {}: {}", file, r);
        }
    } catch (InterruptedException e) {
        LOG.error(e.getMessage());
    }
}

From source file:org.darkware.wpman.wpcli.WPCLI.java

public WPCLI(final String group, final String command, final String... commandArgs) {
    super();//from   ww  w.  ja va2s .c om

    this.cmd = new Command(new ProcessBuilder(), toolPath);

    this.group = group;
    this.command = command;
    this.commandArgs = new ArrayList<>();
    for (String arg : commandArgs)
        this.addArgument(arg);
    this.args = new ArrayList<>();
    this.options = new HashMap<>();

    this.inputData = new ByteArrayOutputStream();
    this.input = new PrintWriter(this.inputData);
}