Example usage for java.lang Runtime getRuntime

List of usage examples for java.lang Runtime getRuntime

Introduction

In this page you can find the example usage for java.lang Runtime getRuntime.

Prototype

public static Runtime getRuntime() 

Source Link

Document

Returns the runtime object associated with the current Java application.

Usage

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.  co 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:de.unisb.cs.st.javaslicer.slicing.Slicer.java

public static void main(String[] args) throws InterruptedException {
    Options options = createOptions();//from  w  w w .  j av  a 2  s  .c om
    CommandLineParser parser = new GnuParser();
    CommandLine cmdLine;

    try {
        cmdLine = parser.parse(options, args, true);
    } catch (ParseException e) {
        System.err.println("Error parsing the command line arguments: " + e.getMessage());
        return;
    }

    if (cmdLine.hasOption('h')) {
        printHelp(options, System.out);
        System.exit(0);
    }

    String[] additionalArgs = cmdLine.getArgs();
    if (additionalArgs.length != 2) {
        printHelp(options, System.err);
        System.exit(-1);
    }
    // ?? 1. ? 2.?
    File traceFile = new File(additionalArgs[0]);
    String slicingCriterionString = additionalArgs[1];

    Long threadId = null;
    if (cmdLine.hasOption('t')) { // the interesting thread id for slicing 
        try {
            threadId = Long.parseLong(cmdLine.getOptionValue('t'));
        } catch (NumberFormatException e) {
            System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t'));
            System.exit(-1);
        }
    }

    TraceResult trace;
    try {
        trace = TraceResult.readFrom(traceFile);
    } catch (IOException e) {
        System.err.format("Could not read the trace file \"%s\": %s%n", traceFile, e);
        System.exit(-1);
        return;
    }

    List<SlicingCriterion> sc = null; // a list contains the instruction's info corresponds to the slicing criterion
    //slicingCriterionString get from additionalArgs[1]
    try {
        sc = StaticSlicingCriterion.parseAll(slicingCriterionString, trace.getReadClasses());
    } catch (IllegalArgumentException e) {
        System.err.println("Error parsing slicing criterion: " + e.getMessage());
        System.exit(-1);
        return;
    }

    List<ThreadId> threads = trace.getThreads(); // the threads that generate the traces
    if (threads.size() == 0) {
        System.err.println("The trace file contains no tracing information.");
        System.exit(-1);
    }

    // threadID is used to mark the interesting thread
    ThreadId tracing = null;
    for (ThreadId t : threads) {
        if (threadId == null) {
            if ("main".equals(t.getThreadName())
                    && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId()))
                tracing = t;
        } else if (t.getJavaThreadId() == threadId.longValue()) {
            tracing = t;
        }
    }

    if (tracing == null) {
        System.err.println(threadId == null ? "Couldn't find the main thread."
                : "The thread you specified was not found.");
        System.exit(-1);
        return;
    }

    long startTime = System.nanoTime();
    Slicer slicer = new Slicer(trace);
    if (cmdLine.hasOption("progress")) // the parameter process indicates that we need to monitor the process of slicing
        slicer.addProgressMonitor(new ConsoleProgressMonitor());
    boolean multithreaded;
    if (cmdLine.hasOption("multithreaded")) {
        String multithreadedStr = cmdLine.getOptionValue("multithreaded");
        multithreaded = ("1".equals(multithreadedStr) || "true".equals(multithreadedStr));
    } else {
        multithreaded = Runtime.getRuntime().availableProcessors() > 1;
    }

    boolean warnUntracedMethods = cmdLine.hasOption("warn-untraced"); // give some warns when encounters untraced functions

    //sliceInstructionCollector implements the interface slice visitor, which travel the dependence graph
    SliceInstructionsCollector collector = new SliceInstructionsCollector(); // the collector is used to collect the instructions in the dependence graph according to the slice criterion. 
    slicer.addSliceVisitor(collector);
    // zhushi by yhb

    if (warnUntracedMethods)
        slicer.addUntracedCallVisitor(new PrintUniqueUntracedMethods()); // the user need the untraced function info, so add untraced call visitor

    slicer.process(tracing, sc, multithreaded); //----------------------the key process of slicing!!!
    Set<InstructionInstance> slice = collector.getDynamicSlice(); // return the slice result from the collector
    long endTime = System.nanoTime();

    Instruction[] sliceArray = slice.toArray(new Instruction[slice.size()]); // convert the set to array
    Arrays.sort(sliceArray); // in order to ensure the sequence of dynamic execution

    // show the slicing result
    System.out.println("The dynamic slice for criterion " + sc + ":");
    for (Instruction insn : sliceArray) {
        System.out.format((Locale) null, "%s.%s:%d %s%n", insn.getMethod().getReadClass().getName(),
                insn.getMethod().getName(), insn.getLineNumber(), insn.toString());
    }
    System.out.format((Locale) null, "%nSlice consists of %d bytecode instructions.%n", sliceArray.length);
    System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime));
}

From source file:Main.java

/**
 * get recommend default thread pool size
 * /*ww w .  java2  s.c  o  m*/
 * @param max
 * @return if 2 * availableProcessors + 1 less than max, return it, else return max;
 */
public static int getDefaultThreadPoolSize(int max) {
    int availableProcessors = 2 * Runtime.getRuntime().availableProcessors() + 1;
    return availableProcessors > max ? max : availableProcessors;
}

From source file:Main.java

public static String getBuildString() {

    String strValue = null;/* w w  w .ja v  a 2  s  .  c om*/
    BufferedReader birReader = null;

    try {

        Process p = Runtime.getRuntime().exec("getprop ro.modversion");
        birReader = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
        strValue = birReader.readLine();
        birReader.close();

    } catch (IOException e) {
        Log.e("HelperFunctions", "Unable to read property", e);
    } finally {

        if (birReader != null) {

            try {

                birReader.close();

            } catch (IOException e) {
                Log.e("HelperFunctions", "Exception while closing the file", e);
            }

        }

    }

    return strValue;

}

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;/*from  w  w  w.  j a va  2 s.  co m*/
    DataOutputStream os = null;
    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:Main.java

public static String getBusyBoxVer() {
    String text = "";
    Process process = null;//w w w . j  a  v a2  s .com
    try {
        //Execute command.
        process = Runtime.getRuntime().exec("busybox");

        //Read file (one line is enough).
        text = readFile(process.getInputStream(), 1);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    if (!TextUtils.isEmpty(text)) {
        //Like this:
        //BusyBox v1.22.1 bionic (2015-05-25 18:22 +0800) multi-call binary.
        String[] infos = text.split(" ");
        if (infos[0].equalsIgnoreCase("busybox")) {
            if (infos[1].startsWith("v") || infos[1].startsWith("V")) {
                return infos[1].substring(1);
            }
        }
    }

    return "";
}

From source file:Main.java

public static String RunExecCmd(StringBuilder sb, Boolean su) {

    String shell;/*from  ww w .  j a  v a 2s  .  c om*/
    if (su) {
        shell = "su";
    } else {
        shell = "sh";
    }

    Process process = null;

    DataOutputStream processOutput = null;
    InputStream processInput = null;
    String outmsg = new String();

    try {

        process = Runtime.getRuntime().exec(shell);
        processOutput = new DataOutputStream(process.getOutputStream());
        processOutput.writeBytes(sb.toString() + "\n");
        processOutput.writeBytes("exit\n");
        processOutput.flush();
        processInput = process.getInputStream();
        outmsg = inputStream2String(processInput, "UTF-8");
        process.waitFor();

    } catch (Exception e) {
        //Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
        //return;
    }

    finally {
        try {
            if (processOutput != null) {
                processOutput.close();
            }
            process.destroy();
        } catch (Exception e) {
        }

    }
    return outmsg;
}

From source file:Main.java

public static String getSystemProperty() {
    String line = null;/*from w  w w .  j  a va  2s  .  c  om*/
    BufferedReader reader = null;
    try {
        Process p = Runtime.getRuntime().exec("getprop ro.miui.ui.version.name");
        reader = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
        line = reader.readLine();
        return line;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return "UNKNOWN";
}

From source file:Main.java

public static long getMaxMemory() {

    return Runtime.getRuntime().maxMemory() / 1024;
}

From source file:Main.java

public static BufferedReader shellExecute(String[] commands, boolean requireRoot) {
    Process shell = null;// www. ja  v a2 s  . c  o m
    DataOutputStream out = null;
    BufferedReader reader = null;
    String startCommand = requireRoot ? "su" : "sh";
    try {
        shell = Runtime.getRuntime().exec(startCommand);
        out = new DataOutputStream(shell.getOutputStream());
        reader = new BufferedReader(new InputStreamReader(shell.getInputStream()));
        for (String command : commands) {
            out.writeBytes(command + "\n");
            out.flush();
        }
        out.writeBytes("exit\n");
        out.flush();
        shell.waitFor();
    } catch (Exception e) {
        Log.e(TAG, "ShellRoot#shExecute() finished with error", e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {

        }
    }
    return reader;
}