Example usage for java.lang Process getOutputStream

List of usage examples for java.lang Process getOutputStream

Introduction

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

Prototype

public abstract OutputStream getOutputStream();

Source Link

Document

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

Usage

From source file:com.shubhangrathore.xposed.xhover.MainActivity.java

/**
 * Restarts SystemUI. Requires SuperUser privilege.
 *
 * @return boolean true if successful, else false.
 *//* w w  w .j a v  a2 s  . co  m*/
private boolean restartSystemUi() {
    boolean mSuccessful;
    try {
        Process mProcess = Runtime.getRuntime().exec("su");
        DataOutputStream mDataOutputStream = new DataOutputStream(mProcess.getOutputStream());
        mDataOutputStream.writeBytes("pkill com.android.systemui \n");
        mDataOutputStream.writeBytes("exit\n");
        mDataOutputStream.flush();
        // We wait for the command to be completed
        // before moving forward. This ensures that the method
        // returns only after all the commands' execution is complete.
        mProcess.waitFor();

        if (mProcess.exitValue() == 1) {
            // If control is here, that means the sub process has returned
            // an unsuccessful exit code.
            // Most probably, SuperUser permission was denied
            Log.e(TAG, "Utilities: SuperUser permission denied. Unable to restart SystemUI.");
            mSuccessful = false;
        } else {
            // SuperUser permission granted
            Log.i(TAG, "Utilities: SuperUser permission granted. SystemUI restarted.");
            mSuccessful = true;
        }
    } catch (IOException e) {
        Log.e(TAG, "restartSystemUI: I/O exception");
        mSuccessful = false;
    } catch (InterruptedException e) {
        Log.e(TAG, "restartSystemUI: InterruptedException exception");
        mSuccessful = false;
    }
    return mSuccessful;
}

From source file:org.inria.myriads.snoozenode.localcontroller.powermanagement.util.PowerManagementUtils.java

/**
 * Checks if the suspend state is supported.
 * //from ww w  .  ja  v  a 2  s. com
 * @param  suspendState         The suspend state
 * @return                      true if everything ok, false otherwise
 */
public static boolean hasSuspendSupport(SuspendState suspendState) {
    Guard.check(suspendState);
    log_.debug(String.format("Checking if the system supports suspend state: %s", suspendState));

    Process process = null;
    boolean isSupported = false;
    try {
        process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", SUPPORTED_POWER_STATES });
        process.waitFor();

        InputStream inputStream = process.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String content;
        while ((content = bufferedReader.readLine()) != null) {
            log_.debug(String.format("Content: %s", content));
            isSupported = hasState(suspendState, content);
            if (isSupported) {
                break;
            }
        }
    } catch (IOException exception) {
        log_.error(String.format("Failed to execute the command: %s", exception.getMessage()));
    } catch (InterruptedException exception) {
        log_.error(String.format("Interrupted exception: %s", exception.getMessage()));
    } catch (Exception exception) {
        log_.error(String.format("Exception: %s", exception.getMessage()));
    } finally {
        if (process != null) {
            IOUtils.closeQuietly(process.getOutputStream());
            IOUtils.closeQuietly(process.getInputStream());
            IOUtils.closeQuietly(process.getErrorStream());
        }
    }

    return isSupported;
}

From source file:com.koushikdutta.superuser.MainActivity.java

void doSystemInstall() {
    final ProgressDialog dlg = new ProgressDialog(this);
    dlg.setTitle(R.string.installing);/*www  .  j av a  2 s  .  c  o  m*/
    dlg.setMessage(getString(R.string.installing_superuser));
    dlg.setIndeterminate(true);
    dlg.show();
    new Thread() {
        public void run() {
            boolean _error = false;
            try {
                final File su = extractSu();
                final String command = "mount -orw,remount /system\n" + "rm /system/xbin/su\n"
                        + "rm /system/bin/su\n" + "rm /system/app/Supersu.*\n" + "rm /system/app/superuser.*\n"
                        + "rm /system/app/supersu.*\n" + "rm /system/app/SuperUser.*\n"
                        + "rm /system/app/SuperSU.*\n"
                        + String.format("cat %s > /system/xbin/su\n", su.getAbsolutePath())
                        + "chmod 6755 /system/xbin/su\n" + "ln -s /system/xbin/su /system/bin/su\n"
                        + "mount -oro,remount /system\n" + "sync\n";
                Process p = Runtime.getRuntime().exec("su");
                p.getOutputStream().write(command.getBytes());
                p.getOutputStream().close();
                if (p.waitFor() != 0)
                    throw new Exception("non zero result");
                SuHelper.checkSu(MainActivity.this);
            } catch (Exception ex) {
                _error = true;
                Log.e("Superuser", "error upgrading", ex);
            }
            dlg.dismiss();
            final boolean error = _error;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setTitle(R.string.install);

                    if (error) {
                        builder.setMessage(R.string.install_error);
                    } else {
                        builder.setMessage(R.string.install_success);
                    }
                    builder.create().show();
                }
            });
        };
    }.start();
}

From source file:com.nks.nksmod.otaupdater.DownloadsActivity.java

private void flashFiles(String[] files, boolean backup, boolean wipeCache, boolean wipeData) {
    try {/*from   w ww  .  j  a v  a  2 s  .  co m*/
        Process p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        os.writeBytes("echo 'NKS MOD Updater'\n");
        os.writeBytes("mkdir -p /cache/recovery/\n");
        os.writeBytes("rm -rf /cache/recovery/command\n");
        os.writeBytes("rm -rf /cache/recovery/extendedcommand\n");
        os.writeBytes("rm -rf /cache/recovery/update.zip\n");
        os.writeBytes("rm -rf /cache/recovery/nksmod.zip\n");
        os.writeBytes("echo 'boot-recovery' >> /cache/recovery/command\n");

        if (backup) {
            os.writeBytes("echo '--nandroid' >> /cache/recovery/command\n");
        }
        if (wipeData) {
            /* os.writeBytes("echo '--wipe_data' >> /cache/recovery/command\n"); */
        }
        if (wipeCache) {
            /* os.writeBytes("echo '--wipe_cache' >> /cache/recovery/command\n"); */
        }

        for (String file : files) {
            os.writeBytes("cp " + file + " /cache/recovery/nksmod.zip\n");
            os.writeBytes("echo '--update_package=/cache/recovery/nksmod.zip' >> /cache/recovery/command\n");
        }

        String rebootCmd = PropUtils.getRebootCmd();
        if (!rebootCmd.equals("$$NULL$$")) {
            os.writeBytes("sync\n");
            if (rebootCmd.endsWith(".sh")) {
                os.writeBytes("sh " + rebootCmd + "\n");
            } else {
                os.writeBytes(rebootCmd + "\n");
            }
        }

        os.writeBytes("sync\n");
        os.writeBytes("exit\n");
        os.flush();
        p.waitFor();
        ((PowerManager) getSystemService(POWER_SERVICE)).reboot("recovery");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:rega.genotype.ui.util.GenotypeLib.java

private static File getTreeEPS(File jobDir, File treeFile)
        throws IOException, InterruptedException, ApplicationException, FileNotFoundException {
    File epsFile = new File(treeFile.getPath().replace(".tre", ".eps"));
    if (epsFile.exists())
        return epsFile;

    Runtime runtime = Runtime.getRuntime();
    Process proc;
    int result;/*  w  w w . ja v a 2 s  .c  o  m*/
    String cmd;

    cmd = Settings.treeGraphCommand + " -t " + treeFile.getAbsolutePath();
    System.err.println(cmd);
    proc = runtime.exec(cmd, null, jobDir);

    InputStream inputStream = proc.getInputStream();

    LineNumberReader reader = new LineNumberReader(new InputStreamReader(inputStream));

    Pattern taxaCountPattern = Pattern.compile("(\\d+) taxa read.");

    int taxa = 0;
    for (;;) {
        String s = reader.readLine();
        if (s == null)
            break;
        Matcher m = taxaCountPattern.matcher(s);

        if (m.find()) {
            taxa = Integer.valueOf(m.group(1)).intValue();
        }
    }

    if ((result = proc.waitFor()) != 0)
        throw new ApplicationException(cmd + " exited with error: " + result);

    proc.getErrorStream().close();
    proc.getInputStream().close();
    proc.getOutputStream().close();

    File tgfFile = new File(treeFile.getPath().replace(".tre", ".tgf"));
    File resizedTgfFile = new File(treeFile.getPath().replace(".tre", ".resized.tgf"));

    BufferedReader in = new BufferedReader(new FileReader(tgfFile));
    PrintStream out = new PrintStream(new FileOutputStream(resizedTgfFile));
    String line;
    while ((line = in.readLine()) != null) {
        line = line.replace("\\width{", "%\\width{");
        line = line.replace("\\height{", "%\\height{");
        line = line.replace("\\margin{", "%\\margin{");
        line = line.replace("\\style{r}{plain}", "%\\style{r}{plain}");
        line = line.replace("\\style{default}{plain}", "%\\style{default}{plain}");
        line = line.replaceAll("\\\\len\\{-", "\\\\len\\{");
        out.println(line);

        if (line.equals("\\begindef")) {
            out.println("\\paper{a2}");
            out.println("\\width{170}");
            out.println("\\height{" + (taxa * 8.6) + "}");
            out.println("\\margin{10}{10}{10}{10}");
            out.println("\\style{default}{plain}{13}");
            out.println("\\style{r}{plain}{13}");
        }
    }
    out.close();
    in.close();

    tgfFile.delete();
    resizedTgfFile.renameTo(tgfFile);

    cmd = Settings.treeGraphCommand + " -p " + tgfFile.getAbsolutePath();
    System.err.println(cmd);
    proc = runtime.exec(cmd, null, jobDir);
    if ((result = proc.waitFor()) != 0)
        throw new ApplicationException(cmd + " exited with error: " + result);

    proc.getErrorStream().close();
    proc.getInputStream().close();
    proc.getOutputStream().close();

    return epsFile;
}

From source file:org.apache.kudu.client.MiniKdc.java

/**
 * Kinit a user with the mini KDC./*from  w w w .j ava 2  s .  c o  m*/
 * @param username the user to kinit
 */
void kinit(String username) throws IOException {
    Process proc = startProcessWithKrbEnv(getBinaryPath("kinit"), username);
    proc.getOutputStream().write(username.getBytes());
    proc.getOutputStream().close();
    checkReturnCode(proc, "kinit", true);
}

From source file:com.Candy.center.AboutCandy.java

private void getLogs(String command) {
    try {// ww w. java 2  s .c  om
        Process process = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(command);
        os.writeBytes("exit\n");
        os.flush();
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.koushikdutta.superuser.MainActivity.java

void doRecoveryInstall() {
    final ProgressDialog dlg = new ProgressDialog(this);
    dlg.setTitle(R.string.installing);/*from ww  w.  j  a v  a  2  s. c  o m*/
    dlg.setMessage(getString(R.string.installing_superuser));
    dlg.setIndeterminate(true);
    dlg.show();
    new Thread() {
        void doEntry(ZipOutputStream zout, String entryName, String dest) throws IOException {
            ZipFile zf = new ZipFile(getPackageCodePath());
            ZipEntry ze = zf.getEntry(entryName);
            zout.putNextEntry(new ZipEntry(dest));
            InputStream in;
            StreamUtility.copyStream(in = zf.getInputStream(ze), zout);
            zout.closeEntry();
            in.close();
            zf.close();
        }

        public void run() {
            try {
                File zip = getFileStreamPath("superuser.zip");
                ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zip));
                doEntry(zout, "assets/update-binary", "META-INF/com/google/android/update-binary");
                doEntry(zout, "assets/install-recovery.sh", "install-recovery.sh");
                zout.close();

                ZipFile zf = new ZipFile(getPackageCodePath());
                ZipEntry ze = zf.getEntry("assets/" + getArch() + "/reboot");
                InputStream in;
                FileOutputStream reboot;
                StreamUtility.copyStream(in = zf.getInputStream(ze),
                        reboot = openFileOutput("reboot", MODE_PRIVATE));
                reboot.close();
                in.close();

                final File su = extractSu();

                String command = String.format("cat %s > /cache/superuser.zip\n", zip.getAbsolutePath())
                        + String.format("cat %s > /cache/su\n", su.getAbsolutePath())
                        + String.format("cat %s > /cache/Superuser.apk\n", getPackageCodePath())
                        + "mkdir /cache/recovery\n"
                        + "echo '--update_package=CACHE:superuser.zip' > /cache/recovery/command\n"
                        + "chmod 644 /cache/superuser.zip\n" + "chmod 644 /cache/recovery/command\n" + "sync\n"
                        + String.format("chmod 755 %s\n", getFileStreamPath("reboot").getAbsolutePath())
                        + "reboot recovery\n";
                Process p = Runtime.getRuntime().exec("su");
                p.getOutputStream().write(command.getBytes());
                p.getOutputStream().close();
                File rebootScript = getFileStreamPath("reboot.sh");
                StreamUtility.writeFile(rebootScript,
                        "reboot recovery ; " + getFileStreamPath("reboot").getAbsolutePath() + " recovery ;");
                p.waitFor();
                Runtime.getRuntime().exec(new String[] { "su", "-c", ". " + rebootScript.getAbsolutePath() });
                if (p.waitFor() != 0)
                    throw new Exception("non zero result");
            } catch (Exception ex) {
                ex.printStackTrace();
                dlg.dismiss();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setPositiveButton(android.R.string.ok, null);
                        builder.setTitle(R.string.install);
                        builder.setMessage(R.string.install_error);
                        builder.create().show();
                    }
                });
            }
        }
    }.start();
}

From source file:controllers.base.SecuredAction.java

public boolean hasVirus(File file) {
    if (file == null) {
        return false;
    }//ww w  . jav  a 2 s .c o  m

    try {
        Process process = Runtime.getRuntime()
                .exec(Play.application().configuration().getString("application.virusChecker.command"));
        byte[] buffer = new byte[2048];
        InputStream stream = FileUtils.openInputStream(file);
        while (IOUtils.read(stream, buffer, 0, 2048) != 0) {
            process.getOutputStream().write(buffer);
        }
        process.getOutputStream().close();
        try {
            int result = process.waitFor();
            if (result == 0) {
                return false;
            } else if (result == 1) {
                return true;
            } else {
                throw new InternalError();
            }
        } catch (InterruptedException e) {
            return hasVirus(file);
        }
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.ops4j.pax.url.mvnlive.internal.Connection.java

/**
 * Create helper thread to safely shutdown the external framework process
 *
 * @param process framework process// w  w w .j  a  v  a2  s  .c om
 * @return stream handler
 */
private Thread createShutdownHook(final Process process) {
    final Pipe errPipe = new Pipe(process.getErrorStream(), System.err).start("Error pipe");
    final Pipe outPipe = new Pipe(process.getInputStream(), System.out).start("Out pipe");
    final Pipe inPipe = new Pipe(process.getOutputStream(), System.in).start("In pipe");

    Thread shutdownHook = new Thread(new Runnable() {
        public void run() {
            inPipe.stop();
            outPipe.stop();
            errPipe.stop();

            try {
                process.destroy();
            } catch (Exception e) {
                // ignore if already shutting down
            }
        }
    }, "mvnlive url handler shutdown hook");

    return shutdownHook;
}