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.liferay.blade.samples.test.BladeCLIUtil.java

public static String execute(File workingDir, String... bladeArgs) throws Exception {

    String bladeCLIJarPath = getLatestBladeCLIJar();

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

    command.add("java");
    command.add("-jar");
    command.add(bladeCLIJarPath);/*w  w  w. j  a  v a 2s .  com*/

    for (String arg : bladeArgs) {
        command.add(arg);
    }

    Process process = new ProcessBuilder(command.toArray(new String[0])).directory(workingDir).start();

    process.waitFor();

    InputStream stream = process.getInputStream();

    String output = new String(IO.read(stream));

    InputStream errorStream = process.getErrorStream();

    List<String> errorList = new ArrayList<>();

    if (errorStream != null) {
        errorList.add(new String(IO.read(errorStream)));
    }

    List<String> filteredErrorList = new ArrayList<>();

    for (String string : errorList) {
        if (!string.isEmpty() && !string.contains("Picked up JAVA_TOOL_OPTIONS:")) {

            filteredErrorList.add(string);
        }
    }

    assertTrue(filteredErrorList.toString(), filteredErrorList.isEmpty());

    output = StringUtil.toLowerCase(output);

    return output;
}

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

/**
 * Compiles the graph to dotty.//from  www.j av  a  2  s  .  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:mamo.vanillaVotifier.ShellCommandSender.java

@NotNull
public Process sendCommand(@NotNull String command, @Nullable Map<String, String> environment)
        throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(new StrTokenizer(command).getTokenArray());
    if (environment != null) {
        processBuilder.environment().putAll(environment);
    }/*  www  .  j a v  a  2 s .c  o m*/
    return processBuilder.start();
}

From source file:com.dickthedeployer.dick.web.service.CommandService.java

public String invoke(Path workingDir, String... command) throws RuntimeException {
    try {//from  w  w w . ja  va 2  s.co  m
        log.info("Executing command {} in path {}", Arrays.toString(command), workingDir.toString());
        StringBuilder text = new StringBuilder();
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(workingDir.toFile());
        builder.redirectErrorStream(true);

        Process process = builder.start();

        try (Scanner s = new Scanner(process.getInputStream())) {
            while (s.hasNextLine()) {
                text.append(s.nextLine());
            }
            int result = process.waitFor();
            log.info("Process exited with result {} and output {}", result, text);

            if (result != 0) {
                throw new CommandExecutionException();
            }
            return text.toString();
        }
    } catch (IOException | InterruptedException ex) {
        throw new CommandExecutionException(ex);
    }
}

From source file:com.liferay.blade.tests.BladeCLI.java

public static String execute(File workingDir, String... bladeArgs) throws Exception {

    String bladeCLIJarPath = getLatestBladeCLIJar();

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

    command.add("java");
    command.add("-jar");
    command.add(bladeCLIJarPath);/* ww w  .  ja v a 2s .  c om*/

    for (String arg : bladeArgs) {
        command.add(arg);
    }

    Process process = new ProcessBuilder(command.toArray(new String[0])).directory(workingDir).start();

    process.waitFor();

    InputStream stream = process.getInputStream();

    String output = new String(IO.read(stream));

    InputStream errorStream = process.getErrorStream();

    String errors = new String(IO.read(errorStream));

    assertTrue(errors, errors == null || errors.isEmpty());

    output = StringUtil.toLowerCase(output);

    return output;
}

From source file:name.martingeisse.ecobuild.util.CommandLineToolInvocation.java

@Override
protected void invoke(List<String> tokens) throws IOException {

    final ProcessBuilder processBuilder = new ProcessBuilder(tokens);
    processBuilder.directory(getWorkingDirectory());
    processBuilder.redirectErrorStream(true);
    final Process process;
    try {/*w  w  w. j a va2s. c o m*/
        process = processBuilder.start();
    } catch (IOException e) {
        getLogger().logError(
                "Exception while starting tool. Command Line: " + getCommand() + " / " + tokens.get(0));
        throw e;
    }
    final MyLoggerWriter loggerWriter = new MyLoggerWriter(getLogger());
    IOUtils.copy(process.getInputStream(), loggerWriter);
    loggerWriter.endStartedLine();
    try {
        process.waitFor();
    } catch (final InterruptedException e) {
        throw new ToolBuildException("An InterruptedException occurred", e);
    }

}

From source file:com.liferay.blade.samples.integration.test.utils.BladeCLIUtil.java

public static String execute(File workingDir, String... bladeArgs) throws Exception {

    String bladeCLIJarPath = getLatestBladeCLIJar();

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

    command.add("java");
    command.add("-jar");
    command.add(bladeCLIJarPath);/*w  ww .j a  va2 s.c  o m*/

    for (String arg : bladeArgs) {
        command.add(arg);
    }

    Process process = new ProcessBuilder(command.toArray(new String[0])).directory(workingDir).start();

    process.waitFor();

    InputStream stream = process.getInputStream();

    String output = new String(IO.read(stream));

    InputStream errorStream = process.getErrorStream();

    List<String> errorList = new ArrayList<>();

    String stringStream = null;

    if (errorStream != null) {
        stringStream = new String(IO.read(errorStream));

        errorList.add(stringStream);
    }

    List<String> filteredErrorList = new ArrayList<>();

    for (String string : errorList) {
        String exclusion = "(.*setlocale.*)";

        Pattern p = Pattern.compile(exclusion, Pattern.DOTALL);

        Matcher m = p.matcher(string);

        while (m.find()) {
            filteredErrorList.add(string);
        }

        if (string.contains("Picked up JAVA_TOOL_OPTIONS:")) {
            filteredErrorList.add(string);
        }
    }

    errorList.removeAll(filteredErrorList);

    Assert.assertTrue(errorList.toString(), errorList.size() <= 1);

    if (errorList.size() == 1) {
        Assert.assertTrue(errorList.get(0), errorList.get(0).isEmpty());
    }

    return output;
}

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 .ja  v  a  2s .  c  om

        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:gool.executor.Command.java

/**
 * Executes a command in the specified working directory.
 * /*from   w ww.j  a  v a2s . c om*/
 * @param workingDir
 *            the working directory.
 * @param params
 *            the command to execute and its parameters.
 * @return the console output.
 */
public static String exec(File workingDir, List<String> params, Map<String, String> env) {
    try {
        StringBuffer buffer = new StringBuffer();

        ProcessBuilder pb = new ProcessBuilder(params);
        pb.directory(workingDir);

        for (Entry<String, String> e : env.entrySet()) {
            pb.environment().put(e.getKey(), e.getValue());
        }
        Process p = pb.redirectErrorStream(true).start();

        p.getOutputStream().close();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line;
        while ((line = in.readLine()) != null) {
            buffer.append(line).append("\n");
        }

        int retval = p.waitFor();

        if (retval != 0) {
            throw new CommandException(
                    "The command execution returned " + retval + " as return value... !\n" + buffer);
        }

        return buffer.toString();
    } catch (IOException e) {
        throw new CommandException(e);
    } catch (InterruptedException e) {
        throw new CommandException("It seems the process was killed", e);
    }
}

From source file:uk.ac.kcl.iop.brc.core.pipeline.dncpipeline.service.PythonService.java

/**
 * Runs the Python interpreter.//from  ww  w.ja  v  a  2 s .com
 * @param args List of arguments to be supplied to the python command.
 * @return Result from python string
 * @throws IOException
 */
public String runFile(List<String> args) throws IOException {
    LinkedList<String> list = new LinkedList<>(args);
    list.addFirst("python");
    ProcessBuilder processBuilder = new ProcessBuilder(list);
    Process p = processBuilder.start();
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    StringWriter stringWriter = new StringWriter();
    in.lines().forEach(stringWriter::append);
    p.destroy();
    return stringWriter.toString();
}