Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

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

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:Main.java

public static String highlight(final List<String> lines, final String meta, final String prog,
        final String encoding) throws IOException {
    final File tmpIn = new File(System.getProperty("java.io.tmpdir"),
            String.format("txtmark_code_%d_%d.in", ID, IN_COUNT.incrementAndGet()));
    final File tmpOut = new File(System.getProperty("java.io.tmpdir"),
            String.format("txtmark_code_%d_%d.out", ID, OUT_COUNT.incrementAndGet()));

    try {//from   w  w w  .j a  va2 s.co  m

        final Writer w = new OutputStreamWriter(new FileOutputStream(tmpIn), encoding);

        try {
            for (final String s : lines) {
                w.write(s);
                w.write('\n');
            }
        } finally {
            w.close();
        }

        final List<String> command = new ArrayList<String>();

        command.add(prog);
        command.add(meta);
        command.add(tmpIn.getAbsolutePath());
        command.add(tmpOut.getAbsolutePath());

        final ProcessBuilder pb = new ProcessBuilder(command);
        final Process p = pb.start();
        final InputStream pIn = p.getInputStream();
        final byte[] buffer = new byte[2048];

        int exitCode = 0;
        for (;;) {
            if (pIn.available() > 0) {
                pIn.read(buffer);
            }
            try {
                exitCode = p.exitValue();
            } catch (final IllegalThreadStateException itse) {
                continue;
            }
            break;
        }

        if (exitCode == 0) {
            final Reader r = new InputStreamReader(new FileInputStream(tmpOut), encoding);
            try {
                final StringBuilder sb = new StringBuilder();
                for (;;) {
                    final int c = r.read();
                    if (c >= 0) {
                        sb.append((char) c);
                    } else {
                        break;
                    }
                }
                return sb.toString();
            } finally {
                r.close();
            }
        }

        throw new IOException("Exited with exit code: " + exitCode);
    } finally {
        tmpIn.delete();
        tmpOut.delete();
    }
}

From source file:com.googlecode.promnetpp.research.main.CoverageMain.java

private static void doSeedRun(int seed) throws IOException, InterruptedException {
    currentSeed = seed;/*from  ww w  .j  a v a  2  s.  co  m*/
    System.out.println("Running with seed " + seed);
    String pattern = "int random = <INSERT_SEED_HERE>;";
    int start = sourceCode.indexOf(pattern);
    int end = start + pattern.length();
    String line = sourceCode.substring(start, end);
    line = line.replace("<INSERT_SEED_HERE>", Integer.toString(seed));
    String sourceCodeWithSeed = sourceCode.replace(pattern, line);
    FileUtils.writeStringToFile(new File("temp.pml"), sourceCodeWithSeed);
    //Run Spin first
    List<String> spinCommand = new ArrayList<String>();
    spinCommand.add(GeneralData.spinHome + "/spin");
    spinCommand.add("-a");
    spinCommand.add("temp.pml");
    ProcessBuilder processBuilder = new ProcessBuilder(spinCommand);
    Process process = processBuilder.start();
    process.waitFor();
    //Compile PAN next
    List<String> compilePANCommand = new ArrayList<String>();
    compilePANCommand.add("gcc");
    compilePANCommand.add("-o");
    compilePANCommand.add("pan");
    compilePANCommand.add("pan.c");
    processBuilder = new ProcessBuilder(compilePANCommand);
    process = processBuilder.start();
    process.waitFor();
    //Finally, run PAN
    List<String> runPANCommand = new ArrayList<String>();
    runPANCommand.add("./pan");
    String runtimeOptions = PANOptions.getRuntimeOptionsFor(fileName);
    if (!runtimeOptions.isEmpty()) {
        runPANCommand.add(runtimeOptions);
    }
    processBuilder = new ProcessBuilder(runPANCommand);
    process = processBuilder.start();
    process.waitFor();
    String PANOutput = Utilities.getStreamAsString(process.getInputStream());
    if (PANOutputContainsErrors(PANOutput)) {
        throw new RuntimeException("PAN reported errors.");
    }
    processPANOutput(PANOutput);
}

From source file:com.peter.javaautoupdater.JavaAutoUpdater.java

static void restartApplication(String jarName) {
    try {//from w  ww  .ja  v a2  s . c o  m
        final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator
                + "java";
        System.out.println("javaBin=" + javaBin);
        //final File currentJar = new File(JavaAutoUpdater.class.getProtectionDomain().getCodeSource().getLocation().toURI());

        /* is it a jar file? */
        if (!jarName.endsWith(".jar")) {
            return;
        }

        /* Build command: java -jar application.jar */
        final ArrayList<String> command = new ArrayList<String>();
        command.add(javaBin);
        command.add("-jar");
        //System.out.println("path=" + new File(JavaAutoUpdater.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent());
        command.add(jarName);
        if (args != null) {
            for (String arg : args) {
                command.add(arg);
            }
        }
        command.add("-noautoupdate");

        //System.out.println("command=" + command);
        final ProcessBuilder builder = new ProcessBuilder(command);
        builder.start();
        System.exit(0);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.frostwire.util.VPNs.java

private static String readProcessOutput(String command, String arguments) {
    String result = "";
    ProcessBuilder pb = new ProcessBuilder(command, arguments);
    pb.redirectErrorStream(true);/*  w w w  .  j  a  va 2  s  .co m*/
    try {
        Process process = pb.start();
        InputStream stdout = process.getInputStream();
        final BufferedReader brstdout = new BufferedReader(new InputStreamReader(stdout));
        String line = null;

        try {
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = brstdout.readLine()) != null) {
                stringBuilder.append(line);
            }

            result = stringBuilder.toString();
        } catch (Exception e) {
        } finally {
            IOUtils.closeQuietly(brstdout);
            IOUtils.closeQuietly(stdout);
        }

    } catch (Throwable e) {
        e.printStackTrace();
    }
    return result;
}

From source file:Main.java

public static long getMaxCpuFreq() {
    long longRet = 0;
    String result = "0";
    ProcessBuilder cmd;
    try {/*from   w w  w  . j  a  va2  s .c  om*/
        String[] args = { "/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" };
        cmd = new ProcessBuilder(args);
        Process process = cmd.start();
        InputStream in = process.getInputStream();
        byte[] re = new byte[24];
        result = "";
        while (in.read(re) != -1) {
            result = result + new String(re);
        }
        in.close();
    } catch (IOException ex) {
        ex.printStackTrace();
        result = "0";
    }

    if (result.length() != 0) {
        try {
            longRet = Long.valueOf(result.trim());
        } catch (Exception e) {
            android.util.Log.e(TAG, "");
        }
    }
    return longRet;
}

From source file:mitm.common.sms.transport.gnokii.Gnokii.java

public static String identify() throws GnokiiException {
    String[] cmd = new String[] { GNOKII_BIN, "--identify" };

    try {/*from w w w  .j av a 2s. c  o  m*/
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();

        String output = IOUtils.toString(process.getInputStream());

        int exitValue;

        try {
            exitValue = process.waitFor();
        } catch (InterruptedException e) {
            throw new GnokiiException("Identify error. Output: " + output);
        }

        if (exitValue != 0) {
            throw new GnokiiException("Identify error. Output: " + output);
        }

        return output;
    } catch (IOException e) {
        throw new GnokiiException(e);
    }
}

From source file:end2endtests.runner.ProcessRunner.java

private static Process startProcess(File workingDir, List<String> command) throws IOException {
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(workingDir);/*from ww w .  j a  v  a 2s  .c  o  m*/
    builder.redirectErrorStream(false);
    builder.command(command);
    return builder.start();
}

From source file:edu.cwru.jpdg.Dotty.java

/**
 * Compiles the graph to dotty./*from   ww  w  .  j  ava  2s .co  m*/
 */
public static String dotty(String graph) {

    byte[] bytes = graph.getBytes();

    try {
        ProcessBuilder pb = new ProcessBuilder("dotty");
        pb.redirectError(ProcessBuilder.Redirect.INHERIT);
        Process p = pb.start();
        OutputStream stdin = p.getOutputStream();
        stdin.write(bytes);
        stdin.close();

        String line;
        BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
        List<String> stdout_lines = new ArrayList<String>();
        line = stdout.readLine();
        while (line != null) {
            stdout_lines.add(line);
            line = stdout.readLine();
        }
        if (p.waitFor() != 0) {
            throw new RuntimeException("javac failed");
        }

        return StringUtils.join(stdout_lines, "\n");
    } catch (InterruptedException e) {
        throw new RuntimeException(e.getMessage());
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }
}

From source file:de.rub.syssec.saaf.analysis.steps.hash.SSDeep.java

protected static String calculateFuzzyHash(File f) throws IOException {
    String hash = null;//from  ww w.ja v  a  2  s  . co m

    if (SSDEEP_PATH != null) {
        ProcessBuilder pb = new ProcessBuilder(SSDEEP_PATH, f.getAbsolutePath());
        Process proc;
        Scanner in = null;
        try {
            proc = pb.start();
            // Start reading from the program
            in = new Scanner(proc.getInputStream());
            while (in.hasNextLine()) {
                hash = in.nextLine();
            }
            if (hash != null)
                return hash.substring(0, hash.lastIndexOf(","));
        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (Exception ignored) {
            }
        }
    } else {
        LOGGER.warn("exec_ssdeep could not be found in saaf.conf");
    }
    return "";
}

From source file:ml.shifu.shifu.executor.ProcessManager.java

public static int runShellProcess(String currentDir, String[] args) throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(args);
    processBuilder.directory(new File(currentDir));
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();

    LogThread logThread = new LogThread(process, process.getInputStream(), currentDir);
    logThread.start();//w  w w.  jav a2s  .c o  m

    try {
        process.waitFor();
    } catch (InterruptedException e) {
        process.destroy();
    } finally {
        logThread.setToQuit(true);
    }

    LOG.info("Under {} directory, finish run `{}`", currentDir, args);
    return process.exitValue();
}