Java Examples for org.reflections.Reflections
The following java examples will help you to understand the usage of org.reflections.Reflections. These source code samples are taken from different open source projects.
Example 1
| Project: reflections-master File: UrlTypeVFS.java View source code |
public Dir createDir(final URL url) {
try {
URL adaptedUrl = adaptURL(url);
return new ZipDir(new JarFile(adaptedUrl.getFile()));
} catch (Exception e) {
try {
return new ZipDir(new JarFile(url.getFile()));
} catch (IOException e1) {
if (Reflections.log != null) {
Reflections.log.warn("Could not get URL", e);
Reflections.log.warn("Could not get URL", e1);
}
}
}
return null;
}Example 2
| Project: bonaparte-java-master File: BClassScanner.java View source code |
/** Scan a list of available reflections. */
public static void scanAndRegisterBonaPortables(Reflections... reflections) {
for (int i = 0; i < reflections.length; ++i) {
int ctr = 0;
for (Class<? extends BonaPortable> cls : reflections[i].getSubTypesOf(BonaPortable.class)) {
try {
BonaPortableClass<?> bclass = (BonaPortableClass<?>) cls.getMethod("class$BonaPortableClass").invoke(null);
if (BonaPortableFactoryById.registerClass(bclass))
++ctr;
} catch (Exception e) {
LOGGER.warn("Cannot obtain BonaPortableClass for {}: {}", cls.getCanonicalName(), e.getMessage());
}
}
LOGGER.info("Startup: Loaded {} BonaPortable classes", ctr);
}
}Example 3
| Project: gecco-master File: GeccoJmx.java View source code |
public static void export(String classpath) {
Reflections reflections = new Reflections("com.geccocrawler.gecco.monitor");
Set<Class<?>> mbeanClasses = reflections.getTypesAnnotatedWith(MBean.class);
for (Class<?> mbeanClass : mbeanClasses) {
MBean mbean = (MBean) mbeanClass.getAnnotation(MBean.class);
String name = mbean.value();
try {
exporter.export(classpath + ":name=" + name, mbeanClass.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
}Example 4
| Project: highway-to-urhell-master File: JaxRsService.java View source code |
@Override
protected void gatherData(List<EntryPathData> incoming) {
if (!getFrameworkInformations().getVersion().equals(VersionUtils.NO_FRAMEWORK)) {
// scan
System.out.println("Start Scan reflections JAX-RS ! ");
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader()));
System.out.println("End Scan reflections JAX-RS ! ");
Set<Class<?>> setPathJAXRS = reflections.getTypesAnnotatedWith(Path.class);
if (setPathJAXRS != null && !setPathJAXRS.isEmpty()) {
// Grab all class extends
for (Class<?> service : setPathJAXRS) {
// search annotation type javax.ws.rs.Path
for (Annotation annotation : service.getAnnotations()) {
if (annotation instanceof Path) {
Path remoteAnnotation = (Path) annotation;
searchAllMethodPublic(remoteAnnotation, service);
}
}
}
}
}
}Example 5
| Project: robe-master File: RobeHibernateBundle.java View source code |
protected static final ImmutableList<Class<?>> loadEntities(String[] packages, String[] entities) {
Set<Class<?>> classes = new HashSet<>();
if (packages != null) {
for (String packageName : packages) {
LOGGER.info("Loading Package: " + packageName);
Reflections reflections = new Reflections(packageName);
classes.addAll(reflections.getTypesAnnotatedWith(Entity.class));
}
}
if (entities != null) {
for (String entity : entities) {
try {
LOGGER.info("Loading Entity: " + entity);
Class entityClass = Class.forName(entity);
if (entityClass.isAnnotationPresent(Entity.class)) {
classes.add(entityClass);
} else {
LOGGER.warn("Class is not annotated with Entity: " + entity);
}
} catch (ClassNotFoundException e) {
LOGGER.warn("Can't load class: " + entity, e);
}
}
}
return ImmutableList.<Class<?>>builder().add(BaseEntity.class).addAll(classes).build();
}Example 6
| Project: silentium-master File: PropertiesParser.java View source code |
public static void parse() {
final Reflections reflections = new Reflections("silentium." + ServerType.getServerTypeName() + ".configs");
final Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(PropertiesFile.class);
for (final Class<?> clazz : annotated) {
final String propertiesPatch = clazz.getAnnotation(PropertiesFile.class).propertiesPatch();
ConfigurableProcessor.process(clazz, PropertiesUtils.load(propertiesPatch));
log.info("Loading: {}", propertiesPatch);
}
}Example 7
| Project: SkypeBot-master File: API.java View source code |
@Override
public Restlet createInboundRoot() {
Router baseRouter = new Router(getContext());
Reflections r = new Reflections("io.mazenmc.skypebot.api");
for (Class<? extends BaseResource> c : r.getSubTypesOf(BaseResource.class)) {
try {
Method m = c.getMethod("processRequest", String.class, JSONObject.class, String.class);
Path p = m.getAnnotation(Path.class);
if (p != null) {
baseRouter.attach(p.value(), c);
}
} catch (NoSuchMethodException ignored) {
}
}
return baseRouter;
}Example 8
| Project: vnluser-master File: TestHttpProcessors.java View source code |
public static Set<Class<?>> getClasses() {
final HashSet<Class<?>> classes = new HashSet<Class<?>>();
// register root resource
Reflections reflections = new Reflections(BASE_CONTROLLER_PACKAGE);
Set<Class<?>> clazzes = reflections.getTypesAnnotatedWith(HttpProcessorConfig.class);
for (Class<?> clazz : clazzes) {
if (!classes.contains(clazz)) {
classes.add(clazz);
System.out.println("...registered controller class: " + clazz);
if (clazz.isAnnotationPresent(HttpProcessorConfig.class)) {
Annotation annotation = clazz.getAnnotation(HttpProcessorConfig.class);
HttpProcessorConfig mapper = (HttpProcessorConfig) annotation;
System.out.println(mapper.uriPath());
System.out.println(mapper.contentType());
}
}
}
// classes.add(HttpNodeResourceHandler.class);
return classes;
}Example 9
| Project: katharsis-core-master File: DefaultExceptionMapperLookup.java View source code |
@Override
public Set<JsonApiExceptionMapper> getExceptionMappers() {
Reflections reflections;
if (resourceSearchPackage != null) {
String[] packageNames = resourceSearchPackage.split(",");
reflections = new Reflections(packageNames);
} else {
reflections = new Reflections(resourceSearchPackage);
}
Set<Class<?>> exceptionMapperClasses = reflections.getTypesAnnotatedWith(ExceptionMapperProvider.class);
Set<JsonApiExceptionMapper> exceptionMappers = new HashSet<>();
for (Class<?> exceptionMapperClazz : exceptionMapperClasses) {
if (!JsonApiExceptionMapper.class.isAssignableFrom(exceptionMapperClazz)) {
throw new InvalidResourceException(exceptionMapperClazz.getCanonicalName() + " is not an implementation of JsonApiExceptionMapper");
}
try {
exceptionMappers.add((JsonApiExceptionMapper<? extends Throwable>) exceptionMapperClazz.newInstance());
} catch (Exception e) {
throw new InvalidResourceException(exceptionMapperClazz.getCanonicalName() + " can not be initialized", e);
}
}
return exceptionMappers;
}Example 10
| Project: Orienteer-master File: MethodStorage.java View source code |
public void reload() {
Reflections reflections = new Reflections(CORE_PATH, new TypeElementsScanner(), new MethodAnnotationsScanner(), new SubTypesScanner());
for (String path : paths) {
reflections.merge(new Reflections(path, new TypeElementsScanner(), new MethodAnnotationsScanner(), new SubTypesScanner()));
}
try {
methodFields = reflections.getMethodsAnnotatedWith(ClassOMethod.class);
methodClasses = reflections.getSubTypesOf(IMethod.class);
} catch (Exception e) {
e.printStackTrace();
}
}Example 11
| Project: ovirt-engine-master File: CommandEnumTestUtils.java View source code |
public static <E extends Enum<E>, C> void testCommandClassHasEnum(Class<E> enumClass, Class<C> commandClass, String suffix) {
final Reflections reflections = new Reflections(CommandsFactory.getCommandPackages());
Set<Class<? extends C>> commands = reflections.getSubTypesOf(commandClass);
Set<String> commandsWithoutEnum = commands.stream().filter( c -> !Modifier.isAbstract(c.getModifiers())).filter( c -> c.getEnclosingClass() == null).filter( c -> {
try {
Enum.valueOf(enumClass, c.getSimpleName().replaceAll(suffix + "$", ""));
return false;
} catch (IllegalArgumentException ignore) {
return true;
}
}).map(Class::getName).collect(Collectors.toSet());
assertTrue("Found the following commands without a corresponding " + enumClass.getSimpleName() + " constant : " + commandsWithoutEnum, commandsWithoutEnum.isEmpty());
}Example 12
| Project: alfred-worker-master File: PluginManager.java View source code |
public void addPluginSource(File file) throws InvalidPluginException {
try {
URL url = file.toURI().toURL();
URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url });
Reflections reflections = new Reflections(ConfigurationBuilder.build(urlClassLoader, url));
workflowPluginClasses.addAll(reflections.getSubTypesOf(AlfredWorkflowPlugin.class));
workflowPluginClasses.addAll(reflections.getSubTypesOf(AbstractWorkflowPlugin.class));
} catch (MalformedURLException e) {
throw new InvalidPluginException(String.format("Invalid plugin: %s.", file.getPath()), e);
}
}Example 13
| Project: artemis-odb-master File: ReflectionsComponentCollectStrategy.java View source code |
/**
* Collect all components on a classpath.
*
* @param classLoader context.
* @return Set of all components on classloader.
*/
public Set<Class<? extends Component>> allComponents(ClassLoader classLoader, Set<URL> urls) {
// Set the context ClassLoader for this Thread to include all classes.
// if we don't do this Reflections gets confused and fetches only a subset
// of components. probably because duplicate entries of Component.class?
Thread.currentThread().setContextClassLoader(classLoader);
// reflect over components.
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(urls).setScanners(new SubTypesScanner(true)).setExecutorService(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())));
return reflections.getSubTypesOf(Component.class);
}Example 14
| Project: cas-master File: CasEmbeddedContainerUtils.java View source code |
/**
* Gets cas banner instance.
*
* @return the cas banner instance
*/
public static Banner getCasBannerInstance() {
final String packageName = CasEmbeddedContainerUtils.class.getPackage().getName();
final Reflections reflections = new Reflections(new ConfigurationBuilder().filterInputsBy(new FilterBuilder().includePackage(packageName)).setUrls(ClasspathHelper.forPackage(packageName)).setScanners(new SubTypesScanner(true)));
final Set<Class<? extends AbstractCasBanner>> subTypes = reflections.getSubTypesOf(AbstractCasBanner.class);
subTypes.remove(DefaultCasBanner.class);
if (subTypes.isEmpty()) {
return new DefaultCasBanner();
}
try {
final Class<? extends AbstractCasBanner> clz = subTypes.iterator().next();
LOGGER.debug("Created banner [{}]", clz);
return clz.newInstance();
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return new DefaultCasBanner();
}Example 15
| Project: dddlib-master File: EventListenerLoader.java View source code |
/**
* åœ¨æŒ‡å®šçš„åŒ…ä¸æ‰«æ??事件处ç?†å™¨ï¼Œå¹¶å°†å…¶æ³¨å†Œåˆ°äº‹ä»¶æ€»çº¿ã€‚
*/
public void execute() {
for (String each : packages) {
Reflections reflections = new Reflections(each);
Set<Class<? extends AbstractEventListener>> handlers = reflections.getSubTypesOf(AbstractEventListener.class);
for (Class<? extends EventListener> handler : handlers) {
try {
eventBus.register(handler.newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
LOGGER.error("Handler " + handler + " create failed!", e);
} catch (IllegalAccessException e) {
e.printStackTrace();
LOGGER.error("Handler " + handler + " create failed!", e);
}
}
}
}Example 16
| Project: dionysus-master File: EntityIDTest.java View source code |
@Test
public void makeSureEntityIDCanbeDetect() {
Metamodel model = entityManager.getMetamodel();
final Reflections reflections = new Reflections(EntityIDTest.class.getPackage().getName());
Set<Class<?>> entities = reflections.getTypesAnnotatedWith(Entity.class);
for (Class<?> entity : entities) {
EntityType<?> entityType = model.entity(entity);
Class<?> id = entityType.getIdType().getJavaType();
System.out.println(entityType);
if (entity.equals(InvalidEntity.class)) {
Assert.assertEquals(id, Serializable.class);
} else {
Assert.assertNotEquals(id, Serializable.class);
}
}
}Example 17
| Project: dragome-sdk-master File: ServerReflectionServiceImpl.java View source code |
public DragomeConfigurator getConfigurator() {
try {
DragomeConfigurator foundConfigurator = null;
Reflections reflections = new Reflections(".*");
Set<Class<?>> typesAnnotatedWith = null;
typesAnnotatedWith = reflections.getTypesAnnotatedWith(DragomeConfiguratorImplementor.class);
int priorityMax = -1;
Class<?> nextClass = null;
Iterator<Class<?>> iterator = typesAnnotatedWith.iterator();
while (iterator.hasNext()) {
Class<?> next = iterator.next();
DragomeConfiguratorImplementor annotation = next.getAnnotation(DragomeConfiguratorImplementor.class);
int priorityAnno = annotation.priority();
if (priorityAnno > priorityMax) {
priorityMax = priorityAnno;
nextClass = next;
}
}
if (nextClass != null)
foundConfigurator = (DragomeConfigurator) nextClass.newInstance();
if (foundConfigurator == null) {
Set<Class<? extends DragomeConfigurator>> configurators = reflections.getSubTypesOf(DragomeConfigurator.class);
for (Class<? extends DragomeConfigurator> class1 : configurators) {
if (!class1.equals(DomHandlerApplicationConfigurator.class))
foundConfigurator = class1.newInstance();
}
if (foundConfigurator == null)
foundConfigurator = new DomHandlerApplicationConfigurator();
}
return foundConfigurator;
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 18
| Project: fcrepo4-master File: ConstraintExceptionsTest.java View source code |
@Test
public void testConstraintRdfExists() {
final Reflections reflections = new Reflections("org.fcrepo");
final Set<Class<? extends ConstraintViolationException>> subTypes = reflections.getSubTypesOf(ConstraintViolationException.class);
subTypes.add(ConstraintViolationException.class);
for (final Class c : subTypes) {
final File file = new File("src/main/webapp/static/constraints/" + c.getSimpleName() + ".rdf");
Assert.assertTrue("Expected to find: " + file.getPath(), file.exists());
}
}Example 19
| Project: gauge-java-master File: HooksScanner.java View source code |
private void buildHooksRegistry(Reflections reflections) {
HooksRegistry.addBeforeSuiteHooks(reflections.getMethodsAnnotatedWith(BeforeSuite.class));
HooksRegistry.addAfterSuiteHooks(reflections.getMethodsAnnotatedWith(AfterSuite.class));
HooksRegistry.addBeforeSpecHooks(reflections.getMethodsAnnotatedWith(BeforeSpec.class));
HooksRegistry.addAfterSpecHooks(reflections.getMethodsAnnotatedWith(AfterSpec.class));
HooksRegistry.addBeforeScenarioHooks(reflections.getMethodsAnnotatedWith(BeforeScenario.class));
HooksRegistry.addAfterScenarioHooks(reflections.getMethodsAnnotatedWith(AfterScenario.class));
HooksRegistry.addBeforeStepHooks(reflections.getMethodsAnnotatedWith(BeforeStep.class));
HooksRegistry.setAfterStepHooks(reflections.getMethodsAnnotatedWith(AfterStep.class));
HooksRegistry.addBeforeClassStepsHooks(reflections.getMethodsAnnotatedWith(BeforeClassSteps.class));
HooksRegistry.addAfterClassStepsHooks(reflections.getMethodsAnnotatedWith(AfterClassSteps.class));
}Example 20
| Project: guit-master File: Widget2Element.java View source code |
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Reflections reflections = new Reflections("com.google.gwt.dom.client");
for (Class<? extends Node> c : reflections.getSubTypesOf(Node.class)) {
for (Field f : c.getDeclaredFields()) {
if (f.getType().equals(String.class) && f.getName().startsWith("TAG") && Modifier.isStatic(f.getModifiers())) {
f.setAccessible(true);
System.out.println("element2dom.put(\"" + f.get(null) + "\", \"" + c.getCanonicalName() + "\");");
}
}
}
}Example 21
| Project: jsonhome-master File: AnnotationScanner.java View source code |
public Set<Class<?>> scanClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
for (String pkg : packages) {
final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(forClass(Path.class)).addUrls(forPackage(pkg)).setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()).filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(pkg))));
classes.addAll(reflections.getTypesAnnotatedWith(Path.class));
}
return classes;
}Example 22
| Project: Lily-master File: PluginFinder.java View source code |
public void find() throws Exception {
ConfigurationBuilder config = new ConfigurationBuilder();
config.setClassLoaders(new ClassLoader[] { getClass().getClassLoader() });
config.addUrls(Lily.class.getProtectionDomain().getCodeSource().getLocation().toURI().toURL());
Reflections reflections = new Reflections(config);
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(PluginProperties.class);
for (Class<?> clazz : annotated) {
Object objectInstance = clazz.newInstance();
if (!(objectInstance instanceof LilyPlugin)) {
continue;
}
LilyPlugin lilyPlugin = (LilyPlugin) objectInstance;
pluginManager.registerPlugin(lilyPlugin);
}
System.out.println("Amount of loaded plugins: " + annotated.size());
}Example 23
| Project: nextprot-api-master File: EntryBaseSolrIndexer.java View source code |
static void initializeFieldBuilders(Map<Fields, FieldBuilder> fieldsBuilderMap) {
Reflections reflections = new Reflections("org.nextprot.api.tasks.solr.indexer.entry.impl");
Set<Class<?>> entryFieldBuilderClasses = reflections.getTypesAnnotatedWith(EntryFieldBuilder.class);
for (Class<?> c : entryFieldBuilderClasses) {
try {
FieldBuilder fb = (FieldBuilder) c.newInstance();
if (fb.getSupportedFields() != null) {
for (Fields f : fb.getSupportedFields()) {
NPreconditions.checkTrue(!(fieldsBuilderMap.containsKey(f)), "The field " + f.getName() + " is supported by several builders: " + fb.getClass() + ", " + fieldsBuilderMap.get(f));
fieldsBuilderMap.put(f, fb);
}
}
} catch (InstantiationExceptionIllegalAccessException | e) {
e.printStackTrace();
}
}
}Example 24
| Project: nubes-master File: RouteFactory.java View source code |
private List<MVCRoute> extractRoutesFromControllers() {
List<MVCRoute> routes = new ArrayList<>();
config.forEachControllerPackage( controllerPackage -> {
Reflections reflections = new Reflections(controllerPackage);
Set<Class<?>> controllers = reflections.getTypesAnnotatedWith(Controller.class);
controllers.forEach( controller -> routes.addAll(extractRoutesFromController(controller)));
});
return routes;
}Example 25
| Project: play2-crud-master File: ClasspathScanningConverterRegistry.java View source code |
@SuppressWarnings("rawtypes")
private Map<Class<?>, Converter<?>> scan(ClassLoader... classloaders) {
if (log.isDebugEnabled())
log.debug("scan <-");
Collection<URL> urls = ClasspathHelper.forPackage("play.utils.meta.convert", classloaders);
if (log.isDebugEnabled())
log.debug("urls : " + urls);
Configuration configs = new ConfigurationBuilder().setUrls(urls).addClassLoaders(classloaders).setScanners(new SubTypesScanner(false));
final Reflections reflections = new Reflections(configs);
Map<Class<?>, Converter<?>> map = Maps.newHashMap();
Set<Class<? extends Converter>> converterClasses = reflections.getSubTypesOf(Converter.class);
if (log.isDebugEnabled())
log.debug("converterClasses : " + converterClasses);
for (Class<? extends Converter> converterClass : converterClasses) {
try {
if (log.isDebugEnabled())
log.debug("converterClass : " + converterClass);
Converter converter = converterClass.newInstance();
if (converter != null) {
Class<?> keyClass = converter.typeClass();
log.info("Converter:" + keyClass + " : " + converter);
map.put(keyClass, converter);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}Example 26
| Project: schemas-master File: SchemaClassServiceImpl.java View source code |
@PostConstruct
public void initializeSchemaIds() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
Reflections reflections = new Reflections(SCHEMA_CLASS_PACKAGE);
for (Class<? extends SchemaSupport> schemaClass : reflections.getSubTypesOf(SchemaSupport.class)) {
if (schemaClass.isInterface() || Modifier.isAbstract(schemaClass.getModifiers())) {
continue;
}
SchemaId schemaId;
if (schemaClass.isEnum()) {
schemaId = schemaClass.getEnumConstants()[0].getSchemaId();
} else {
Constructor<? extends SchemaSupport> constructor = schemaClass.getDeclaredConstructor();
constructor.setAccessible(true);
schemaId = constructor.newInstance().getSchemaId();
}
schemaIds.add(schemaId);
}
}Example 27
| Project: spring-documenter-master File: Application.java View source code |
public static void main(String[] args) throws Exception {
Reflections reflections = new Reflections("org.springframework");
List<Class<?>> clazzes = new ArrayList<Class<?>>(reflections.getTypesAnnotatedWith(Documented.class));
Collections.sort(clazzes, new Comparator<Class<?>>() {
@Override
public int compare(Class o1, Class o2) {
return o1.getName().compareTo(o2.getName());
}
});
System.out.println("##################################################");
System.out.println("Total Annotations: " + clazzes.size());
System.out.println("##################################################");
String old = IOUtils.toString(new FileReader("annotations-bkp.csv"));
FileWriter out = new FileWriter(new File("annotations.csv"));
out.write("\"Name\",\"Class\",\"URL\"\n");
for (Class<?> class1 : clazzes) {
System.out.println(class1.getName());
Document doc = Jsoup.connect("http://www.bing.com/search?q=" + URLEncoder.encode(class1.getName(), "UTF-8")).get();
int ctr = 1;
for (Element elem : doc.select("h2 a")) {
ctr++;
System.out.println(elem.attr("href"));
out.append("\"" + class1.getSimpleName() + "\",\"" + class1.getName() + "\",\"" + elem.attr("href") + "\"\n");
if (ctr > 2)
break;
}
}
out.close();
System.out.println("##################################################");
}Example 28
| Project: tabletoptool-master File: SerializationVersionAnnotationTest.java View source code |
@DataProvider(name = "traverseAnnotatedClasses")
public Object[][] traverseAnnotatedClasses() {
Reflections reflections = new Reflections("com.t3");
LinkedList<Class<?>> annotatedClasses = new LinkedList<>(reflections.getTypesAnnotatedWith(SerializationVersion.class));
AssertJUnit.assertFalse(annotatedClasses.isEmpty());
MacroEngine.initialize();
for (TokenPropertyType tpt : TokenPropertyType.values()) annotatedClasses.add(tpt.getType());
HashSet<Class<?>> checked = new HashSet<Class<?>>();
while (!annotatedClasses.isEmpty()) {
Class<?> cl = annotatedClasses.removeFirst();
if (cl != null && cl.getClassLoader() != null && !checked.contains(cl)) {
checked.add(cl);
annotatedClasses.addAll(reflections.getSubTypesOf(cl));
annotatedClasses.add(cl.getSuperclass());
}
}
ArrayList<Class<?>> sorted = new ArrayList<>(checked);
Collections.sort(sorted, new Comparator<Class<?>>() {
@Override
public int compare(Class<?> o1, Class<?> o2) {
return o1.getName().compareTo(o2.getName());
}
});
Object[][] result = new Object[checked.size()][1];
for (int i = 0; i < sorted.size(); i++) result[i][0] = sorted.get(i);
System.out.println(sorted);
return result;
}Example 29
| Project: tapestry-tldgen-master File: SingleTypeFieldAnnotationScannerTest.java View source code |
public void testOk() throws MalformedURLException {
Reflections reflection = new Reflections(new ConfigurationBuilder().filterInputsBy(new FilterBuilder.Include(FilterBuilder.prefix("fr.exanpe.test.heritage"))).setUrls(new URL[] { new File("target/test-classes/").toURI().toURL() }).setScanners(new SingleTypeFieldAnnotationScanner(SubSubComponent.class)));
Collection<String> fieldsAsString = reflection.getStore().get(SingleTypeFieldAnnotationScanner.class).values();
assertEquals(3, fieldsAsString.size());
}Example 30
| Project: udidb-master File: OperationProvider.java View source code |
private void addSupportedOperations(String[] opPackages) {
Set<URL> packages = new HashSet<>();
for (String opPackage : opPackages) {
packages.addAll(ClasspathHelper.forPackage(opPackage));
}
Reflections reflections = new Reflections(packages, new SubTypesScanner());
for (Class<? extends Operation> opClass : reflections.getSubTypesOf(Operation.class)) {
if (Modifier.isAbstract(opClass.getModifiers()))
continue;
DisplayName displayName = opClass.getAnnotation(DisplayName.class);
if (displayName != null) {
operations.put(displayName.value(), opClass);
} else {
throw new RuntimeException(opClass.getSimpleName() + " is an invalid Operation.");
}
}
}Example 31
| Project: luwak-master File: TestCoreLuceneQueryExtractors.java View source code |
@Test
public void checkAllCoreQueriesAreHandled() {
quietLogging();
Reflections reflections = new Reflections("org.apache.lucene");
Set<Class<? extends Query>> coreQueries = reflections.getSubTypesOf(Query.class);
QueryAnalyzer defaultAnalyzer = QueryAnalyzer.fromComponents(new WildcardNGramPresearcherComponent());
Set<String> missingClasses = new HashSet<>();
for (Class<? extends Query> c : coreQueries) {
if (Modifier.isAbstract(c.getModifiers()))
continue;
if (Modifier.isPublic(c.getModifiers()) != true)
continue;
if (defaultAnalyzer.getTreeBuilderForQuery(c) == TreeBuilders.ANY_NODE_BUILDER) {
if (shouldHandle(c))
missingClasses.add(c.getName());
}
}
assertThat(missingClasses).isEmpty();
}Example 32
| Project: aorra-master File: DefaultChartBuilder.java View source code |
private static ImmutableList<ChartTypeBuilder> detectBuilders() {
final ImmutableList.Builder<ChartTypeBuilder> b = new ImmutableList.Builder<ChartTypeBuilder>();
for (Class<? extends ChartTypeBuilder> builderClass : new Reflections("charts.builder").getSubTypesOf(ChartTypeBuilder.class)) {
if (builderClass.isInterface())
continue;
if (Modifier.isAbstract(builderClass.getModifiers()))
continue;
try {
Logger.debug("Found chart builder: " + builderClass.getCanonicalName());
b.add(builderClass.newInstance());
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return b.build();
}Example 33
| Project: atam4j-master File: Atam4j.java View source code |
private Class[] findTestClasses() {
final Class[] classes = testClasses.orElseGet(() -> new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forJavaClassPath()).setScanners(new SubTypesScanner(), new TypeAnnotationsScanner())).getTypesAnnotatedWith(Monitor.class).stream().toArray(Class[]::new));
if (classes.length == 0) {
throw new NoTestClassFoundException("Could not find any annotated test classes and no classes were provided via the Atam4jBuilder.");
}
return classes;
}Example 34
| Project: atom-nuke-master File: ContainerBootstrap.java View source code |
@Override
public void bootstrap() {
final ExecutorService bootStrapExecutorService = new ThreadPoolExecutor(nukeEnvironment.numProcessors(), nukeEnvironment.numProcessors(), 5, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
final Reflections bootstrapScanner = new Reflections(new ConfigurationBuilder().setScanners(new TypeAnnotationsScanner()).setExecutorService(bootStrapExecutorService).setUrls(ClasspathHelper.forClassLoader(Thread.currentThread().getContextClassLoader(), ClassLoader.getSystemClassLoader())));
bootStrapExecutorService.shutdownNow();
for (Class bootstrapService : bootstrapScanner.getTypesAnnotatedWith(NukeBootstrap.class)) {
if (Service.class.isAssignableFrom(bootstrapService)) {
LOG.debug("Submitting bootstrap service: " + bootstrapService.getName());
try {
final Service serviceInstance = (Service) bootstrapService.newInstance();
serviceManager.submit(new InstanceContextImpl<Service>(NopInstanceEnvironment.getInstance(), serviceInstance));
} catch (Exception ex) {
LOG.error("Failed to load bootstrap service: " + bootstrapService.getName() + " - This may cause unexpected behavior however the container may still attempt normal init.", ex);
}
}
}
for (Class bootstrapService : bootstrapScanner.getTypesAnnotatedWith(NukeService.class)) {
if (Service.class.isAssignableFrom(bootstrapService)) {
LOG.debug("Submitting bootstrap service: " + bootstrapService.getName());
try {
final Service serviceInstance = (Service) bootstrapService.newInstance();
serviceManager.submit(new InstanceContextImpl<Service>(NopInstanceEnvironment.getInstance(), serviceInstance));
} catch (Exception ex) {
LOG.error("Failed to load service: " + bootstrapService.getName() + " - This may cause unexpected behavior however the container may still attempt normal init.", ex);
}
}
}
serviceManager.resolve();
}Example 35
| Project: baigan-config-master File: ConfigurationBeanDefinitionRegistrar.java View source code |
private void createAndRegisterBeanDefinitions(final Set<String> packages, final BeanDefinitionRegistry registry) {
for (final String singlePackage : packages) {
final Set<Class<?>> configServiceInterfaces = new Reflections(singlePackage).getTypesAnnotatedWith(BaiganConfig.class);
for (final Class<?> interfaceToImplement : configServiceInterfaces) {
final BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ConfigurationServiceBeanFactory.class);
builder.addPropertyValue("candidateInterface", interfaceToImplement);
final String factoryBeanName = interfaceToImplement.getName() + "BaiganProxyConfigurationFactoryBean";
registry.registerBeanDefinition(factoryBeanName, builder.getBeanDefinition());
}
}
}Example 36
| Project: c10n-master File: C10NModule.java View source code |
@SuppressWarnings("unchecked")
@Override
protected void configure() {
Set<Class<?>> c10nTypes = new Reflections(new ConfigurationBuilder().filterInputsBy(getPackageInputFilter()).setUrls(getPackageURLs())).getTypesAnnotatedWith(C10NMessages.class);
for (Class<?> c10nType : c10nTypes) {
if (c10nType.isInterface()) {
bind((Class<Object>) c10nType).toInstance(C10N.get(c10nType));
}
}
}Example 37
| Project: cointrader-master File: ReflectionUtil.java View source code |
public static Reflections getCommandReflections() { if (commandReflections == null) { List<String> paths = ConfigUtil.getPathProperty("command.path"); Set<URL> urls = new HashSet<>(); for (String path : paths) urls.addAll(ClasspathHelper.forPackage(path)); commandReflections = new Reflections(urls, new SubTypesScanner()); } return commandReflections; }
Example 38
| Project: coner-master File: ConerCoreApplication.java View source code |
private HibernateBundle<ConerCoreConfiguration> getHibernateBundle() {
if (hibernateBundle == null) {
Reflections r = new Reflections("org.coner.core.hibernate.entity");
Set<Class<? extends HibernateEntity>> hibernateEntityClasses = r.getSubTypesOf(HibernateEntity.class);
hibernateBundle = new HibernateBundle<ConerCoreConfiguration>(ImmutableList.copyOf(hibernateEntityClasses), new SessionFactoryFactory()) {
@Override
public DataSourceFactory getDataSourceFactory(ConerCoreConfiguration conerCoreConfiguration) {
return conerCoreConfiguration.getDataSourceFactory();
}
};
}
return hibernateBundle;
}Example 39
| Project: craftconomy3-master File: TestLoadedCommands.java View source code |
@Test
public void testCommands() {
Reflections reflections = new Reflections("com.greatmancode.craftconomy3.commands");
for (Class<? extends CommandExecutor> clazz : reflections.getSubTypesOf(CommandExecutor.class)) {
try {
CommandExecutor instance = clazz.newInstance();
if (instance.help() == null) {
fail("Help is null for: " + clazz.getName());
}
if (instance.maxArgs() < 0) {
fail("Fail maxArgs for class: " + clazz.getName());
}
if (instance.minArgs() < 0) {
fail("Fail minArgs for class: " + clazz.getName());
}
if (instance.maxArgs() < instance.minArgs()) {
fail("Fail maxArgs less than minArgs for class:" + clazz.getName());
}
if (instance.getPermissionNode() != null) {
if (!instance.getPermissionNode().contains("craftconomy")) {
fail("Fail permissionNode for class: " + clazz.getName());
}
}
if (!instance.playerOnly() && instance.playerOnly()) {
fail("Fail playerOnly. Should never get this..");
}
} catch (InstantiationException e) {
fail(e.getMessage());
} catch (IllegalAccessException e) {
fail(e.getMessage());
}
}
}Example 40
| Project: dbfit-master File: DbEnvironmentFactory.java View source code |
private void initDefaultEnvironments() {
Reflections reflections = new Reflections("dbfit");
for (Class<?> c : reflections.getTypesAnnotatedWith(DatabaseEnvironment.class)) {
DatabaseEnvironment envAnnotation = c.getAnnotation(DatabaseEnvironment.class);
registerEnv(envAnnotation.name(), envAnnotation.driver());
}
}Example 41
| Project: disconf-master File: ScanPrinterUtils.java View source code |
/**
* 打�出StoreMap的数�
*/
public static void printStoreMap(Reflections reflections) {
LOGGER.info("Now we will print store map......");
Store store = reflections.getStore();
Map<String, /* indexName */
Multimap<String, String>> storeMap = store.getStoreMap();
for (String indexName : storeMap.keySet()) {
LOGGER.info("====================================");
LOGGER.info("indexName:" + indexName);
Multimap<String, String> multimap = storeMap.get(indexName);
for (String firstName : multimap.keySet()) {
Collection<String> lastNames = multimap.get(firstName);
LOGGER.info("\t\t" + firstName + ": " + lastNames);
}
}
}Example 42
| Project: DLect-master File: AnnotatedClassFinder.java View source code |
@SafeVarargs
public static Set<Class<?>> getClassesWithAll(String packageName, Class<? extends Annotation> annotation, Class<? extends Annotation>... annotations) {
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(packageName)).setScanners(new MethodAnnotationsScanner()));
Set<Class<?>> methods = Sets.newHashSet(reflections.getTypesAnnotatedWith(annotation));
for (Class<? extends Annotation> anot : annotations) {
methods.retainAll(reflections.getTypesAnnotatedWith(anot));
}
return methods;
}Example 43
| Project: es4j-master File: PackageScanner.java View source code |
Set<Class<? extends T>> scan(Class<? extends T> aClass) {
Configuration configuration = ConfigurationBuilder.build((Object[]) packages).addClassLoaders(classLoaders).addScanners(new AssignableScanner(aClass));
Reflections reflections = new Reflections(configuration);
Predicate<Class<? extends T>> classPredicate = klass -> Modifier.isPublic(klass.getModifiers()) && (!klass.isMemberClass() || (klass.isMemberClass() && Modifier.isStatic(klass.getModifiers()))) && !Modifier.isInterface(klass.getModifiers()) && !Modifier.isAbstract(klass.getModifiers());
HashSet<Class<? extends T>> subtypes = Sets.newHashSet(ReflectionUtils.forNames(reflections.getStore().getAll(AssignableScanner.class.getSimpleName(), Collections.singletonList(aClass.getName())), classLoaders));
return subtypes.stream().filter(classPredicate).collect(Collectors.toSet());
}Example 44
| Project: estatio-master File: UdoDomainObjectContract_jdoAnnotations_Test.java View source code |
@SuppressWarnings("rawtypes")
@Test
public void searchAndTest() {
Reflections reflections = new Reflections("org.estatio.dom");
Set<Class<? extends UdoDomainObject>> subtypes = reflections.getSubTypesOf(UdoDomainObject.class);
for (Class<? extends UdoDomainObject> subtype : subtypes) {
if (subtype.isAnonymousClass() || subtype.isLocalClass() || subtype.isMemberClass() || subtype.getName().endsWith("ForTesting")) {
// skip (probably a testing class)
continue;
}
if (UdoDomainObject.class == subtype || UdoDomainObject2.class == subtype) {
// skip
continue;
}
System.out.println(">>> " + subtype.getName());
// must have a @PersistenceCapable(identityType=...) annotation
final PersistenceCapable persistenceCapable = subtype.getAnnotation(PersistenceCapable.class);
Assertions.assertThat(persistenceCapable).isNotNull();
IdentityType identityType = persistenceCapable.identityType();
Assertions.assertThat(identityType).isNotNull();
if (identityType == IdentityType.DATASTORE) {
// NOT mandatory to have a @DatastoreIdentity, but if does, then @DatastoreIdentity(..., column="id")
final DatastoreIdentity datastoreIdentity = subtype.getAnnotation(DatastoreIdentity.class);
if (datastoreIdentity != null) {
Assertions.assertThat(datastoreIdentity.column()).isEqualTo("id");
}
}
Inheritance inheritance = subtype.getAnnotation(Inheritance.class);
if (inheritance != null && inheritance.strategy() == InheritanceStrategy.SUPERCLASS_TABLE) {
// must NOT have a @Discriminator(..., column="discriminator")
final Annotation[] declaredAnnotations = subtype.getDeclaredAnnotations();
for (Annotation declaredAnnotation : declaredAnnotations) {
if (declaredAnnotation.annotationType() == Discriminator.class) {
Assert.fail("Class " + subtype.getName() + " inherits from " + subtype.getSuperclass().getName() + "and has (incorrectly) been annotated with @Discriminator");
}
}
// check if supertype has discriminator
// must have a @Discriminator(..., column="discriminator") on one of its supertypes
final Discriminator superDiscriminator = subtype.getSuperclass().getAnnotation(Discriminator.class);
Assertions.assertThat(superDiscriminator).isNotNull();
Assertions.assertThat(superDiscriminator.column()).isEqualTo("discriminator");
}
if (subtype.getSuperclass().equals(UdoDomainObject.class)) {
// must have a @Version(..., column="version")
final Version version = getAnnotationOfTypeOfItsSupertypes(subtype, Version.class);
Assertions.assertThat(version).isNotNull();
Assertions.assertThat(version.column()).isEqualTo("version");
}
}
}Example 45
| Project: flink-master File: StateHandleSerializationTest.java View source code |
/**
* This test validates that all subclasses of {@link StateObject} have a proper
* serial version UID.
*/
@Test
public void ensureStateHandlesHaveSerialVersionUID() {
try {
Reflections reflections = new Reflections("org.apache.flink");
// check all state handles
@SuppressWarnings("unchecked") Set<Class<?>> stateHandleImplementations = (Set<Class<?>>) (Set<?>) reflections.getSubTypesOf(StateObject.class);
for (Class<?> clazz : stateHandleImplementations) {
validataSerialVersionUID(clazz);
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}Example 46
| Project: gisgraphy-master File: EntityTest.java View source code |
@Test
public void CheckAllEntitiesHasTheirPlacetype() {
Reflections reflections = new Reflections("com.gisgraphy.domain.geoloc.entity");
Set<Class<? extends GisFeature>> allClasses = reflections.getSubTypesOf(GisFeature.class);
System.out.println("Found " + allClasses.size() + " entities that extends GisFeature");
for (Class c : allClasses) {
System.out.println(c.getSimpleName());
try {
Class placetype = Class.forName("com.gisgraphy.domain.placetype." + c.getSimpleName());
} catch (ClassNotFoundException e) {
Assert.fail("com.gisgraphy.domain.placetype." + c.getSimpleName() + " doesn't exists, each entities should have their placetype");
}
}
}Example 47
| Project: judochop-master File: SetupDao.java View source code |
public void setup() throws IOException, NoSuchFieldException, IllegalAccessException {
String key;
CreateIndexResponse ciResp;
Reflections reflections = new Reflections("org.apache.usergrid.chop.webapp.dao");
Set<Class<? extends Dao>> daoClasses = reflections.getSubTypesOf(Dao.class);
IndicesAdminClient client = elasticSearchClient.getClient().admin().indices();
for (Class<? extends Dao> daoClass : daoClasses) {
key = daoClass.getDeclaredField("DAO_INDEX_KEY").get(null).toString();
if (!client.exists(new IndicesExistsRequest(key)).actionGet().isExists()) {
ciResp = client.create(new CreateIndexRequest(key)).actionGet();
if (ciResp.isAcknowledged()) {
LOG.debug("Index for key {} didn't exist, now created", key);
} else {
LOG.debug("Could not create index for key: {}", key);
}
} else {
LOG.debug("Key {} already exists", key);
}
}
}Example 48
| Project: Kylin-master File: KyroMappingGenerator.java View source code |
public static void main(String[] args) {
Set<Class<? extends Serializable>> subTypesOfSerializable = new Reflections("org.apache.kylin").getSubTypesOf(Serializable.class);
String begin = "kyroClasses.add(";
String end = ".class);";
TreeSet<String> sortedSet = new TreeSet();
for (Class clazz : subTypesOfSerializable) {
if (clazz.getCanonicalName() != null)
sortedSet.add(clazz.getCanonicalName());
}
Set<Class<? extends BytesSerializer>> subTypesOfBytes = new Reflections("org.apache.kylin.metadata.datatype").getSubTypesOf(BytesSerializer.class);
for (Class clazz : subTypesOfBytes) {
if (clazz.getCanonicalName() != null)
sortedSet.add(clazz.getCanonicalName());
}
Set<Class<? extends MeasureIngester>> subTypesOfMeasure = new Reflections("org.apache.kylin.measure").getSubTypesOf(MeasureIngester.class);
for (Class clazz : subTypesOfMeasure) {
if (clazz.getCanonicalName() != null)
sortedSet.add(clazz.getCanonicalName());
}
for (String className : sortedSet) {
System.out.println(begin + className + end);
}
}Example 49
| Project: mjprof-master File: PluginUtils.java View source code |
//conParameter - constructor parameters
public static HashMap<Class, Class> getAllPlugins() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, ClassNotFoundException {
HashMap<Class, Class> map = new HashMap<>();
//TODO
Reflections reflections = new Reflections("com.performizeit");
Set<Class<?>> annotatedPlugin = reflections.getTypesAnnotatedWith(Plugin.class);
for (Class cla : annotatedPlugin) {
if (BasePlugin.class.isAssignableFrom(cla)) {
invokeGetHelpLine(cla);
map.put(cla, cla);
} else {
System.out.println("ERROR: class " + cla.getName() + " needs to extend BasePlugin child");
}
}
return map;
}Example 50
| Project: mongobee-master File: ChangeService.java View source code |
public List<Class<?>> fetchChangeLogs() {
Reflections reflections = new Reflections(changeLogsBasePackage);
// TODO remove dependency, do own method
Set<Class<?>> changeLogs = reflections.getTypesAnnotatedWith(ChangeLog.class);
List<Class<?>> filteredChangeLogs = (List<Class<?>>) filterByActiveProfiles(changeLogs);
Collections.sort(filteredChangeLogs, new ChangeLogComparator());
return filteredChangeLogs;
}Example 51
| Project: nd4j-master File: JacksonReflectionLoader.java View source code |
/**
* Get the implementations for a given list of classes.
* These classes MUST be abstract classes or interfaces
* @param types the types to get hte sub classes for
* @return a map containing a list of interface names to
* implementation types
*/
public static Map<String, String> getImpls(List<Class<?>> types) {
Map<String, String> classes = new HashMap<>();
for (Class<?> type : types) {
Reflections reflections = new Reflections();
Set<Class<?>> subClasses = (Set<Class<?>>) reflections.getSubTypesOf(type);
if (subClasses.size() > 1) {
throw new IllegalArgumentException(String.format("Class " + type + " type can't be inferred. There is more than %d of sub class for the given class", subClasses.size()));
} else if (subClasses.isEmpty())
throw new IllegalArgumentException("No class implementation found for " + type.getCanonicalName());
classes.put(type.getCanonicalName(), subClasses.iterator().next().getCanonicalName());
}
return classes;
}Example 52
| Project: oodt-master File: Workbench.java View source code |
public static Set<String> getImageFiles(String packageName) {
Pattern pattern = Pattern.compile(".*\\.(png|gif|jpg|jpeg|jp2)");
Set<String> resources = new Reflections(packageName, new ResourcesScanner()).getResources(pattern);
Set<String> filteredResources = new HashSet<String>();
Map<String, Boolean> resMap = new ConcurrentHashMap<String, Boolean>();
for (String res : resources) {
String resName = new File(res).getName();
if (!resMap.containsKey(resName)) {
resMap.put(resName, true);
filteredResources.add(resName);
}
}
return filteredResources;
}Example 53
| Project: play-sitemap-module.edulify.com-master File: AnnotationUrlProvider.java View source code |
@Override
public void addUrlsTo(WebSitemapGenerator generator) {
String baseUrl = configuration.getString("sitemap.baseUrl");
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Reflections reflections = new Reflections("controllers", new MethodAnnotationsScanner());
Set<Method> actions = reflections.getMethodsAnnotatedWith(SitemapItem.class);
for (Method method : actions) {
String actionUrl = actionUrl(classLoader, method);
SitemapItem annotation = method.getAnnotation(SitemapItem.class);
if (annotation != null) {
WebSitemapUrl url = webSitemapUrl(baseUrl, actionUrl, annotation);
generator.addUrl(url);
}
}
}Example 54
| Project: replication-benchmarker-master File: SimulatorConfigurator.java View source code |
public static void main(String args[]) {
try {
/*
* System.out.println("hello !"); List<String> ls =
* lireListService("jbenchmarker");
*
* for (String s : ls) { System.out.println("->" + s);
}
*/
//System.exit(0);
Reflections reflections = new Reflections("");
Set<Class<? extends CRDT>> subTypes = reflections.getSubTypesOf(CRDT.class);
for (Class<? extends CRDT> c : subTypes) {
System.out.println("" + c.getName());
}
//switch case()
System.exit(0);
Factory<CRDT> rf = (Factory<CRDT>) Class.forName(args[0]).newInstance();
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}Example 55
| Project: SubTools-master File: Bootstrapper.java View source code |
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<ServiceProvider> getProviders() {
Reflections reflections = new Reflections("org.lodder.subtools.multisubdownloader");
Set<Class<? extends ServiceProvider>> providerClasses = reflections.getSubTypesOf(ServiceProvider.class);
List<ServiceProvider> providers = new ArrayList<>();
// Intantieer alle serviceproviders
for (Class serviceProviderClass : providerClasses) {
ServiceProvider serviceProvider = null;
try {
Constructor constructor = serviceProviderClass.getConstructor();
serviceProvider = (ServiceProvider) constructor.newInstance();
} catch (Exception e) {
LOGGER.error("ServiceProvider: '{}' failed to create instance.", serviceProviderClass.getClass().getName());
}
if (serviceProvider == null)
continue;
providers.add(serviceProvider);
}
return providers;
}Example 56
| Project: swagger-core-master File: ReflectiveJaxrsScanner.java View source code |
protected Reflections getReflections() { if (reflections == null) { ConfigurationBuilder config = new ConfigurationBuilder(); acceptablePackages = new HashSet<String>(); if (resourcePackage != "") { String[] parts = resourcePackage.split(","); for (String pkg : parts) { if (!"".equals(pkg)) { acceptablePackages.add(pkg); config.addUrls(ClasspathHelper.forPackage(pkg)); } } } config.setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner()); this.reflections = new Reflections(config); } return this.reflections; }
Example 57
| Project: TeraSpout-master File: ComponentSystemManager.java View source code |
public void loadSystems(String packageName, String rootPackagePath) {
Reflections reflections = new Reflections(rootPackagePath);
Set<Class<?>> systems = reflections.getTypesAnnotatedWith(RegisterComponentSystem.class);
for (Class<?> system : systems) {
if (!ComponentSystem.class.isAssignableFrom(system)) {
logger.log(Level.WARNING, String.format("Cannot load %s, must be a subclass of ComponentSystem", system.getSimpleName()));
continue;
}
RegisterComponentSystem registerInfo = system.getAnnotation(RegisterComponentSystem.class);
// TODO: filter registrations
String id = packageName + ":" + system.getSimpleName();
try {
ComponentSystem newSystem = (ComponentSystem) system.newInstance();
register(newSystem, id);
logger.log(Level.INFO, "Loaded " + id);
} catch (InstantiationException e) {
logger.log(Level.SEVERE, "Failed to load system " + id, e);
} catch (IllegalAccessException e) {
logger.log(Level.SEVERE, "Failed to load system " + id, e);
}
}
}Example 58
| Project: thysdrus-master File: CircuitBreakerDiscoverer.java View source code |
//@Override
public void afterPropertiesSet() throws Exception {
String beanNames[] = context.getBeanNamesForType(CircuitBreakerDefinition.class);
if (beanNames != null && beanNames.length > 0) {
Reflections reflections = new Reflections("", new MethodAnnotationsScanner());
Set<Method> methods = reflections.getMethodsAnnotatedWith(MonitoredByCircuitBreakerBean.class);
logger.info("methods: " + methods);
if (methods == null) {
return;
}
// scan the class path for annotation store them in a map <beanId, method>
Map<String, List<Method>> annotatedMethods = new HashMap<String, List<Method>>();
Iterator<Method> iterator = methods.iterator();
while (iterator.hasNext()) {
Method method = iterator.next();
MonitoredByCircuitBreakerBean annotation = method.getAnnotation(MonitoredByCircuitBreakerBean.class);
if (annotation != null) {
List<Method> methodList = annotatedMethods.get(annotation.value());
if (methodList == null) {
methodList = new ArrayList<Method>();
}
methodList.add(method);
annotatedMethods.put(annotation.value(), methodList);
}
}
for (String beanName : beanNames) {
CircuitBreakerDefinition cbDefinition = (CircuitBreakerDefinition) context.getBean(beanName);
CircuitBreaker circuitBreaker = new CircuitBreaker();
String key = cbDefinition.getCircuitBreakerKey() == null ? beanName : cbDefinition.getCircuitBreakerKey();
circuitBreaker.setCircuitBreakerKey(key);
circuitBreaker.setFailureIndications(cbDefinition.getFailureIndications());
circuitBreaker.setFailureThreshold(cbDefinition.getFailureThreshold());
circuitBreaker.setFailureThresholdTimeFrameMs(cbDefinition.getFailureThresholdTimeFrameMs());
circuitBreaker.setRetryTimeoutMs(cbDefinition.getRetryTimeoutMs());
circuitBreaker.setRegisteredMethods(annotatedMethods.get(beanName));
cbHandler.registerCircuitBreaker(circuitBreaker);
}
}
}Example 59
| Project: tinyspring-master File: ApiScanner.java View source code |
public static ApiDocumentation scan(String version, String path, List<String> packages) {
Set<URL> urls = new HashSet<URL>();
FilterBuilder filter = new FilterBuilder();
log.debug("Scanning {} package(s)...", packages.size());
for (String pkg : packages) {
urls.addAll(ClasspathHelper.forPackage(pkg));
filter.includePackage(pkg);
}
Reflections reflections = new Reflections(new ConfigurationBuilder().filterInputsBy(filter).setUrls(urls));
ApiDocumentation apiDoc = new ApiDocumentation(version, path);
apiDoc.setRepositories(scanApiRepository(reflections.getTypesAnnotatedWith(ApiRepository.class)));
apiDoc.setModels(scanApiModel(reflections.getTypesAnnotatedWith(ApiModel.class)));
return apiDoc;
}Example 60
| Project: user-master File: SetupDao.java View source code |
public void setup() throws IOException, NoSuchFieldException, IllegalAccessException {
String key;
CreateIndexResponse ciResp;
Reflections reflections = new Reflections("org.apache.usergrid.chop.webapp.dao");
Set<Class<? extends Dao>> daoClasses = reflections.getSubTypesOf(Dao.class);
IndicesAdminClient client = elasticSearchClient.getClient().admin().indices();
for (Class<? extends Dao> daoClass : daoClasses) {
key = daoClass.getDeclaredField("DAO_INDEX_KEY").get(null).toString();
if (!client.exists(new IndicesExistsRequest(key)).actionGet().isExists()) {
ciResp = client.create(new CreateIndexRequest(key)).actionGet();
if (ciResp.isAcknowledged()) {
LOG.debug("Index for key {} didn't exist, now created", key);
} else {
LOG.debug("Could not create index for key: {}", key);
}
} else {
LOG.debug("Key {} already exists", key);
}
}
}Example 61
| Project: usergrid-master File: SetupDao.java View source code |
public void setup() throws IOException, NoSuchFieldException, IllegalAccessException {
String key;
CreateIndexResponse ciResp;
Reflections reflections = new Reflections("org.apache.usergrid.chop.webapp.dao");
Set<Class<? extends Dao>> daoClasses = reflections.getSubTypesOf(Dao.class);
IndicesAdminClient client = elasticSearchClient.getClient().admin().indices();
for (Class<? extends Dao> daoClass : daoClasses) {
key = daoClass.getDeclaredField("DAO_INDEX_KEY").get(null).toString();
if (!client.exists(new IndicesExistsRequest(key)).actionGet().isExists()) {
ciResp = client.create(new CreateIndexRequest(key)).actionGet();
if (ciResp.isAcknowledged()) {
LOG.debug("Index for key {} didn't exist, now created", key);
} else {
LOG.debug("Could not create index for key: {}", key);
}
} else {
LOG.debug("Key {} already exists", key);
}
}
}Example 62
| Project: ysoserial-master File: ObjectPayload.java View source code |
// get payload classes by classpath scanning
public static Set<Class<? extends ObjectPayload>> getPayloadClasses() {
final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName());
final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class);
for (Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) {
Class<? extends ObjectPayload> pc = iterator.next();
if (pc.isInterface() || Modifier.isAbstract(pc.getModifiers())) {
iterator.remove();
}
}
return payloadTypes;
}Example 63
| Project: astrix-master File: AstrixApiProviderClassScanner.java View source code |
private Stream<ApiProviderClass> scanPackage(String basePackage) {
log.debug("Scanning package for api-providers: package={}", basePackage);
List<ApiProviderClass> providerClasses = apiProvidersByBasePackage.get(basePackage);
if (providerClasses != null) {
log.debug("Returning cached api-providers found on earlier scan types={}", providerClasses);
return providerClasses.stream();
}
List<Class<? extends Annotation>> allProviderAnnotationTypes = getAllProviderAnnotationTypes();
log.debug("Running scan for api-providers of types={}", allProviderAnnotationTypes);
List<ApiProviderClass> discoveredApiPRoviders = new ArrayList<>();
Reflections reflections = new Reflections(basePackage);
for (Class<? extends Annotation> apiAnnotation : allProviderAnnotationTypes) {
for (Class<?> providerClass : reflections.getTypesAnnotatedWith(apiAnnotation)) {
ApiProviderClass provider = ApiProviderClass.create(providerClass);
log.debug("Found api provider {}", provider);
discoveredApiPRoviders.add(provider);
}
}
apiProvidersByBasePackage.put(basePackage, discoveredApiPRoviders);
return discoveredApiPRoviders.stream();
}Example 64
| Project: autobots-master File: MainFreelanceComp.java View source code |
public static void main(String[] args) throws Exception {
SelenideUtils.configureBrowser(CHROME);
long startTime = System.currentTimeMillis();
Reflections reflections = new Reflections(FlProcessor.class.getPackage().getName());
Set<Class<? extends FlProcessor>> sites = reflections.getSubTypesOf(FlProcessor.class);
Set<Job> jobs = new LinkedHashSet<>();
for (Class<? extends FlProcessor> siteProcessorClass : sites) {
try {
if (siteProcessorClass == CURRENT_SITE_CLASS) {
jobs.addAll(grabSiteJobs(siteProcessorClass));
}
} catch (ExceptionError | e) {
e.printStackTrace();
System.out.printf("duration=%s\n", System.currentTimeMillis() - startTime);
return;
}
}
ExcelIO excelIO = new ExcelIO(OUTPUT_XLSX, WRITE);
Job instance = jobs.iterator().next();
excelIO.createSheet(instance.getSite());
List<String> columnNames = Arrays.asList(instance.getClass().getDeclaredFields()).stream().map(Field::getName).collect(Collectors.toList());
excelIO.printRow(false, columnNames.toArray(new String[columnNames.size()]));
for (Job job : jobs) {
excelIO.printRow(false, job.getSite(), job.getQueryName(), job.getUrl(), job.getProposalCount(), job.getLifeDuration());
}
excelIO.close();
System.out.printf("Program execution finished, duration=%s\n", System.currentTimeMillis() - startTime);
// System.exit(0);
}Example 65
| Project: baleen-master File: StructureUtil.java View source code |
/**
* Get the given structure classes from by name or return all classes if null or empty
*
* @param typeNames the types to get
* @return the structure classes
* @throws ResourceInitializationException
*/
public static Set<Class<? extends Structure>> getStructureClasses(String[] typeNames) throws ResourceInitializationException {
Set<Class<? extends Structure>> structuralClasses = new HashSet<>();
if (typeNames == null || typeNames.length == 0) {
Reflections reflections = new Reflections(DEFAULT_STRUCTURAL_PACKAGE);
structuralClasses = reflections.getSubTypesOf(Structure.class);
} else {
for (final String typeName : typeNames) {
try {
structuralClasses.add(BuilderUtils.getClassFromString(typeName, DEFAULT_STRUCTURAL_PACKAGE));
} catch (final InvalidParameterException e) {
throw new ResourceInitializationException(e);
}
}
}
return structuralClasses;
}Example 66
| Project: behave-master File: DesktopReflectionUtil.java View source code |
@SuppressWarnings("unchecked")
public static ElementIndex getElementIndex(String pageName, String elementName) {
Reflections reflections = new Reflections("");
Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(ScreenMap.class);
Class<?> clazz = null;
for (Class<?> clazzI : annotatedClasses) {
ScreenMap annotation = clazzI.getAnnotation(ScreenMap.class);
if (annotation.name().equals(pageName)) {
clazz = clazzI;
break;
}
}
if (clazz == null)
throw new RuntimeException("Nenhuma Tela foi encontrada com o nome [" + pageName + "].");
Set<Field> fields = ReflectionUtils.getAllFields(clazz, ReflectionUtils.withAnnotation(ElementIndex.class));
ElementIndex index = null;
for (Field fieldI : fields) {
ElementMap annotation = fieldI.getAnnotation(ElementMap.class);
if (annotation.name().equals(elementName)) {
index = fieldI.getAnnotation(ElementIndex.class);
break;
}
}
return index;
}Example 67
| Project: beowulf-master File: ScsManager.java View source code |
private void initializeReflections() {
// reflections = new Reflections("com.nvarghese.beowulf.scs");
reflections = new Reflections(new ConfigurationBuilder().filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.nvarghese.beowulf.scs"))).setUrls(ClasspathHelper.forPackage("com.nvarghese.beowulf.scs")).setScanners(new SubTypesScanner()));
}Example 68
| Project: BoofCV-master File: ExampleLauncherApp.java View source code |
@Override
protected void createTree(DefaultMutableTreeNode root) {
List<String> packages = new ArrayList<>();
packages.add("boofcv.examples.calibration");
packages.add("boofcv.examples.enhance");
packages.add("boofcv.examples.features");
packages.add("boofcv.examples.fiducial");
packages.add("boofcv.examples.geometry");
packages.add("boofcv.examples.imageprocessing");
packages.add("boofcv.examples.recognition");
packages.add("boofcv.examples.segmentation");
packages.add("boofcv.examples.sfm");
packages.add("boofcv.examples.stereo");
packages.add("boofcv.examples.tracking");
// Reflections is a weird package that does not behave the way one would expect. Several hacks below
for (String p : packages) {
Reflections reflections = new Reflections(p, new SubTypesScanner(false));
List<String> listTypes = new ArrayList<>();
listTypes.addAll(reflections.getAllTypes());
addAll((Set) reflections.getSubTypesOf(LearnSceneFromFiles.class), listTypes);
String name = p.split("\\.")[2];
Collections.sort(listTypes);
List<Class> classes = new ArrayList<>();
String classNames[] = listTypes.toArray(new String[1]);
for (int i = 0; i < classNames.length; i++) {
if (!classNames[i].contains("Example"))
continue;
// no idea why this is needed
if (classNames[i].contains("$"))
continue;
try {
classes.add(Class.forName(classNames[i]));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
createNodes(root, name, classes.toArray(new Class[0]));
}
}Example 69
| Project: botan-core-master File: Robot.java View source code |
private void setActions() {
final Reflections reflections = new Reflections();
Set<Class<? extends BotanMessageHandlers>> classes = reflections.getSubTypesOf(BotanMessageHandlers.class);
classes.forEach( clazz -> {
try {
final BotanMessageHandlers register = clazz.newInstance();
register.initialize(this);
register.register(this);
registers.add(register);
} catch (final InstantiationExceptionIllegalAccessException | e) {
e.printStackTrace();
}
});
}Example 70
| Project: che-master File: DynaProviderGenerator.java View source code |
private void findDynaObjects() throws IOException {
ConfigurationBuilder configuration = new ConfigurationBuilder();
List<URL> urls = new ArrayList<>();
for (String element : classpath) {
urls.add(new File(element).toURI().toURL());
}
ClassLoader contextClassLoader = URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(contextClassLoader);
configuration.setUrls(ClasspathHelper.forClassLoader(contextClassLoader));
configuration.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
Reflections reflection = new Reflections(configuration);
Set<Class<?>> classes = reflection.getTypesAnnotatedWith(DynaObject.class);
for (Class clazz : classes) {
//accept only classes
if (clazz.isEnum() || clazz.isInterface() || clazz.isAnnotation()) {
continue;
}
dynaClasses.add(new ClassModel(clazz));
System.out.println(String.format("New Dyna Object Found: %s", clazz.getCanonicalName()));
}
System.out.println(String.format("Found: %d Dyna Objects", dynaClasses.size()));
}Example 71
| Project: DevTools-master File: DynaProviderGenerator.java View source code |
private void findDynaObjects() throws IOException {
ConfigurationBuilder configuration = new ConfigurationBuilder();
List<URL> urls = new ArrayList<>();
for (String element : classpath) {
urls.add(new File(element).toURI().toURL());
}
ClassLoader contextClassLoader = URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(contextClassLoader);
configuration.setUrls(ClasspathHelper.forClassLoader(contextClassLoader));
configuration.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
Reflections reflection = new Reflections(configuration);
Set<Class<?>> classes = reflection.getTypesAnnotatedWith(DynaObject.class);
for (Class clazz : classes) {
//accept only classes
if (clazz.isEnum() || clazz.isInterface() || clazz.isAnnotation()) {
continue;
}
dynaClasses.add(new ClassModel(clazz));
System.out.println(String.format("New Dyna Object Found: %s", clazz.getCanonicalName()));
}
System.out.println(String.format("Found: %d Dyna Objects", dynaClasses.size()));
}Example 72
| Project: dkpro-core-master File: CasValidator.java View source code |
public static CasValidator createWithAllChecks() {
Reflections reflections = new Reflections(Check.class.getPackage().getName());
CasValidator validator = new CasValidator();
validator.setChecks(reflections.getSubTypesOf(Check.class).stream().filter( c -> !Modifier.isAbstract(c.getModifiers())).collect(Collectors.toList()));
return validator;
}Example 73
| Project: dropwizard-dbdeploy-master File: ClasspathResourceScanner.java View source code |
public static Collection<String> scan(final String path) {
Reflections reflections = new //
Reflections(//
new ConfigurationBuilder().setScanners(//
new ResourcesScanner()).setUrls(ClasspathHelper.forPackage(path)));
Map<String, Multimap<String, String>> store = reflections.getStore().getStoreMap();
Preconditions.checkArgument(store.size() == 1, "Stores should just have one key");
Multimap<String, String> foundResouces = store.values().iterator().next();
return Collections2.filter(foundResouces.values(), new Predicate<String>() {
@Override
public boolean apply(String input) {
return input.startsWith(path);
}
});
}Example 74
| Project: dumpling-master File: CliCommandOptionHandler.java View source code |
/*package*/
@Nonnull
static Set<? extends CliCommand> getAllHandlers() {
Reflections reflections = new Reflections("com.github.olivergondza.dumpling");
final Set<Class<? extends CliCommand>> types = reflections.getSubTypesOf(CliCommand.class);
final Set<CliCommand> handlers = new HashSet<CliCommand>();
for (Class<? extends CliCommand> type : types) {
try {
handlers.add(type.newInstance());
} catch (InstantiationException ex) {
AssertionError e = new AssertionError("Cli command " + type.getName() + " does not declare default contructor");
e.initCause(ex);
throw e;
} catch (IllegalAccessException ex) {
AssertionError e = new AssertionError("Cli command " + type.getName() + " does not declare default contructor");
e.initCause(ex);
throw e;
}
}
return handlers;
}Example 75
| Project: eadventure-master File: SetGetTest.java View source code |
@Test
public void testSetGest() {
Reflections reflections = new Reflections("es.eucm.ead.model");
for (Class<?> c : reflections.getSubTypesOf(Identified.class)) {
for (Field f : getFields(c, withAnnotation(Param.class))) {
String input = f.getName();
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Set<Method> s = getMethods(c, withName("get" + output), withParametersCount(0));
Set<Method> s2 = getMethods(c, withName("is" + output), withParametersCount(0));
if (s.size() != 1 && s2.size() != 1) {
fail("No get method for field " + f.getName() + " in class " + c);
}
s = getMethods(c, withName("set" + output), withParameters(f.getType()));
if (s.size() != 1) {
fail("No set method for field " + f.getName() + " in class " + c);
}
}
}
}Example 76
| Project: effektif-master File: TestSuiteHelper.java View source code |
public static Class<?>[] scanTestClasses() {
Reflections reflections = new Reflections("com.effektif.workflow.test.api");
Set<Class<? extends WorkflowTest>> resources = reflections.getSubTypesOf(WorkflowTest.class);
Class<?>[] testClasses = new Class<?>[resources.size()];
Iterator<Class<? extends WorkflowTest>> iterator = resources.iterator();
int i = 0;
while (iterator.hasNext()) {
testClasses[i] = iterator.next();
i++;
}
return testClasses;
}Example 77
| Project: EventHub-master File: Module.java View source code |
@Provides
private EventHubHandler getEventHubHandler(Injector injector, EventHub eventHub) throws ClassNotFoundException {
Map<String, Provider<Command>> commandsMap = Maps.newHashMap();
Reflections reflections = new Reflections(PACKAGE_NAME);
Set<Class<? extends Command>> commandClasses = reflections.getSubTypesOf(Command.class);
for (Class<? extends Command> commandClass : commandClasses) {
String path = commandClass.getAnnotation(Path.class).value();
//noinspection unchecked
commandsMap.put(path, (Provider<Command>) injector.getProvider(commandClass));
}
return new EventHubHandler(eventHub, commandsMap);
}Example 78
| Project: generator-master File: GenerateTestSourceFiles.java View source code |
private void gatherGenerators(List<CompilationUnitGenerator> generators) throws InstantiationException, IllegalAccessException {
Reflections reflections = new Reflections("mbg.domtest.generators");
Set<Class<? extends CompilationUnitGenerator>> classes = reflections.getSubTypesOf(CompilationUnitGenerator.class);
for (Class<? extends CompilationUnitGenerator> clazz : classes) {
if (clazz.getAnnotation(IgnoreDomTest.class) == null) {
generators.add(clazz.newInstance());
} else {
System.out.println("Generator " + clazz.getName() + " ignored");
}
}
}Example 79
| Project: Glydar-master File: CubeWorldPacket.java View source code |
private static void __addPacketsFromPackage(String pkg) {
Reflections refPackage = new Reflections(pkg);
Set<Class<? extends CubeWorldPacket>> clientPackets = refPackage.getSubTypesOf(CubeWorldPacket.class);
for (Class<? extends CubeWorldPacket> c : clientPackets) {
try {
Annotation a = c.getAnnotation(CubeWorldPacket.Packet.class);
if (a == null)
continue;
int classID = ((CubeWorldPacket.Packet) a).id();
CUBE_WORLD_PACKET_HASH_MAP.put(classID, c.getConstructor());
} catch (Exception e) {
e.printStackTrace();
}
}
}Example 80
| Project: hotwind-master File: ClassUtils.java View source code |
/** íŠ¹ì • 패키지 ì?´í•˜ì?˜, íŠ¹ì • 어노테ì?´ì…˜ ì§€ì •ë?œ í?´ëž˜ìŠ¤ë“¤ 찾기. */
public static Set<Class<?>> findAnnotatedClasses(final String rootPackage, final Class<? extends Annotation> klassAnnotation) {
Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(ClasspathHelper.forPackage(rootPackage)).setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner()));
Set<Class<?>> annotatedKlasses = reflections.getTypesAnnotatedWith(klassAnnotation);
logger.info(ObjectUtils.toString(annotatedKlasses));
return annotatedKlasses;
}Example 81
| Project: incubator-streams-master File: ActivitySerDeTest.java View source code |
/**
* Tests that defined activity verbs have an example which can be loaded into
* Activity beans and into verb-specific beans.
* @throws Exception Exception
*/
@Test
public void testVerbSerDe() throws Exception {
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.apache.streams.pojo.json")).setScanners(new SubTypesScanner()));
Set<Class<? extends Activity>> verbs = reflections.getSubTypesOf(Activity.class);
for (Class verbClass : verbs) {
LOGGER.info("Verb: " + verbClass.getSimpleName());
Activity activity = (Activity) verbClass.newInstance();
String verbName = activity.getVerb();
String testfile = verbName.toLowerCase() + ".json";
LOGGER.info("Serializing: activities/" + testfile);
assert (ActivitySerDeTest.class.getClassLoader().getResource("activities/" + testfile) != null);
InputStream testActivityFileStream = ActivitySerDeTest.class.getClassLoader().getResourceAsStream("activities/" + testfile);
assert (testActivityFileStream != null);
activity = MAPPER.convertValue(MAPPER.readValue(testActivityFileStream, verbClass), Activity.class);
String activityString = MAPPER.writeValueAsString(activity);
LOGGER.info("Deserialized: " + activityString);
assert (!activityString.contains("null"));
assert (!activityString.contains("[]"));
}
}Example 82
| Project: iris-master File: ReflectionsTest.java View source code |
@Test
public void testReflectionsOnSpecificPackage() throws MalformedURLException {
// enforce loading class with current classloader
AnnotatedInteractionCmdStubImpl1 object = new AnnotatedInteractionCmdStubImpl1();
File jarFile = new File("src/test/jars/AnnotatedTestInteractionCommandClasses.jar");
ClassLoader classloader = new ParentLastURLClassloader(new URL[] { jarFile.toURI().toURL() }, Thread.currentThread().getContextClassLoader());
Reflections r = new Reflections(new ConfigurationBuilder().setUrls(jarFile.toURI().toURL()).addClassLoader(classloader));
Set<Class<?>> annotated = r.getTypesAnnotatedWith(InteractionCommandImpl.class);
// we knew 3 classes with given annotation was in a jar we prepared
Assert.assertEquals("The number of classes detected is different than expected", 3, annotated.size());
for (Class cls : annotated) {
// for every class chack if it was really loaded with the classloader we wanted
// AnnotatedClass1 - in case of classloading method being faulty would be from parent!
Assert.assertEquals("Classloader used to load class different than expected, delegation model failed!", cls.getClassLoader(), classloader);
}
}Example 83
| Project: isis-master File: ClassDiscoveryServiceUsingReflections.java View source code |
@Programmatic
@Override
public <T> Set<Class<? extends T>> findSubTypesOfClasses(Class<T> type, String packagePrefix) {
if (type == FixtureScript.class) {
Set fixtureScriptTypes = AppManifest.Registry.instance().getFixtureScriptTypes();
if (fixtureScriptTypes != null) {
return fixtureScriptTypes;
}
}
// no appManifest or not asking for FixtureScripts
Vfs.setDefaultURLTypes(getUrlTypes());
final Reflections reflections = new Reflections(ClasspathHelper.forClassLoader(Thread.currentThread().getContextClassLoader()), ClasspathHelper.forClass(Object.class), ClasspathHelper.forPackage(packagePrefix), new SubTypesScanner(false));
return reflections.getSubTypesOf(type);
}Example 84
| Project: java-concurrency-torture-master File: ForkedMain.java View source code |
private static <T> SortedSet<Class<? extends T>> filterTests(final String filter, Class<T> klass) {
// God I miss both diamonds and lambdas here.
Pattern pattern = Pattern.compile(filter);
Reflections r = new Reflections(new ConfigurationBuilder().filterInputsBy(new FilterBuilder().include("net.shipilev.concurrent.torture.*")).setUrls(ClasspathHelper.forClassLoader()).setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));
SortedSet<Class<? extends T>> s = new TreeSet<Class<? extends T>>(new Comparator<Class<? extends T>>() {
@Override
public int compare(Class<? extends T> o1, Class<? extends T> o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (Class<? extends T> k : r.getSubTypesOf(klass)) {
if (!pattern.matcher(k.getName()).matches()) {
continue;
}
if (Modifier.isAbstract(k.getModifiers())) {
continue;
}
s.add(k);
}
return s;
}Example 85
| Project: java-sproc-wrapper-master File: GlobalValueTransformerLoader.java View source code |
public static synchronized ValueTransformer<?, ?> getValueTransformerForClass(final Class<?> genericType) throws InstantiationException, IllegalAccessException {
// did we already scanned the classpath for global value transformers?
if (scannedClasspath == false) {
final Predicate<String> filter = new Predicate<String>() {
@Override
public boolean apply(final String input) {
return GlobalValueTransformer.class.getCanonicalName().equals(input);
}
};
// last to get the namespace from the system environment
String myNameSpaceToScan = null;
try {
myNameSpaceToScan = System.getenv(GLOBAL_VALUE_TRANSFORMER_SEARCH_NAMESPACE);
} catch (final Exception e) {
}
if (Strings.isNullOrEmpty(myNameSpaceToScan)) {
// last to use the given namespace
myNameSpaceToScan = namespaceToScan;
}
if (!Strings.isNullOrEmpty(myNameSpaceToScan)) {
final Reflections reflections = new Reflections(new ConfigurationBuilder().filterInputsBy(new FilterBuilder.Include(FilterBuilder.prefix(myNameSpaceToScan))).setUrls(ClasspathHelper.forPackage(myNameSpaceToScan)).setScanners(new TypeAnnotationsScanner().filterResultsBy(filter), new SubTypesScanner()));
final Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(GlobalValueTransformer.class);
for (final Class<?> foundGlobalValueTransformer : typesAnnotatedWith) {
final Class<?> valueTransformerReturnType = ValueTransformerUtils.getUnmarshalFromDbClass(foundGlobalValueTransformer);
if (valueTransformerReturnType != null) {
GlobalValueTransformerRegistry.register(valueTransformerReturnType, (ValueTransformer<?, ?>) foundGlobalValueTransformer.newInstance());
LOG.debug("Global Value Transformer [{}] for type [{}] registered. ", foundGlobalValueTransformer.getSimpleName(), valueTransformerReturnType.getSimpleName());
} else {
LOG.error("Could add global transformer [{}] to global registry. Could not find method unmarshalFromDb.", foundGlobalValueTransformer);
}
}
}
scannedClasspath = true;
}
return GlobalValueTransformerRegistry.getValueTransformerForClass(genericType);
}Example 86
| Project: jbehave-core-master File: ScanningStepsFactory.java View source code |
private Set<Class<?>> scanTypes(String packageName) {
Reflections reflections = new Reflections(packageName, new MethodAnnotationsScanner());
Set<Class<?>> types = new HashSet<Class<?>>();
types.addAll(typesAnnotatedWith(reflections, Given.class));
types.addAll(typesAnnotatedWith(reflections, When.class));
types.addAll(typesAnnotatedWith(reflections, Then.class));
types.addAll(typesAnnotatedWith(reflections, Before.class));
types.addAll(typesAnnotatedWith(reflections, After.class));
types.addAll(typesAnnotatedWith(reflections, BeforeScenario.class));
types.addAll(typesAnnotatedWith(reflections, AfterScenario.class));
types.addAll(typesAnnotatedWith(reflections, BeforeStory.class));
types.addAll(typesAnnotatedWith(reflections, AfterStory.class));
types.addAll(typesAnnotatedWith(reflections, BeforeStories.class));
types.addAll(typesAnnotatedWith(reflections, AfterStories.class));
return types;
}Example 87
| Project: jetstream-esper-master File: AnnotationConfigLoader.java View source code |
private Map<Class<?>, AnnotationProcessor> loadProcessors() {
Reflections reflections = new Reflections(processor_package);
Set<Class<? extends AnnotationProcessor>> proc_classes = reflections.getSubTypesOf(AnnotationProcessor.class);
Map<Class<?>, AnnotationProcessor> procMap = new HashMap<Class<?>, AnnotationProcessor>();
for (Class<?> procClass : proc_classes) {
try {
Class<?>[] clzargs = null;
Method m = procClass.getDeclaredMethod("getAnnotationClass", clzargs);
AnnotationProcessor processor = (AnnotationProcessor) procClass.newInstance();
Object[] objargs = null;
Class<?> clz = (Class<?>) m.invoke(processor, objargs);
if (clz != null)
procMap.put(clz, processor);
} catch (Throwable t) {
t.printStackTrace();
}
}
return procMap;
}Example 88
| Project: jggapi-master File: PacketChain.java View source code |
protected final void registerDefaultHandlers() throws GGException {
final Configuration configuration = new ConfigurationBuilder().setScanners(new TypeAnnotationsScanner()).setUrls(ClasspathHelper.getUrlsForPackagePrefix("pl.radical.open.gg.packet.in"));
final Reflections reflections = new Reflections(configuration);
final Set<Class<?>> classes = reflections.getTypesAnnotatedWith(IncomingPacket.class);
if (classes.isEmpty()) {
throw new GGException("No classes found to register as packet handlers!");
}
for (final Class<?> c : classes) {
final IncomingPacket annotation = c.getAnnotation(IncomingPacket.class);
if (LOG.isTraceEnabled()) {
LOG.trace("Registering class {} with handler {} for packet [{}]", ClassUtils.getShortClassName(c.getName()), ClassUtils.getShortClassName(annotation.handler().getName()), Integer.toString(c.getAnnotation(IncomingPacket.class).type()));
}
registerGGPackageHandler(annotation.type(), annotation.handler());
}
}Example 89
| Project: josm-master File: TableCellRendererTest.java View source code |
/**
* Unit test of all table cell renderers against null values.
* @throws NoSuchMethodException no default constructor - to fix this, add a default constructor to the class
* or add the class to the SKIP_TEST list above
* @throws ReflectiveOperationException if an error occurs
*/
@Test
public void testTableCellRenderer() throws ReflectiveOperationException {
Reflections reflections = new Reflections("org.openstreetmap.josm");
Set<Class<? extends TableCellRenderer>> renderers = reflections.getSubTypesOf(TableCellRenderer.class);
// if it finds less than 10 classes, something is broken
Assert.assertTrue(renderers.size() >= 10);
JTable tbl = new JTable(2, 2);
for (Class<? extends TableCellRenderer> klass : renderers) {
if (Modifier.isAbstract(klass.getModifiers()) || SKIP_TEST.contains(klass.getName())) {
continue;
}
if (klass.isAnonymousClass()) {
continue;
}
assertNotNull(createInstance(klass).getTableCellRendererComponent(tbl, null, false, false, 0, 0));
}
}Example 90
| Project: jskat-multimodule-master File: JSkatPlayerResolver.java View source code |
private static Set<String> getAllImplementations() {
Set<String> result = new HashSet<String>();
Reflections reflections = new Reflections("org.jskat");
Set<Class<? extends AbstractJSkatPlayer>> subTypes = reflections.getSubTypesOf(AbstractJSkatPlayer.class);
for (Class<? extends AbstractJSkatPlayer> jskatPlayer : subTypes) {
if (isNotAbstract(jskatPlayer) && isNotHumanPlayer(jskatPlayer)) {
result.add(jskatPlayer.getName());
}
}
return result;
}Example 91
| Project: khs-sherpa-master File: RestfulRequestProcessor.java View source code |
public String getEndpoint(HttpServletRequest request) {
Map<String, Object> map = applicationContext.getEndpointTypes();
Collection<Method> methods = new HashSet<Method>();
for (Entry<String, Object> entry : map.entrySet()) {
Collection<Method> m = Reflections.getAllMethods(entry.getValue().getClass(), Predicates.and(ReflectionUtils.withAnnotation(Action.class), SherpaPredicates.withActionMappingPattern(UrlUtil.getPath(request))));
methods.addAll(m);
}
method = MethodUtil.validateHttpMethods(methods.toArray(new Method[] {}), request.getMethod());
if (method != null) {
Class<?> type = method.getDeclaringClass();
if (type.isAnnotationPresent(Endpoint.class)) {
if (StringUtils.isNotEmpty(type.getAnnotation(Endpoint.class).value())) {
return type.getAnnotation(Endpoint.class).value();
}
}
return type.getSimpleName();
}
throw new SherpaEndpointNotFoundException("no endpoint for url [" + UrlUtil.getPath(request) + "]");
}Example 92
| Project: kiji-table-layout-updater-master File: ResourceUpdateLoader.java View source code |
/**
* This method assumes that the DDL updates are located in the classpath
* under the folder defined by {@link #packagePrefix} The updates files must respect the
* pattern returned by {@link #buildUpdateFilePattern(String)}.
*
* @param tableName The name of the table to load updates for.
* @return The table updates.
* @throws java.io.IOException If an I/O error occurs
* @throws TableUpdatesNotFoundException If updates for the given tables are not found.
*/
@Override
public SortedSet<Update> loadUpdates(String tableName) throws IOException, TableUpdatesNotFoundException {
Reflections reflections = new Reflections(packagePrefix + tableName, new ResourcesScanner());
Set<String> resources = reflections.getResources(Pattern.compile(buildUpdateFilePattern(tableName)));
if (resources.isEmpty()) {
throw new TableUpdatesNotFoundException(tableName);
}
SortedSet<Update> updates = new TreeSet<Update>(Update.UPDATE_COMPARATOR);
for (String resource : resources) {
int id = extractIdFromFileName(new File(resource).getName());
BufferedReader reader = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream(resource)));
String line;
StringBuilder ddl = new StringBuilder();
while ((line = reader.readLine()) != null) {
ddl.append(line).append("\n");
}
updates.add(new Update(id, ddl.toString()));
}
return updates;
}Example 93
| Project: knorxx-master File: KnorxxScriptExporter.java View source code |
private <T> T getSingleton(Class<T> javaClass, Reflections reflections) {
Set<Class<? extends T>> subClasses = reflections.getSubTypesOf(javaClass);
int allowedResultCount = 1;
T instance = null;
for (Class<? extends T> subClass : subClasses) {
if (!(subClass.equals(javaClass) || subClass.equals(knorxx.framework.generator.web.server.json.GsonHelper.class))) {
try {
instance = subClass.getConstructor().newInstance();
} catch (NoSuchMethodExceptionSecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | ex) {
throw new IllegalStateException(ex);
}
} else {
allowedResultCount++;
}
}
if (subClasses.size() != allowedResultCount) {
throw new IllegalStateException("Can't instantiate a singleton of '" + javaClass.getName() + "' because the following subclasses were found on the classpath: " + Joiner.on(", ").join(subClasses));
}
return instance;
}Example 94
| Project: krail-master File: OptionKeyLocator.java View source code |
/**
* Scans the entire application by reflection for instance of {@link OptionKey} and returns a Set of data types they use. Only works with static fields,
* as {@link OptionContext} implementations are not instantiated (but there is no reason not to use static fields for Option keys
*
* @return Set of data types used by {@link OptionKey}
*/
public Set<Class<?>> contextKeyTypes() {
Reflections reflections = new Reflections();
Set<Class<? extends OptionContext>> contexts = reflections.getSubTypesOf(OptionContext.class);
Set<Class<?>> keyTypes = new HashSet<>();
for (Class<? extends OptionContext> contextClass : contexts) {
Set<Field> contextFields = ReflectionUtils.getAllFields(contextClass, p -> p.getType().equals(OptionKey.class));
for (Field contextField : contextFields) {
try {
contextField.setAccessible(true);
final OptionKey key = (OptionKey) contextField.get(null);
Object defaultValue = key.getDefaultValue();
if (defaultValue instanceof I18NKey) {
keyTypes.add(I18NKey.class);
} else if (defaultValue.getClass().isEnum()) {
keyTypes.add(Enum.class);
} else {
keyTypes.add(defaultValue.getClass());
}
} catch (IllegalAccessExceptionNullPointerException | e) {
log.warn("unable to read field {}", contextField.getName());
}
}
}
return keyTypes;
}Example 95
| Project: kylo-master File: ServiceLevelAgreementActionConfigTransformer.java View source code |
public List<ServiceLevelAgreementActionUiConfigurationItem> discoverActionConfigurations() {
List<ServiceLevelAgreementActionUiConfigurationItem> rules = new ArrayList<>();
Set<Class<?>> items = new Reflections("com.thinkbiganalytics").getTypesAnnotatedWith(ServiceLevelAgreementActionConfig.class);
for (Class c : items) {
List<FieldRuleProperty> properties = getUiProperties(c);
ServiceLevelAgreementActionConfig policy = (ServiceLevelAgreementActionConfig) c.getAnnotation(ServiceLevelAgreementActionConfig.class);
ServiceLevelAgreementActionUiConfigurationItem configItem = buildUiModel(policy, c, properties);
rules.add(configItem);
}
return rules;
}Example 96
| Project: mybatis-generator-master File: GenerateTestSourceFiles.java View source code |
private void gatherGenerators(List<CompilationUnitGenerator> generators) throws InstantiationException, IllegalAccessException {
Reflections reflections = new Reflections("mbg.domtest.generators");
Set<Class<? extends CompilationUnitGenerator>> classes = reflections.getSubTypesOf(CompilationUnitGenerator.class);
for (Class<? extends CompilationUnitGenerator> clazz : classes) {
if (clazz.getAnnotation(IgnoreDomTest.class) == null) {
generators.add(clazz.newInstance());
} else {
System.out.println("Generator " + clazz.getName() + " ignored");
}
}
}Example 97
| Project: openiot-master File: GraphNodeScanner.java View source code |
public static Set<Class<?>> detectGraphNodeClasses(String rootPackage) {
try {
Reflections reflections = new Reflections(rootPackage);
Set<Class<?>> detectedClasses = reflections.getTypesAnnotatedWith(GraphNodeClass.class);
Iterator<Class<?>> setIt = detectedClasses.iterator();
while (setIt.hasNext()) {
GraphNodeClass annotation = setIt.next().getAnnotation(GraphNodeClass.class);
if (annotation.hideFromScanner()) {
setIt.remove();
}
}
return detectedClasses;
} catch (Exception ex) {
LoggerService.log(ex);
}
return null;
}Example 98
| Project: overtown-master File: PackageScanner.java View source code |
protected ScannerResult scanPackage(String packageToSearch) throws PackageNotFoundException, IOException {
Reflections reflections = new Reflections(packageToSearch);
Set<Class<?>> controllers = reflections.getTypesAnnotatedWith(Controller.class);
Set<Class<?>> serverEndpoints = reflections.getTypesAnnotatedWith(ServerEndpoint.class);
Set<Class<?>> sessionListeners = reflections.getTypesAnnotatedWith(SessionListener.class);
Set<Class<? extends HttpServlet>> servlets = reflections.getSubTypesOf(HttpServlet.class);
ScannerResult scannerResult = new ScannerResult();
scannerResult = mapControllers(scannerResult, filtrateClasses(controllers));
for (Class<?> c : filtrateClasses(serverEndpoints)) {
scannerResult.addServerEndpointClass(c);
}
for (Class<?> c : filtrateClasses(sessionListeners)) {
scannerResult.addSessionListener(c);
}
for (Class c : filtrateClasses(servlets)) {
scannerResult.addServletClass(c);
}
scannerResult.setNotFoundClass(findErrorHandler(NotFound.class, reflections));
scannerResult.setMethodNotAllowedClass(findErrorHandler(MethodNotAllowed.class, reflections));
scannerResult.setInternalErrorClass(findErrorHandler(InternalError.class, reflections));
return scannerResult;
}Example 99
| Project: querydsl-master File: SerializationTest.java View source code |
@Test
public void expressions() throws Exception {
Map<Class<?>, Object> args = Maps.newHashMap();
args.put(Object.class, "obj");
args.put(BeanPath.class, new EntityPathBase<Object>(Object.class, "obj"));
args.put(Class.class, Integer.class);
args.put(Class[].class, new Class<?>[] { Object.class, Object.class });
args.put(java.util.Date.class, new java.util.Date(0));
args.put(java.sql.Date.class, new java.sql.Date(0));
args.put(java.sql.Time.class, new java.sql.Time(0));
args.put(java.sql.Timestamp.class, new java.sql.Timestamp(0));
args.put(Expression.class, Expressions.enumPath(Gender.class, "e"));
args.put(Expression[].class, new Expression<?>[] { Expressions.enumPath(Gender.class, "e"), Expressions.stringPath("s") });
args.put(FactoryExpression.class, Projections.tuple(Expressions.stringPath("str")));
args.put(GroupExpression.class, GroupBy.avg(Expressions.numberPath(Integer.class, "num")));
args.put(Number.class, 1);
args.put(Operator.class, Ops.AND);
args.put(Path.class, Expressions.stringPath("str"));
args.put(PathBuilderValidator.class, PathBuilderValidator.DEFAULT);
args.put(PathMetadata.class, PathMetadataFactory.forVariable("obj"));
args.put(PathInits.class, PathInits.DEFAULT);
args.put(Predicate.class, Expressions.path(Object.class, "obj").isNull());
args.put(QueryMetadata.class, new DefaultQueryMetadata());
args.put(String.class, "obj");
Reflections reflections = new Reflections();
Set<Class<? extends Expression>> types = reflections.getSubTypesOf(Expression.class);
for (Class<?> type : types) {
if (!type.isInterface() && !type.isMemberClass() && !Modifier.isAbstract(type.getModifiers())) {
for (Constructor<?> c : type.getConstructors()) {
Object[] parameters = new Object[c.getParameterTypes().length];
for (int i = 0; i < c.getParameterTypes().length; i++) {
parameters[i] = Objects.requireNonNull(args.get(c.getParameterTypes()[i]), c.getParameterTypes()[i].getName());
}
c.setAccessible(true);
Object o = c.newInstance(parameters);
assertEquals(o, Serialization.serialize(o));
}
}
}
}Example 100
| Project: SimpleServer-master File: LegacyTagResolver.java View source code |
private void loadTags() throws SAXException {
Reflections r = new Reflections("simpleserver", new SubTypesScanner());
Set<Class<? extends TagConverter>> classes = r.getSubTypesOf(TagConverter.class);
for (Class<? extends TagConverter> tag : classes) {
if (Modifier.isAbstract(tag.getModifiers())) {
continue;
}
TagConverter instance;
try {
instance = tag.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new SAXException("Unable to load tag \"" + tag.getSimpleName() + "\" (after " + tags.size() + " tags)");
}
tags.put(instance.tag, instance);
}
}Example 101
| Project: swagger-katharsis-master File: ResourceRegistryTest.java View source code |
@Before
public void before() throws Exception {
ResourceRegistryBuilder registryBuilder = new ResourceRegistryBuilder(new SampleJsonServiceLocator(), new ResourceInformationBuilder(RESOURCE_FIELD_NAME_TRANSFORMER));
resourceRegistry = registryBuilder.build(RESOURCE_SEARCH_PACKAGE, RESOURCE_DEFAULT_DOMAIN);
Reflections reflections = new Reflections(RESOURCE_SEARCH_PACKAGE);
jsonApiResources = reflections.getTypesAnnotatedWith(JsonApiResource.class);
}