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:dk.netarkivet.common.utils.ProcessUtils.java

/** Runs an external process that takes no input, discarding its output.
 *
 * @param environment An environment to run the process in (may be null)
 * @param programAndArgs The program and its arguments.
 * @return The return code of the process.
 *//*from ww w  . j ava2s . com*/
public static int runProcess(String[] environment, String... programAndArgs) {
    try {
        log.debug("Running external program: " + StringUtils.conjoin(" ", programAndArgs) + " with environment "
                + StringUtils.conjoin(" ", environment));

        Process p = Runtime.getRuntime().exec(programAndArgs, environment);
        discardProcessOutput(p.getInputStream());
        discardProcessOutput(p.getErrorStream());
        while (true) {
            try {
                return p.waitFor();
            } catch (InterruptedException e) {
                // Ignoring interruptions, we just want to try waiting
                // again.
            }
        }
    } catch (IOException e) {
        throw new IOFailure("Failure while running " + Arrays.toString(programAndArgs), e);
    }
}

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  ww.j  av  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) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        sh.waitFor();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // AbLogUtil.d(AbAppUtil.class, "#kill -9 "+pid);
    // L.i(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:com.github.pemapmodder.pocketminegui.utils.Utils.java

private static File installLinuxPHP(File home, InstallProgressReporter progress) {
    progress.report(0.0);/*from  w  ww . ja  v a2 s  .  c o  m*/
    File bin = new File(home, ".pmgui_tmp_pm_linux_installer");
    bin.mkdirs();
    try {
        InputStream get = new URL("http", "get.pocketmine.net", "").openStream();
        Process bash = new ProcessBuilder("bash -s - -v development").directory(bin)
                .redirectOutput(ProcessBuilder.Redirect.INHERIT).redirectError(ProcessBuilder.Redirect.INHERIT)
                .start();
        progress.report(0.25);
        byte[] bytes = IOUtils.toByteArray(get);
        progress.report(0.5);
        bash.getOutputStream().write(bytes);
        int result = bash.waitFor();
        progress.report(0.75);
        if (result == 0) {
            File out = new File(bin, "bin");
            FileUtils.copyDirectory(out, new File(home, "bin"));
            FileUtils.deleteDirectory(bin);
            File output = new File(out, "php7/bin/php");
            progress.completed(output);
            return output;
        } else {
            FileUtils.deleteDirectory(bin);
            return null;
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
        try {
            FileUtils.deleteDirectory(bin);
        } catch (IOException e1) {
        }
        return null;
    }
}

From source file:com.floragunn.searchguard.util.SecurityUtil.java

public static boolean isRootUser() {

    boolean isRoot = false;

    int exitValue = -1;
    String result = null;/*from  ww  w . j  av  a2  s.  co  m*/

    try {
        final Process p = Runtime.getRuntime().exec("id -u");
        result = IOUtils.toString(p.getInputStream());
        exitValue = p.waitFor();
        p.destroy();
    } catch (final Exception e) {
        //ignore
    }

    if (exitValue == 0 && result != null) {
        isRoot = "0".equals(result.trim());
    }

    if (!isRoot) {
        return isWindowsAdmin();
    } else {
        return true;
    }
}

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

private static void exec(String[] cmd, String tmpdir) throws IOException, InterruptedException {
    String[] env = new String[] { "PRECOMPILE_STREAMLINE_FILES=1" };

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

    // any error message?
    StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), true);

    // kick them off
    errorGobbler.start();//w w w. ja  v a2  s  .co m

    proc.waitFor();
}

From source file:Main.java

public static int execRootCmdForExitCode(String[] cmds) {
    int result = -1;
    DataOutputStream dos = null;/*from w w w  .java2s.com*/
    DataInputStream dis = null;

    try {
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());
        dis = new DataInputStream(p.getInputStream());

        for (String cmd : cmds) {
            Log.i("CmdUtils", cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
        }
        dos.writeBytes("exit\n");
        dos.flush();
        String line;
        while ((line = dis.readLine()) != null) {
            Log.d("result", line);
        }
        p.waitFor();
        result = p.exitValue();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:io.werval.cli.DamnSmallDevShell.java

static void rebuild(URL[] applicationClasspath, URL[] runtimeClasspath, Set<File> sourcesRoots,
        File classesDir) {/*from w  w w  .  j  a v  a2  s.  c  om*/
    System.out.println("Compiling Application...");
    String javacOutput = EMPTY;
    try {
        // Collect java files
        String javaFiles = EMPTY;
        for (File sourceRoot : sourcesRoots) {
            if (sourceRoot.exists()) {
                ProcessBuilder findBuilder = new ProcessBuilder("find", sourceRoot.getAbsolutePath(), "-type",
                        "f", "-iname", "*.java");
                Process find = findBuilder.start();
                int returnCode = find.waitFor();
                if (returnCode != 0) {
                    throw new IOException("Unable to find java source files in " + sourceRoot);
                }
                javaFiles += NEWLINE + readAllAsString(find.getInputStream(), 4096, UTF_8);
            }
        }
        if (hasText(javaFiles)) {
            // Write list in a temporary file
            File javaListFile = new File(classesDir, ".devshell-java-list");
            try (FileWriter writer = new FileWriter(javaListFile)) {
                writer.write(javaFiles);
                writer.close();
            }
            // Compile
            String[] classpathStrings = new String[runtimeClasspath.length];
            for (int idx = 0; idx < runtimeClasspath.length; idx++) {
                classpathStrings[idx] = runtimeClasspath[idx].toURI().toASCIIString();
            }
            ProcessBuilder javacBuilder = new ProcessBuilder("javac", "-encoding", "UTF-8", "-source", "1.8",
                    "-d", classesDir.getAbsolutePath(), "-classpath", join(classpathStrings, ":"),
                    "@" + javaListFile.getAbsolutePath());
            Process javac = javacBuilder.start();
            int returnCode = javac.waitFor();
            if (returnCode != 0) {
                throw new IOException("Unable to build java source files.");
            }
            javacOutput = readAllAsString(javac.getInputStream(), 4096, UTF_8);
        }
    } catch (InterruptedException | IOException | URISyntaxException ex) {
        throw new WervalException("Unable to rebuild" + (isEmpty(javacOutput) ? "" : "\n" + javacOutput), ex);
    }
}

From source file:mx.itesm.imb.EcoreImbEditor.java

/**
 * //from w w  w  . j  a va 2 s. c  o  m
 * @param command
 * @param baseDir
 * @return
 */
private static void executeCommand(final String command, final File baseDir) throws Exception {
    Process process;
    int processCode;

    process = Runtime.getRuntime().exec(command, null, baseDir);
    processCode = process.waitFor();
    if (processCode != 0) {
        throw new RuntimeException("Unable to execute: " + command + ", in: " + baseDir);
    }
}

From source file:kr.ac.kaist.wala.hybridroid.analysis.resource.AndroidDecompiler.java

private static void permission(String path) {
    String[] cmd = { "chmod", "755", path };
    ProcessBuilder pb = new ProcessBuilder();
    pb.command(cmd);/*from w  ww . java 2s.  c  o m*/

    Process p = null;
    try {
        p = pb.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String r = null;

        while ((r = br.readLine()) != null) {
            System.out.println(r);
        }

        while ((r = bre.readLine()) != null) {
            System.err.println(r);
        }

        int res = p.waitFor();
        if (res != 0) {
            throw new InternalError("failed to decompile: " + path);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.clavain.alerts.Methods.java

public static boolean sendTTSMessage(String message, String mobile_nr) {
    boolean retval = false;

    try {//from  ww  w. java2  s.  c o m
        if (p.getProperty("tts.provider").equals("smsflatrate")) {
            String key = p.getProperty("smsflatrate.key");
            String gw = p.getProperty("smsflatrate.ttsgw");

            String msg = URLEncoder.encode(message);
            URL url = new URL("http://smsflatrate.net/schnittstelle.php?key=" + key + "&to=" + mobile_nr
                    + "&voice=Dave&repeat=2&rate=1&type=" + gw + "&text=" + msg);
            URLConnection conn = url.openConnection();
            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            String resp = "";
            while ((inputLine = br.readLine()) != null) {
                resp = inputLine;
            }
            //conn.getContent();      
            if (resp.trim().equals("100")) {
                retval = true;
            }
        } else if (p.getProperty("tts.provider").equals("script")) {
            List<String> commands = new ArrayList<String>();
            // add global timeout script
            commands.add(p.getProperty("tts.script"));
            commands.add(mobile_nr);
            commands.add(message);
            ProcessBuilder pb = new ProcessBuilder(commands).redirectErrorStream(true);
            logger.info("tts.script - Running: " + commands);
            Process p = pb.start();
            Integer rv = p.waitFor();

        }
    } catch (Exception ex) {
        retval = false;
        logger.error("sendTTSMessage Error: " + ex.getLocalizedMessage());
    }
    return retval;
}