Example usage for java.lang Process getInputStream

List of usage examples for java.lang Process getInputStream

Introduction

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

Prototype

public abstract InputStream getInputStream();

Source Link

Document

Returns the input stream connected to the normal output of the process.

Usage

From source file:Main.java

public static int findProcessIdWithPS(String command) throws Exception {

    int procId = -1;

    Runtime r = Runtime.getRuntime();

    Process procPs;

    procPs = r.exec(SHELL_CMD_PS);//from   w ww  . ja v a 2 s.c  o m

    BufferedReader reader = new BufferedReader(new InputStreamReader(procPs.getInputStream()));
    String line;

    while ((line = reader.readLine()) != null) {
        if (line.contains(' ' + command)) {

            StringTokenizer st = new StringTokenizer(line, " ");
            st.nextToken(); // proc owner

            procId = Integer.parseInt(st.nextToken().trim());

            break;
        }
    }

    return procId;

}

From source file:Main.java

public static String sudoForResult(String... strings) {
    String res = "";
    DataOutputStream outputStream = null;
    InputStream response = null;/*from  w ww.  j a v  a2  s. c o m*/
    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:Main.java

public static String getCustomROM() {
    String line;//  w  w w  . j  a v  a  2 s  .c o  m
    BufferedReader input = null;
    StringBuilder sb = new StringBuilder();
    String version = Build.VERSION.RELEASE;
    try {
        Process process = Runtime.getRuntime().exec("getprop ro.build.description");
        input = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"), 1024);
        line = input.readLine();
        if (line == null || line.length() == 0) {
            return null;
        }
        String[] s = line.split("\\s");
        for (int i = 0; i < s.length; i++) {
            if (!s[i].equals(version) && !s[i].contains("key")) {
                sb.append(s[i] + " ");
            }
        }
        input.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return sb.toString();
}

From source file:com.sec.ose.osi.UIMain.java

private static boolean isRunning() {
    log.debug("Running Test...");
    String execCMD = "";
    String protexStr = "";
    String osName = System.getProperty("os.name").toLowerCase();
    if (osName.indexOf("win") >= 0) {
        // windows
        execCMD = "TASKLIST /V /FO CSV /FI \"IMAGENAME eq javaw.exe\" /NH";
        protexStr = "osit";
    } else if (osName.indexOf("nix") >= 0 || osName.indexOf("nux") >= 0) {
        execCMD = "ps -ef";
        protexStr = "java -jar ./lib/" + OSIT_JAR_FILE_NAME;
    } else {//from w  w  w  . j  a v  a2  s .c om
        JOptionPane.showMessageDialog(null, osName + " is not supported. The program will be closed.", "Error",
                JOptionPane.ERROR_MESSAGE);
        //         System.exit(-1);
    }

    InputStreamReader isr = null;
    try {
        Process p = Runtime.getRuntime().exec(execCMD);
        isr = new InputStreamReader(p.getInputStream(), "UTF-8");
        BufferedReader reader = new BufferedReader(isr);

        String str = null;
        int count = 0;
        while ((str = reader.readLine()) != null) {
            log.debug("### ONLY ONE OSI PROCESS CHECK : " + str.toLowerCase());
            if (str.toLowerCase().contains(protexStr.toLowerCase())) {
                if (++count > 1) {
                    reader.close();
                    return true;
                }
            }
        }
    } catch (IOException e1) {
        log.warn(e1.getMessage());
    } finally {
        try {
            if (isr != null) {
                isr.close();
            }
        } catch (Exception e) {
            log.debug(e);
        }
    }
    return false;
}

From source file:Main.java

@SuppressLint("HardwareIds")
static String getPhoneMacAddress(Context context) {
    String mac = "";

    InputStreamReader inputStreamReader = null;
    LineNumberReader lineNumberReader = null;
    try {//from  w w  w.  ja v a2  s.c o  m
        @SuppressLint("WifiManagerPotentialLeak")
        WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = manager.getConnectionInfo();
        mac = info.getMacAddress();

        if (TextUtils.isEmpty(mac)) {
            Process process = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
            inputStreamReader = new InputStreamReader(process.getInputStream());
            lineNumberReader = new LineNumberReader(inputStreamReader);
            String line = lineNumberReader.readLine();
            if (line != null) {
                mac = line.trim();
            }
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (lineNumberReader != null) {
            try {
                lineNumberReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    if (TextUtils.isEmpty(mac)) {
        mac = "na";
    }

    return mac;
}

From source file:net.dv8tion.jda.player.Playlist.java

public static Playlist getPlaylist(String url) {
    List<String> infoArgs = new LinkedList<>();
    infoArgs.addAll(YOUTUBE_DL_PLAYLIST_ARGS);
    infoArgs.add("--"); //Url separator. Deals with YT ids that start with --
    infoArgs.add(url);//from   ww w.  j av  a  2  s .  c o m

    //Fire up Youtube-dl and get all sources from the provided url.
    List<AudioSource> sources = new ArrayList<>();
    Scanner scan = null;
    try {
        Process infoProcess = new ProcessBuilder().command(infoArgs).start();
        byte[] infoData = IOUtils.readFully(infoProcess.getInputStream(), -1, false);
        if (infoData == null || infoData.length == 0)
            throw new NullPointerException(
                    "The YT-DL playlist process resulted in a null or zero-length INFO!");

        String sInfo = new String(infoData);
        scan = new Scanner(sInfo);

        JSONObject source = new JSONObject(scan.nextLine());
        if (source.has("_type"))//Is a playlist
        {
            sources.add(new RemoteSource(source.getString("url")));
            while (scan.hasNextLine()) {
                source = new JSONObject(scan.nextLine());
                sources.add(new RemoteSource(source.getString("url")));
            }
        } else //Single source link
        {
            sources.add(new RemoteSource(source.getString("webpage_url")));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }

    //Now that we have all the sources we can create our Playlist object.
    Playlist playlist = new Playlist("New Playlist");
    playlist.sources = sources;
    return playlist;
}

From source file:com.ms.commons.utilities.CoreUtilities.java

/**
 * ?Linux?IP//from   w  w  w  .  jav  a2  s  .c  om
 * 
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
private static String getIfconig() throws IOException, InterruptedException {
    String cmd = "/sbin/ifconfig";
    Process process = Runtime.getRuntime().exec(cmd);
    process.waitFor();
    InputStream in = process.getInputStream();
    InputStreamReader inr = new InputStreamReader(in);
    BufferedReader br = new BufferedReader(inr);
    String wg = "";
    while (true) {
        String line = br.readLine();
        if (line == null) {
            break;
        }
        if (line.indexOf("inet addr") != -1 || line.indexOf("inet ?") != -1) {
            wg = line.substring(line.indexOf(":") + 1, line.length());
            wg = wg.trim();
            int index = wg.indexOf("Bcast");
            if (index == -1) {
                index = wg.indexOf("");
            }
            if (index != -1) {
                wg = wg.substring(0, index);
                wg = wg.trim();
                break;
            } else {
                if (wg.length() > 14) {
                    wg = wg.substring(0, 14);
                }
            }
        }
    }
    return wg.trim();
}

From source file:com.act.utils.ProcessRunner.java

/**
 * Run's a child process using the specified command and arguments, timing out after a specified number of seconds
 * if the process does not terminate on its own in that time.
 * @param command The process to run.//ww w  .  ja  va  2  s.  c o  m
 * @param args The arguments to pass to that process.
 * @param timeoutInSeconds A timeout to impose on the child process; an InterruptedException is likely to occur
 *                         when the child process times out.
 * @return The exit code of the child process.
 * @throws InterruptedException
 * @throws IOException
 */
public static int runProcess(String command, List<String> args, Long timeoutInSeconds)
        throws InterruptedException, IOException {
    /* The ProcessBuilder doesn't differentiate the command from its arguments, but we do in our API to ensure the user
     * doesn't just pass us a single string command, which invokes the shell and can cause all sorts of bugs and
     * security issues. */
    List<String> commandAndArgs = new ArrayList<String>(args.size() + 1) {
        {
            add(command);
            addAll(args);
        }
    };
    ProcessBuilder processBuilder = new ProcessBuilder(commandAndArgs);
    LOGGER.info("Running child process: %s", StringUtils.join(commandAndArgs, " "));

    Process p = processBuilder.start();
    // Log whatever the child writes.
    new StreamLogger(p.getInputStream(), l -> LOGGER.info("[child STDOUT]: %s", l)).run();
    new StreamLogger(p.getErrorStream(), l -> LOGGER.warn("[child STDERR]: %s", l)).run();
    // Wait for the child process to exit, timing out if it takes to long to finish.
    if (timeoutInSeconds != null) {
        p.waitFor(timeoutInSeconds, TimeUnit.SECONDS);
    } else {
        p.waitFor();
    }

    // 0 is the default success exit code in *nix land.
    if (p.exitValue() != 0) {
        LOGGER.error("Child process exited with non-zero status code: %d", p.exitValue());
    }

    return p.exitValue();
}

From source file:Main.java

public static int findProcessIdWithPS(String command) throws Exception {

    int procId = -1;

    Runtime r = Runtime.getRuntime();

    Process procPs = null;

    procPs = r.exec(SHELL_CMD_PS);/*from w ww  . j a v  a  2  s  .co m*/

    BufferedReader reader = new BufferedReader(new InputStreamReader(procPs.getInputStream()));
    String line = null;

    while ((line = reader.readLine()) != null) {
        if (line.indexOf(' ' + command) != -1) {

            StringTokenizer st = new StringTokenizer(line, " ");
            st.nextToken(); // proc owner

            procId = Integer.parseInt(st.nextToken().trim());

            break;
        }
    }

    return procId;

}

From source file:Main.java

public static int findProcessIdWithPS(String command) throws Exception {

    int procId = -1;

    Runtime r = Runtime.getRuntime();

    Process procPs = null;

    procPs = r.exec(SHELL_CMD_PS);//from ww w .j  av  a  2  s  . c  om

    BufferedReader reader = new BufferedReader(new InputStreamReader(procPs.getInputStream()));
    String line = null;

    while ((line = reader.readLine()) != null) {
        if (line.indexOf(' ' + command) != -1) {

            StringTokenizer st = new StringTokenizer(line, " ");
            st.nextToken(); //proc owner

            procId = Integer.parseInt(st.nextToken().trim());

            break;
        }
    }

    return procId;

}