uk.sponte.automation.seleniumpom.helpers.ImplementationFinder Maven / Gradle / Ivy
package uk.sponte.automation.seleniumpom.helpers;
import org.reflections.Reflections;
import uk.sponte.automation.seleniumpom.annotations.PageFilter;
import uk.sponte.automation.seleniumpom.annotations.Validator;
import uk.sponte.automation.seleniumpom.dependencies.DependencyInjector;
import java.util.*;
/**
* Helper class used to find best matching implementation (child class) based on
* PageFilter and Validator(s)
*/
public class ImplementationFinder {
private Class pageClass;
private DependencyInjector dependencyInjector;
private static HashMap reflectionsCache = new HashMap();
public ImplementationFinder(Class pageClass, DependencyInjector dependencyInjector) {
this.pageClass = pageClass;
this.dependencyInjector = dependencyInjector;
}
public T find() {
Set> subTypesOf = getReflections(pageClass).getSubTypesOf(pageClass);
ArrayList> sortedListOfImplementationClasses = new ArrayList>(subTypesOf);
Collections.sort(sortedListOfImplementationClasses, new PageFilterAnnotatedClassComparator());
for (Class extends T> klass : sortedListOfImplementationClasses) {
PageFilter annotation = klass.getAnnotation(PageFilter.class);
if (annotation != null) {
boolean valid = true;
for (Class extends Validator> validatorClass : annotation.value()) {
Validator validator = dependencyInjector.get(validatorClass);
if (!validator.isValid()) {
valid = false;
break;
}
}
if (valid) {
return dependencyInjector.get(klass);
}
}
}
return dependencyInjector.get(pageClass);
}
private Reflections getReflections(Class pageClass) {
String packageName = pageClass.getPackage().getName();
if(reflectionsCache.containsKey(packageName)) {
return reflectionsCache.get(packageName);
}
Reflections reflections = new Reflections(pageClass.getPackage().getName());
reflectionsCache.put(packageName, reflections);
return reflections;
}
private class PageFilterAnnotatedClassComparator implements Comparator> {
@Override
public int compare(Class extends T> o1, Class extends T> o2) {
int o1ValidatorsCount = 0;
int o2ValidatorsCount = 0;
PageFilter pageFilterO1 = o1.getAnnotation(PageFilter.class);
PageFilter pageFilterO2 = o2.getAnnotation(PageFilter.class);
if (pageFilterO1 != null)
o1ValidatorsCount = pageFilterO1.value().length;
if (pageFilterO2 != null)
o2ValidatorsCount = pageFilterO2.value().length;
return Integer.valueOf(o2ValidatorsCount).compareTo(Integer.valueOf(o1ValidatorsCount));
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy