1 package org.openecomp.sdc.asdctool.migration.scanner;
3 import org.apache.commons.io.FileUtils;
4 import org.openecomp.sdc.asdctool.migration.core.MigrationException;
7 import java.lang.reflect.Modifier;
12 * scan and instantiate classes of given type in the class path
14 public class ClassScanner {
17 private ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
19 public <T> List<T> getAllClassesOfType(String basePackage, Class<T> ofType) {
20 Collection<File> allClassesInPackage = getAllClassesInPackage(basePackage);
21 List<T> loadedClasses = new ArrayList<>();
22 for (File clazzFile : allClassesInPackage) {
23 Optional<T> instance = loadAndInstantiateClass(getClassReference(clazzFile), ofType);
24 instance.ifPresent(loadedClasses::add);
29 private <T> Optional<T> loadAndInstantiateClass(String classReference, Class<T> ofType) {
31 return instantiateClassOfType(classReference, ofType);
32 }catch (ClassNotFoundException e) {
34 throw new MigrationException(String.format("could not find class %s of type %s. cause: %s", classReference, ofType.toGenericString(), e.getMessage()));
35 } catch (IllegalAccessException e1) {
37 throw new MigrationException(String.format("could not instantiate class %s of type %s. class is not accessible. cause: %s", classReference, ofType.toGenericString(), e1.getMessage()));
38 } catch (InstantiationException e2) {
40 throw new MigrationException(String.format("could not instantiate class %s of type %s. cause: %s", classReference, ofType.toGenericString(), e2.getMessage()));
44 private <T> Optional<T> instantiateClassOfType(String classReference, Class<T> ofType) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
45 String className = classReference.replaceAll(".class$", "").replaceAll(".class", "");
46 Class<?> aClass = classLoader.loadClass(className);
47 if (ofType.isAssignableFrom(aClass) && isInstantiateAbleClass(aClass)){
48 return Optional.of((T) aClass.newInstance());
50 return Optional.empty();
53 private boolean isInstantiateAbleClass(Class<?> clazz) {
54 return !Modifier.isAbstract(clazz.getModifiers()) && !clazz.isEnum() && !clazz.isAnonymousClass() && !clazz.isInterface();
57 private Collection<File> getAllClassesInPackage(String fromPackage) {
58 String path = fromPackage.replace(".", "/");
59 URL resource = classLoader.getResource(path);
60 if (noMigrationTasks(resource)) {
61 return Collections.emptyList();
63 return FileUtils.listFiles(new File(resource.getFile()), new String[]{"class"}, true);
66 private boolean noMigrationTasks(URL resource) {
67 return resource == null;
70 private String getClassReference(File classFile) {
71 String asPackage = classFile.getPath().replace(File.separator, ".");
72 String classes = "classes.";
73 return asPackage.substring(asPackage.indexOf(classes) + classes.length());