1/* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 17package libcore.dalvik.system; 18 19import libcore.io.Streams; 20 21import java.io.File; 22import java.io.FileOutputStream; 23import java.io.IOException; 24import java.io.InputStream; 25import java.util.HashMap; 26import java.util.List; 27import java.util.Map; 28 29import static org.junit.Assert.*; 30 31class ClassLoaderTestSupport { 32 private static final String PACKAGE_PATH = "dalvik/system/"; 33 34 static Map<String, File> setupAndCopyResources(List<String> resources) throws Exception { 35 File srcDir = File.createTempFile("src", ""); 36 assertTrue(srcDir.delete()); 37 assertTrue(srcDir.mkdirs()); 38 39 HashMap<String, File> resourcesMap = new HashMap<>(); 40 resourcesMap.put(null, srcDir); 41 42 for (String resource: resources) { 43 File resourceFile = new File(srcDir, resource); 44 copyResource(resource, resourceFile); 45 46 resourcesMap.put(resource, resourceFile); 47 } 48 49 return resourcesMap; 50 } 51 52 static void cleanUpResources(Map<String, File> resources) { 53 cleanUpDir(resources.get(null)); 54 } 55 56 private static void cleanUpDir(File dir) { 57 if (dir == null || !dir.isDirectory()) { 58 return; 59 } 60 61 File[] files = dir.listFiles(); 62 for (File file : files) { 63 if (file.isDirectory()) { 64 cleanUpDir(file); 65 } else { 66 assertTrue(file.delete()); 67 } 68 } 69 assertTrue(dir.delete()); 70 } 71 72 /** 73 * Copy a resource in the package directory to the indicated 74 * target file. 75 */ 76 private static void copyResource(String resourceName, 77 File destination) throws IOException { 78 ClassLoader loader = DexClassLoaderTest.class.getClassLoader(); 79 assertFalse(destination.exists()); 80 InputStream in = loader.getResourceAsStream(PACKAGE_PATH + resourceName); 81 if (in == null) { 82 throw new IllegalStateException("Resource not found: " + PACKAGE_PATH + resourceName); 83 } 84 85 try (FileOutputStream out = new FileOutputStream(destination)) { 86 Streams.copy(in, out); 87 } finally { 88 in.close(); 89 } 90 } 91 92} 93