1 /* 2 * Copyright (C) 2016 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 17 package com.android.cts.apicoverage; 18 19 import java.io.File; 20 import java.io.FileNotFoundException; 21 import java.io.IOException; 22 import java.lang.reflect.Modifier; 23 import java.net.URL; 24 import java.net.URLClassLoader; 25 import java.util.ArrayList; 26 import java.util.Collection; 27 import java.util.Enumeration; 28 import java.util.HashSet; 29 import java.util.List; 30 import java.util.Set; 31 import java.util.jar.JarEntry; 32 import java.util.jar.JarFile; 33 34 /** Representation of the entire CDD. */ 35 class JarTestFinder { 36 getClasses(File jarTestFile)37 public static Collection<Class<?>> getClasses(File jarTestFile) 38 throws IllegalArgumentException { 39 List<Class<?>> classes = new ArrayList<>(); 40 41 try (JarFile jarFile = new JarFile(jarTestFile)) { 42 Enumeration<JarEntry> e = jarFile.entries(); 43 44 URL[] urls = { 45 new URL(String.format("jar:file:%s!/", jarTestFile.getAbsolutePath())) 46 }; 47 URLClassLoader cl = URLClassLoader.newInstance(urls, JarTestFinder.class.getClassLoader()); 48 49 while (e.hasMoreElements()) { 50 JarEntry je = e.nextElement(); 51 if (je.isDirectory() || !je.getName().endsWith(".class") 52 || je.getName().contains("$")) { 53 continue; 54 } 55 String className = getClassName(je.getName()); 56 if (!className.endsWith("Test")) { 57 continue; 58 } 59 try { 60 Class<?> cls = cl.loadClass(className); 61 int modifiers = cls.getModifiers(); 62 if (!Modifier.isStatic(modifiers) 63 && !Modifier.isPrivate(modifiers) 64 && !Modifier.isProtected(modifiers) 65 && !Modifier.isInterface(modifiers) 66 && !Modifier.isAbstract(modifiers)) { 67 68 classes.add(cls); 69 } 70 } catch (ClassNotFoundException | Error x) { 71 System.err.println( 72 String.format("Cannot find test class %s from %s", 73 className, jarTestFile.getName())); 74 x.printStackTrace(); 75 } 76 } 77 } catch (IOException e) { 78 e.printStackTrace(); 79 } 80 return classes; 81 } 82 getClassName(String name)83 private static String getClassName(String name) { 84 // -6 because of .class 85 return name.substring(0, name.length() - 6).replace('/', '.'); 86 } 87 } 88