Example usage for java.lang Process waitFor

List of usage examples for java.lang Process waitFor

Introduction

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

Prototype

public abstract int waitFor() throws InterruptedException;

Source Link

Document

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Usage

From source file:Main.java

public static int execRootCmdSilent(String cmd) {
    try {//from w  w  w. ja va  2 s. c  o  m
        Process p = Runtime.getRuntime().exec("su ");
        Object obj = p.getOutputStream();
        DataOutputStream dOutStream = new DataOutputStream((OutputStream) obj);
        String str = String.valueOf(cmd);
        obj = str + "\n";
        dOutStream.writeBytes((String) obj);
        dOutStream.flush();
        dOutStream.writeBytes("exit\n");
        dOutStream.flush();
        p.waitFor();
        int result = p.exitValue();
        return (Integer) result;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

From source file:Main.java

public static String sudoForResult(String... strings) {
    String res = "";
    DataOutputStream outputStream = null;
    InputStream response = null;//from  w w  w  .  j av  a  2 s.com
    try {
        Process su = Runtime.getRuntime().exec("su");
        outputStream = new DataOutputStream(su.getOutputStream());
        response = su.getInputStream();

        for (String s : strings) {
            outputStream.writeBytes(s + "\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        res = readFully(response);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        closeSilently(outputStream, response);
    }
    return res;
}

From source file:com.clustercontrol.platform.PlatformPertial.java

public static void setupHostname() {
    String hostname = null;/*from w w  w .j a v a2  s.co  m*/
    // hinemos.cfg???hostname?
    String etcDir = System.getProperty("hinemos.manager.etc.dir");
    if (etcDir != null) {
        File config = new File(etcDir, "hinemos.cfg");
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(config.getAbsolutePath());
            br = new BufferedReader(fr);

            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (line.trim().startsWith("MANAGER_HOST")) {
                    hostname = line.split("=")[1];
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            log.warn("configuration file not found." + config.getAbsolutePath(), e);
        } catch (IOException e) {
            log.warn("configuration read error." + config.getAbsolutePath(), e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }

            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                }
            }
        }
    }

    if (hostname == null || hostname.length() == 0) {
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        InputStreamReader is = null;
        BufferedReader br = null;

        try {
            process = runtime.exec("hostname");

            is = new InputStreamReader(process.getInputStream());
            br = new BufferedReader(is);
            process.waitFor();

            if (br != null) {
                hostname = br.readLine();
            }

        } catch (IOException | InterruptedException e) {
            log.warn("command execute error.", e);
        } finally {
            if (process != null) {
                process.destroy();
            }

            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }

    if (hostname == null) {
        hostname = "";
    }

    System.setProperty("hinemos.manager.hostname", hostname);
}

From source file:Main.java

public static boolean isRooted() {
    Process p;
    try {// w  ww. j av a  2s  .  c  om
        p = new ProcessBuilder("su").start();
        BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
        BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));

        stdin.write("whoami");
        stdin.newLine();
        stdin.write("exit");
        stdin.newLine();
        stdin.close();
        try {
            p.waitFor();
            if (!stdout.ready())
                return false;
            String user = stdout.readLine(); //We only expect one line of output
            stdout.close();
            if (user == "root") {
                return true;
            } else {
                return false;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:Main.java

public static void killProcesses(Context context, int pid, String processName) {

    String cmd = "kill -9 " + pid;
    String Command = "am force-stop " + processName + "\n";
    Process sh = null;
    DataOutputStream os = null;//from w  w  w  .ja v  a 2s.  c o m
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        os.writeBytes(Command + "\n");
        os.writeBytes(cmd + "\n");
        os.writeBytes("exit\n");
        os.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        sh.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // AbLogUtil.d(AbAppUtil.class, "#kill -9 "+pid);
    Log.i("AppUtil", processName);
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    String packageName = null;
    try {
        if (processName.indexOf(":") == -1) {
            packageName = processName;
        } else {
            packageName = processName.split(":")[0];
        }

        activityManager.killBackgroundProcesses(packageName);

        //
        Method forceStopPackage = activityManager.getClass().getDeclaredMethod("forceStopPackage",
                String.class);
        forceStopPackage.setAccessible(true);
        forceStopPackage.invoke(activityManager, packageName);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:TestFuseDFS.java

/**
 * Wait for the given process to return and check that it exited
 * as required. Log if the process failed.
 *//*w  w w .jav  a2  s .com*/
private static void checkProcessRet(Process p, boolean expectPass) throws IOException {
    try {
        int ret = p.waitFor();
        if (ret != 0) {
            dumpInputStream(p.getErrorStream());
        }
        if (expectPass) {
            assertEquals(0, ret);
        } else {
            assertTrue(ret != 0);
        }
    } catch (InterruptedException ie) {
        fail("Process interrupted: " + ie.getMessage());
    }
}

From source file:loadTest.loadTestLib.LUtil.java

public static boolean startDockerBuild() throws IOException, InterruptedException {
    if (useDocker) {
        if (runInDockerCluster) {

            HashMap<String, Integer> dockerNodes = getDockerNodes();
            String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString()
                    .substring(5);//  ww w . j  a  v a  2 s . c om
            ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size());

            dockerError = false;
            doneDockers = 0;

            for (Entry<String, Integer> entry : dockerNodes.entrySet()) {
                exec.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = entry.getKey() + "/images/vauvenal5/loadtest";
                            URL obj = new URL(url);
                            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("DELETE");
                            con.setRequestProperty("force", "true");
                            int responseCode = con.getResponseCode();
                            con.disconnect();

                            url = entry.getKey()
                                    + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile";
                            obj = new URL(url);
                            con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("POST");
                            con.setRequestProperty("Content-type", "application/tar");
                            con.setDoOutput(true);
                            File file = new File(dockerTar);
                            FileInputStream fileStr = new FileInputStream(file);
                            byte[] b = new byte[(int) file.length()];
                            fileStr.read(b);
                            con.getOutputStream().write(b);
                            con.getOutputStream().flush();
                            con.getOutputStream().close();

                            responseCode = con.getResponseCode();

                            if (responseCode != 200) {
                                dockerError = true;
                            }

                            String msg = "";

                            do {
                                Thread.sleep(5000);
                                msg = "";
                                url = entry.getKey() + "/images/json";
                                obj = new URL(url);
                                HttpURLConnection con2 = (HttpURLConnection) obj.openConnection();
                                con2.setRequestMethod("GET");
                                responseCode = con2.getResponseCode();

                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(con2.getInputStream()));
                                String line = null;

                                while ((line = in.readLine()) != null) {
                                    msg += line;
                                }

                                con2.disconnect();
                            } while (!msg.contains("vauvenal5/loadtest"));

                            con.disconnect();
                            doneDockers++;
                        } catch (MalformedURLException ex) {
                            dockerError = true;
                        } catch (FileNotFoundException ex) {
                            dockerError = true;
                        } catch (IOException ex) {
                            dockerError = true;
                        } catch (InterruptedException ex) {
                            dockerError = true;
                        }
                    }
                });
            }

            while (doneDockers < dockerNodes.size()) {
                Thread.sleep(5000);
            }

            return !dockerError;
        }

        //get the path and substring the 'file:' from the URI
        String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5);

        ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest");
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process docker = processBuilder.start();

        docker.waitFor();

        processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process proc = processBuilder.start();
        return proc.waitFor() == 0;
    }
    return true;
}

From source file:com.microsoftopentechnologies.intellij.helpers.AndroidStudioHelper.java

public static void deleteActivityTemplates(Object caller) throws IOException, InterruptedException {
    String[] cmd = null;//from   w ww . ja v a2s. com

    String templatePath = URLDecoder
            .decode(ApplicationComponent.class.getResource("").getPath().replace("file:/", ""), "UTF-8");
    templatePath = templatePath.replace("/", File.separator);
    templatePath = templatePath.substring(0, templatePath.indexOf(File.separator + "lib"));
    templatePath = templatePath + File.separator + "plugins" + File.separator + "android" + File.separator;
    templatePath = templatePath + "lib" + File.separator + "templates" + File.separator + "activities"
            + File.separator;

    String[] env = null;

    String tmpdir = getTempLocation();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(
            ServiceCodeReferenceHelper.getTemplateResource("ActivityTemplate.zip"));
    unZip(bufferedInputStream, tmpdir);

    if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
        try {
            VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
            VirtualFile officeTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + officeTemplateName));

            if (mobileTemplate != null)
                mobileTemplate.delete(caller);

            if (officeTemplate != null)
                officeTemplate.delete(caller);
        } catch (IOException ex) {
            PrintWriter printWriter = new PrintWriter(tmpdir + "\\script.bat");
            printWriter.println("@echo off");
            printWriter.println("del \"" + templatePath + mobileServicesTemplateName + "\" /Q /S");
            printWriter.println("del \"" + templatePath + officeTemplateName + "\" /Q /S");
            printWriter.flush();
            printWriter.close();

            String[] tmpcmd = { tmpdir + "\\elevate.exe", "script.bat", "1" };

            cmd = tmpcmd;

            ArrayList<String> tempenvlist = new ArrayList<String>();
            for (String envval : System.getenv().keySet())
                tempenvlist.add(String.format("%s=%s", envval, System.getenv().get(envval)));

            tempenvlist.add("PRECOMPILE_STREAMLINE_FILES=1");
            env = new String[tempenvlist.size()];
            tempenvlist.toArray(env);

            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd, env, new File(tmpdir));
            proc.waitFor();
        }
    } else if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {
        VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
        VirtualFile officeTemplate = LocalFileSystem.getInstance()
                .findFileByIoFile(new File(templatePath + officeTemplateName));

        if (mobileTemplate != null && officeTemplate != null) {
            exec(new String[] { "osascript", "-e",
                    "do shell script \"rm -r \\\"/" + templatePath + mobileServicesTemplateName + "\\\"\"",
                    "-e", "do shell script \"rm -r \\\"/" + templatePath + officeTemplateName + "\\\"\"" },
                    tmpdir);
        }
    } else {
        try {
            VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
            VirtualFile officeTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + officeTemplateName));

            mobileTemplate.delete(caller);
            officeTemplate.delete(caller);
        } catch (IOException ex) {

            JPasswordField pf = new JPasswordField();
            int okCxl = JOptionPane.showConfirmDialog(null, pf,
                    "To copy Microsoft Services templates, the plugin needs your password:",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

            if (okCxl == JOptionPane.OK_OPTION) {
                String password = new String(pf.getPassword());

                exec(new String[] { "echo", password, "|", "sudo", "-S", "rm", "-r",
                        tmpdir + mobileServicesTemplateName, templatePath + mobileServicesTemplateName },
                        tmpdir);

                exec(new String[] { "echo", password, "|", "sudo", "-S", "rm", "-r",
                        tmpdir + officeTemplateName, templatePath + officeTemplateName }, tmpdir);
            }
        }
    }
}

From source file:jGPIO.DTO.java

/**
 * Tries to use lshw to detect the physical system in use.
 * //from  ww w  .j  a  v a2s  .  c  om
 * @return The filename of the GPIO Definitions file.
 */
static private String autoDetectSystemFile() {
    String definitions = System.getProperty("definitions.lookup");
    if (definitions == null) {
        definitions = DEFAULT_DEFINITIONS;
    }

    File capabilitiesFile = new File(definitions);

    // If it doesn't exist, fall back to the default
    if (!capabilitiesFile.exists() && !definitions.equals(DEFAULT_DEFINITIONS)) {
        System.out.println("Could not find definitions lookup file at: " + definitions);
        System.out.println("Trying default definitions file at: " + definitions);
        capabilitiesFile = new File(DEFAULT_DEFINITIONS);
    }

    if (!capabilitiesFile.exists()) {
        System.out.println("Could not find definitions file at: " + definitions);
        return null;
    }

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e1) {
        e1.printStackTrace();
    }

    // Generate the lshw output if available
    Process lshw;
    try {
        lshw = Runtime.getRuntime().exec("lshw -c bus -disable dmi -xml");
        lshw.waitFor();
    } catch (Exception e1) {
        System.out.println("Couldn't execute lshw to identify board");
        e1.printStackTrace();
        return null;
    }
    Document lshwXML = null;
    try {
        lshwXML = dBuilder.parse(lshw.getInputStream());
    } catch (IOException e1) {
        System.out.println("IO Exception running lshw");
        e1.printStackTrace();
        return null;
    } catch (SAXException e1) {
        System.out.println("Could not parse lshw output");
        e1.printStackTrace();
        return null;
    }

    XPath xp = XPathFactory.newInstance().newXPath();
    NodeList capabilities;
    try {
        capabilities = (NodeList) xp.evaluate("/list/node[@id=\"core\"]/capabilities/capability", lshwXML,
                XPathConstants.NODESET);
    } catch (XPathExpressionException e1) {
        System.out.println("Couldn't run Caoability lookup");
        e1.printStackTrace();
        return null;
    }

    Document lookupDocument = null;
    try {
        lookupDocument = dBuilder.parse(capabilitiesFile);
        String lookupID = null;

        for (int i = 0; i < capabilities.getLength(); i++) {
            Node c = capabilities.item(i);
            lookupID = c.getAttributes().getNamedItem("id").getNodeValue();
            System.out.println("Looking for: " + lookupID);
            NodeList nl = (NodeList) xp.evaluate("/lookup/capability[@id=\"" + lookupID + "\"]", lookupDocument,
                    XPathConstants.NODESET);

            if (nl.getLength() == 1) {
                definitionFile = nl.item(0).getAttributes().getNamedItem("file").getNodeValue();
                pinDefinitions = (JSONArray) new JSONParser().parse(new FileReader(definitionFile));
                return definitionFile;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.microsoftopentechnologies.intellij.helpers.AndroidStudioHelper.java

public static void newActivityTemplateManager() throws IOException, InterruptedException {
    String[] cmd = null;// w  ww.j  a  v a  2 s .c  om

    String templatePath = URLDecoder
            .decode(ApplicationComponent.class.getResource("").getPath().replace("file:/", ""), "UTF-8");
    templatePath = templatePath.replace("/", File.separator);
    templatePath = templatePath.substring(0, templatePath.indexOf(File.separator + "lib"));
    templatePath = templatePath + File.separator + "plugins" + File.separator + "android" + File.separator;
    templatePath = templatePath + "lib" + File.separator + "templates" + File.separator + "activities"
            + File.separator;

    String[] env = null;

    if (!new File(templatePath + mobileServicesTemplateName).exists()) {
        String tmpdir = getTempLocation();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(
                ServiceCodeReferenceHelper.getTemplateResource("ActivityTemplate.zip"));
        unZip(bufferedInputStream, tmpdir);

        if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
            try {
                copyFolder(new File(tmpdir + mobileServicesTemplateName),
                        new File(templatePath + mobileServicesTemplateName));
                copyFolder(new File(tmpdir + officeTemplateName), new File(templatePath + officeTemplateName));
            } catch (IOException ex) {
                PrintWriter printWriter = new PrintWriter(tmpdir + "\\script.bat");
                printWriter.println("@echo off");
                printWriter.println("md \"" + templatePath + mobileServicesTemplateName + "\"");
                printWriter.println("md \"" + templatePath + officeTemplateName + "\"");
                printWriter.println("xcopy \"" + tmpdir + mobileServicesTemplateName + "\" \"" + templatePath
                        + mobileServicesTemplateName + "\" /s /i /Y");
                printWriter.println("xcopy \"" + tmpdir + officeTemplateName + "\" \"" + templatePath
                        + officeTemplateName + "\" /s /i /Y");
                printWriter.flush();
                printWriter.close();

                String[] tmpcmd = { tmpdir + "\\elevate.exe", "script.bat", "1" };

                cmd = tmpcmd;

                ArrayList<String> tempenvlist = new ArrayList<String>();
                for (String envval : System.getenv().keySet())
                    tempenvlist.add(String.format("%s=%s", envval, System.getenv().get(envval)));

                tempenvlist.add("PRECOMPILE_STREAMLINE_FILES=1");
                env = new String[tempenvlist.size()];
                tempenvlist.toArray(env);

                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(cmd, env, new File(tmpdir));
                proc.waitFor();

                //wait for elevate command to finish
                Thread.sleep(3000);

                if (!new File(templatePath + mobileServicesTemplateName).exists())
                    UIHelper.showException(
                            "Error copying template files. Please refer to documentation to copy manually.",
                            new Exception());
            }
        } else {
            if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {

                String[] strings = { "osascript",
                        //        "-e",
                        //        "do shell script \"mkdir -p \\\"/" + templatePath + mobileServicesTemplateName + "\\\"\"",
                        //        "-e",
                        //        "do shell script \"mkdir -p \\\"/" + templatePath + officeTemplateName + "\\\"\"",
                        "-e",
                        "do shell script \"cp -Rp \\\"" + tmpdir + mobileServicesTemplateName + "\\\" \\\"/"
                                + templatePath + "\\\"\"",
                        "-e", "do shell script \"cp -Rp \\\"" + tmpdir + officeTemplateName + "\\\" \\\"/"
                                + templatePath + "\\\"\"" };

                exec(strings, tmpdir);
            } else {
                try {

                    copyFolder(new File(tmpdir + mobileServicesTemplateName),
                            new File(templatePath + mobileServicesTemplateName));
                    copyFolder(new File(tmpdir + officeTemplateName),
                            new File(templatePath + officeTemplateName));

                } catch (IOException ex) {

                    JPasswordField pf = new JPasswordField();
                    int okCxl = JOptionPane.showConfirmDialog(null, pf,
                            "To copy Microsoft Services templates, the plugin needs your password:",
                            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

                    if (okCxl == JOptionPane.OK_OPTION) {
                        String password = new String(pf.getPassword());

                        exec(new String[] { "echo", password, "|", "sudo", "-S", "cp", "-Rp",
                                tmpdir + mobileServicesTemplateName,
                                templatePath + mobileServicesTemplateName }, tmpdir);

                        exec(new String[] { "echo", password, "|", "sudo", "-S", "cp", "-Rp",
                                tmpdir + officeTemplateName, templatePath + officeTemplateName }, tmpdir);
                    }
                }
            }
        }
    }
}