1 package org.robolectric.util; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.File; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.OutputStream; 8 import java.net.MalformedURLException; 9 import java.net.URL; 10 import java.util.ArrayList; 11 import java.util.List; 12 13 /** 14 * Generic collection of utility methods. 15 */ 16 public class Util { 17 public static void copy(InputStream in, OutputStream out) throws IOException { 18 byte[] buffer = new byte[8196]; 19 int len; 20 try { 21 while ((len = in.read(buffer)) != -1) { 22 out.write(buffer, 0, len); 23 } 24 } finally { 25 in.close(); 26 } 27 } 28 29 /** 30 * This method consumes an input stream and returns its content. 31 * 32 * @param is The input stream to read from. 33 * @return The bytes read from the stream. 34 * @throws IOException Error reading from stream. 35 */ 36 public static byte[] readBytes(InputStream is) throws IOException { 37 try (ByteArrayOutputStream bos = new ByteArrayOutputStream(is.available())) { 38 copy(is, bos); 39 return bos.toByteArray(); 40 } 41 } 42 43 public static <T> T[] reverse(T[] array) { 44 for (int i = 0; i < array.length / 2; i++) { 45 int destI = array.length - i - 1; 46 T o = array[destI]; 47 array[destI] = array[i]; 48 array[i] = o; 49 } 50 return array; 51 } 52 53 public static File file(String... pathParts) { 54 return file(new File("."), pathParts); 55 } 56 57 public static File file(File f, String... pathParts) { 58 for (String pathPart : pathParts) { 59 f = new File(f, pathPart); 60 } 61 62 String dotSlash = "." + File.separator; 63 if (f.getPath().startsWith(dotSlash)) { 64 f = new File(f.getPath().substring(dotSlash.length())); 65 } 66 67 return f; 68 } 69 70 public static URL url(String path) throws MalformedURLException { 71 //Starts with double backslash, is likely a UNC path 72 if(path.startsWith("\\\\")) { 73 path = path.replace("\\", "/"); 74 } 75 return new URL("file:/" + (path.startsWith("/") ? "/" + path : path)); 76 } 77 78 public static List<Integer> intArrayToList(int[] ints) { 79 List<Integer> youSuckJava = new ArrayList<>(); 80 for (int attr1 : ints) { 81 youSuckJava.add(attr1); 82 } 83 return youSuckJava; 84 } 85 86 public static int parseInt(String valueFor) { 87 if (valueFor.startsWith("0x")) { 88 return Integer.parseInt(valueFor.substring(2), 16); 89 } else { 90 return Integer.parseInt(valueFor, 10); 91 } 92 } 93 } 94