Tsu Chiang Chuang | 9a223d7 | 2011-04-27 17:19:46 -0700 | [diff] [blame^] | 1 | |
| 2 | package dot.junit; |
| 3 | |
| 4 | |
| 5 | import com.android.ddmlib.IDevice; |
| 6 | |
| 7 | import java.io.File; |
| 8 | import java.io.FileOutputStream; |
| 9 | import java.io.IOException; |
| 10 | import java.io.InputStream; |
| 11 | import java.io.UnsupportedEncodingException; |
| 12 | import java.util.Scanner; |
| 13 | |
| 14 | public class DeviceUtil { |
| 15 | |
| 16 | private static boolean DEBUG = System.getProperty("cts.vm-tests.debug") != null; |
| 17 | |
| 18 | /** |
| 19 | * Executes the command and its arguments in a native process. |
| 20 | * |
| 21 | * @param commandAndArgs a string array to be passed containing the |
| 22 | * executable and its arguments |
| 23 | * @param okIndicator if not null, this String must occur in the stdout of |
| 24 | * the executable (since only checking for the return code is not |
| 25 | * sufficient e.g. for adb shell cmd) |
| 26 | * @throws Exception thrown by the underlying command in case of an error. |
| 27 | */ |
| 28 | public static void digestCommand(String[] commandAndArgs, String okIndicator) { |
| 29 | RuntimeException re = null; |
| 30 | try { |
| 31 | if (DEBUG) { |
| 32 | String c = ""; |
| 33 | for (int i = 0; i < commandAndArgs.length; i++) { |
| 34 | c += commandAndArgs[i] + " "; |
| 35 | } |
| 36 | System.out.print("com: " + c); |
| 37 | } |
| 38 | StringBuilder sb = new StringBuilder(); |
| 39 | ProcessBuilder pb = new ProcessBuilder(commandAndArgs).redirectErrorStream(true); |
| 40 | Process p = pb.start(); |
| 41 | |
| 42 | InputStream is = p.getInputStream(); |
| 43 | Scanner scanner = new Scanner(is); |
| 44 | int retCode = p.waitFor(); |
| 45 | while (scanner.hasNextLine()) { |
| 46 | sb.append(scanner.nextLine()); |
| 47 | } |
| 48 | scanner.close(); |
| 49 | if (retCode != 0 || (okIndicator != null && !sb.toString().contains(okIndicator))) { |
| 50 | String msg = sb.toString() + "\nreturn code: " + retCode; |
| 51 | re = new RuntimeException(msg); |
| 52 | if (DEBUG) System.out.println("-> error! msg:"+msg); |
| 53 | } else { |
| 54 | if (DEBUG) System.out.println(" -> " + retCode); |
| 55 | } |
| 56 | } catch (Exception e) { |
| 57 | throw new RuntimeException("Exception occurred: " + e.getClass().getName() + ", msg:" |
| 58 | + e.getMessage()); |
| 59 | } finally { |
| 60 | if (re != null) { |
| 61 | throw re; |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | public static void adbExec(IDevice device, String tmpdir, String classpath, String mainclass) { |
| 67 | DeviceUtil.digestCommand(new String[] {"adb", "-s", device.getSerialNumber(), "shell", |
| 68 | "ANDROID_DATA=" + tmpdir, "dalvikvm", "-Xint:portable", "-Xmx512M", "-Xss32K", |
| 69 | "-Djava.io.tmpdir=" + tmpdir, "-classpath", classpath, mainclass, "&&", |
| 70 | "echo", "mk_dalvikvmok" }, "mk_dalvikvmok"); |
| 71 | } |
| 72 | } |