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:com.kylinolap.common.util.CliCommandExecutor.java

private Pair<Integer, String> runNativeCommand(String command) throws IOException {
    String[] cmd = new String[3];
    String osName = System.getProperty("os.name");
    if (osName.startsWith("Windows")) {
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
    } else {/*  ww w  .  ja va2s.c  om*/
        cmd[0] = "/bin/bash";
        cmd[1] = "-c";
    }
    cmd[2] = command;

    ProcessBuilder builder = new ProcessBuilder(cmd);
    builder.redirectErrorStream(true);
    Process proc = builder.start();

    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    IOUtils.copy(proc.getInputStream(), buf);
    String output = buf.toString("UTF-8");

    try {
        int exitCode = proc.waitFor();
        return new Pair<Integer, String>(exitCode, output);
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:ca.canucksoftware.systoolsmgr.CommandLine.java

public boolean doCmd() {
    try {//w  w w .j a v  a 2 s  .  co  m
        response = null;
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(false);
        Process p = pb.start();
        String stdout = getTextFromStream(p.getInputStream());
        String stderr = getTextFromStream(p.getErrorStream());
        if (p.waitFor() != 0) {
            returnCode = p.exitValue();
        } else {
            returnCode = 0;
        }
        if (returnCode == 0) {
            response = stdout;
        } else {
            response = stderr;
        }
    } catch (Exception e) {
        response = e.getMessage();
        returnCode = -1;
    }
    return (returnCode == 0);
}

From source file:org.anarres.qemu.image.QEmuImage.java

/**
 * Creates this image.//w  ww  .j  a v a2 s  .c  o  m
 * <p>
 * The size of the new image is derived from the existing backing file.
 * <p>
 * backingFile is referenced by a relative path. If you want it referenced
 * absolutely, canonicalize the argument with {@link File#getAbsoluteFile()}
 * before calling this method.
 *
 * @param format      The image format for the new image.
 * @param backingFile The backing file for the new image.
 */
public void create(@Nonnull QEmuImageFormat format, @Nonnull File backingFile) throws IOException {
    ProcessBuilder builder = new ProcessBuilder("qemu-img", "create", "-f", format.name(), "-b",
            backingFile.getPath(), file.getAbsolutePath());
    Process process = builder.start();
    ByteStreams.copy(process.getInputStream(), System.err);
}

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

public ProcessOutput execute(boolean logCommand, String... arguments) {
    try {//from w ww.  j  a v a 2 s. c  o  m
        List<String> commandWithArguments = getProcessArguments(arguments);

        ProcessBuilder processBuilder = createProcessBuilder(commandWithArguments);
        Process process = processBuilder.start();
        OutputProcessor outputProcessor = new OutputProcessor(process);
        outputProcessor.start();
        process.waitFor();

        String output = outputProcessor.getOutput();
        int exitValue = process.exitValue();

        logOutput(commandWithArguments, output, logCommand);
        return new ProcessOutput(output, exitValue);

    } catch (Exception e) {
        throw new MigrateBirdException("Failed to execute command.", e);
    }
}

From source file:com.sixt.service.framework.logging.ServicePropertiesProvider.java

/**
 * If running in docker, use that; else, generate test_service
 *//*from w  w w .j  a v  a2s  .  co  m*/
private void parseServiceInstance() {
    try {
        ProcessBuilder pb = new ProcessBuilder("bash", "-c",
                "cat /proc/self/cgroup | grep docker | sed 's/^.*\\///' | tail -n1 | cut -c 1-12");
        Process p = pb.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String output = reader.readLine();
        if (!StringUtils.isBlank(output)) {
            serviceInstanceId = output.trim();
        }
        p.waitFor();
    } catch (Exception e) {
        System.err.println("Error getting docker container id");
        e.printStackTrace();
    }
    if (serviceInstanceId == null) {
        serviceInstanceId = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 12);
    }
}

From source file:com.teradata.benchto.driver.macro.shell.ShellMacroExecutionDriver.java

public void runBenchmarkMacro(String macroName, Map<String, String> environment) {
    try {//from  ww w.  j av a  2s. co m
        String macroCommand = getMacroCommand(macroName);
        ProcessBuilder processBuilder = new ProcessBuilder(SHELL, "-c", macroCommand);
        processBuilder.environment().putAll(environment);
        Process macroProcess = processBuilder.start();
        LOGGER.info("Executing macro: '{}'", macroCommand);
        macroProcess.waitFor();
        boolean completedSuccessfully = macroProcess.exitValue() == 0;
        printOutput(macroProcess, !completedSuccessfully);
        checkState(completedSuccessfully, "Macro %s exited with code %s", macroName, macroProcess.exitValue());
    } catch (IOException | InterruptedException e) {
        throw new BenchmarkExecutionException("Could not execute macro " + macroName, e);
    }
}

From source file:ape.KillNodeCommand.java

public boolean runImpl(String[] args) throws ParseException, IOException {
    if (Main.VERBOSE) {
        System.out.println("NodeType: " + args[0]);
    }/*from  ww w .j  a va2  s .  c om*/

    String nodeType = args[0];

    if (nodeType.toLowerCase().equals("datanode") || nodeType.toLowerCase().equals("tasktracker")
            || nodeType.toLowerCase().equals("jobtracker") || nodeType.toLowerCase().equals("namenode")) {
        System.out.println("Kill is about to execute the following command:");

        /**
         * The line of code below sends a very ugly bash command to kill the corresponding process.
         * It gets a list of running processes, then greps it for the node type, then 
         * removes the result generated by running grep, then it gets the process ID of that line 
         * 
         */
        String cmd = "echo \"kill -9 \\$(ps -ef | grep -i " + nodeType
                + " | grep -v grep | grep -v ape | awk -F ' '  '{print \\$2}')\" > /tmp/kill-node.sh && chmod +x /tmp/kill-node.sh && /tmp/./kill-node.sh && rm /tmp/kill-node.sh";

        System.out.println(cmd);

        ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
        pb.redirectErrorStream(true);
        Process sh = pb.start();
        InputStream shIn = sh.getInputStream();
        try {
            if (sh.waitFor() != 0) {
                System.out.println("Executing Kill Command failed");
                return false;
            }
        } catch (InterruptedException e) {
            System.out.println(
                    "The kill command was killed before it could kill its target process.  Kind of ironic really...");
            e.printStackTrace();
            throw new RuntimeException();
        }
        int c;
        while ((c = shIn.read()) != -1) {
            System.out.write(c);
        }
        try {
            shIn.close();
        } catch (IOException e) {
            System.out.println("Could not close InputStream from the kill process.");
            e.printStackTrace();
            return false;
        }
    }

    else {
        System.out.println("Invalid node type: " + nodeType);
        System.out.println("Should be one of the following: DataNode, TaskTracker, NameNode, JobTracker.");
        return false;
    }
    return true;
}

From source file:com.thebuzzmedia.exiftool.ExifToolNew3.java

/**
 * There is a bug that prevents exiftool to read unicode file names. We can get the windows filename if necessary
 * with getMSDOSName/*from   w  w w .  j a v a  2  s.co m*/
 * 
 * @link(http://perlmaven.com/unicode-filename-support-suggested-solution)
 * @link(http://stackoverflow.com/questions/18893284/how-to-get-short-filenames-in-windows-using-java)
 */
public static String getMSDOSName(File file) {
    try {
        String path = getAbsolutePath(file);
        String path2 = file.getAbsolutePath();
        System.out.println(path2);
        // String toExecute = "cmd.exe /c for %I in (\"" + path2 + "\") do @echo %~fsI";
        // ProcessBuilder pb = new ProcessBuilder("cmd","/c","for","%I","in","(" + path2 + ")","do","@echo","%~sI");
        path2 = new File(
                "d:\\aaaaaaaaaaaaaaaaaaaaaaaaaaaa\\bbbbbbbbbbbbbbbbbb\\2013-12-22--12-10-42------Bulevardul-Petrochimitilor.jpg")
                        .getAbsolutePath();
        path2 = new File(
                "d:\\personal\\photos-tofix\\2013-proposed1-bad\\2013-12-22--12-10-42------Bulevardul-Petrochimitilor.jpg")
                        .getAbsolutePath();

        System.out.println(path2);
        ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "for", "%I", "in", "(\"" + path2 + "\")", "do",
                "@echo", "%~fsI");
        // ProcessBuilder pb = new ProcessBuilder("cmd","/c","chcp 65001 & dir",path2);
        // ProcessBuilder pb = new ProcessBuilder("cmd","/c","ls",path2);
        Process process = pb.start();
        // Process process = Runtime.getRuntime().exec(execLine);
        // Process process = Runtime.getRuntime().exec(new String[]{"cmd","/c","for","%I","in","(\"" + path2 +
        // "\")","do","@echo","%~fsI"});
        process.waitFor();
        byte[] data = new byte[65536];
        // InputStreamReader isr = new InputStreamReader(process.getInputStream(), "UTF-8");
        // String charset = Charset.defaultCharset().name();
        String charset = "UTF-8";
        String lines = IOUtils.toString(process.getInputStream(), charset);
        // int size = process.getInputStream().read(data);
        // String path3 = path;
        // if (size > 0)
        // path3 = new String(data, 0, size).replaceAll("\\r\\n", "");
        String path3 = lines;
        System.out.println(pb.command());
        System.out.println(path3);
        byte[] data2 = new byte[65536];
        int size2 = process.getErrorStream().read(data2);
        if (size2 > 0) {
            String error = new String(data2, 0, size2);
            System.out.println(error);
            throw new RuntimeException("Error was thrown " + error);
        }
        return path3;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:backtype.storm.utils.ShellProcess.java

public Number launch(Map conf, TopologyContext context) throws IOException {
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(new File(context.getCodeDir()));
    _subprocess = builder.start();

    processIn = new DataOutputStream(_subprocess.getOutputStream());
    processOut = new BufferedReader(new InputStreamReader(_subprocess.getInputStream()));
    processErrorStream = _subprocess.getErrorStream();

    JSONObject setupInfo = new JSONObject();
    setupInfo.put("pidDir", context.getPIDDir());
    setupInfo.put("conf", conf);
    setupInfo.put("context", context);
    writeMessage(setupInfo);/*ww  w  .j a va  2  s .co m*/

    return (Number) readMessage().get("pid");
}

From source file:es.ua.dlsi.patch.translation.LocalApertiumTranslator.java

public Map<String, Set<String>> getTranslation(final Set<String> inputset) {
    Map<String, Set<String>> dictionary = new HashMap<>();
    if (!inputset.isEmpty()) {
        try {//from w  ww  . j a va2  s . c o m
            StringBuilder sb = new StringBuilder();
            List<String> input = new LinkedList<>(inputset);
            for (String s : input) {
                sb.append("<p>");
                sb.append(s);
                sb.append("</p>");
            }

            //String[] command = {"apertium", "-u", "-f html", langCmd};

            ProcessBuilder probuilder = new ProcessBuilder("apertium", "-u", "-fhtml", langCmd);

            Process process = probuilder.start();
            OutputStream stdin = process.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
            writer.write(sb.toString());
            writer.flush();
            writer.close();

            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuilder finalline = new StringBuilder();

            while ((line = br.readLine()) != null) {
                finalline.append(line);
            }
            br.close();
            String finaltranslation = StringEscapeUtils
                    .unescapeHtml3(finalline.toString().replaceAll("\\s<", "<").replaceAll(">\\s", ">")
                            .replaceAll("^<p>", "").replace("</p>", ""));
            List<String> translations = new LinkedList<>(Arrays.asList(finaltranslation.split("<p>")));
            for (int i = 0; i < translations.size(); i++) {
                if (dictionary.containsKey(input.get(i))) {
                    dictionary.get(input.get(i)).add(translations.get(i));
                } else {
                    Set<String> trans_set = new HashSet<>();
                    trans_set.add(translations.get(i));
                    dictionary.put(input.get(i), trans_set);
                }
            }

        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }
    return dictionary;
}