Java Code Examples for org.reflections.Reflections#getTypesAnnotatedWith()

The following examples show how to use org.reflections.Reflections#getTypesAnnotatedWith() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NavigatorPlugin.java    From navigator-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Currently this is unsupported. Instead, a generic custom entity is
 * being used by Navigator.
 *
 * Search for classes defined using the @MClass annotation
 * in the given package. Registers all found classes with Navigator
 * @param packageName
 */
@SuppressWarnings("unchecked")
public MetadataModel registerModels(String packageName) {
  Reflections ref = new Reflections(packageName + ".");
  Set<Class<?>> types = ref.getTypesAnnotatedWith(MClass.class);
  Collection<Class<Entity>> modelClasses = Lists.newArrayListWithExpectedSize(
      types.size() + 1);
  for (Class<?> aClass : types) {
    Preconditions.checkArgument(Entity.class.isAssignableFrom(aClass));
    modelClasses.add((Class<Entity>)aClass);
  }
  if (modelClasses.size() > 0) {
    LOG.info("Registering models: {}", modelClasses);
    return registerModels(modelClasses);
  } else {
    LOG.info("No models to be registered in package {}", packageName);
    return null;
  }
}
 
Example 2
Source File: RoleClassLoader.java    From anno4j with Apache License 2.0 6 votes vote down vote up
private void scanConceptsWithReflections() throws ObjectStoreConfigException {
    logger.debug("Search for concepts with reflections");
    Set<URL> classpath = new HashSet<>();
    classpath.addAll(ClasspathHelper.forClassLoader());
    classpath.addAll(ClasspathHelper.forJavaClassPath());
    classpath.addAll(ClasspathHelper.forManifest());
    classpath.addAll(ClasspathHelper.forPackage(""));
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(classpath)
.useParallelExecutor()
.filterInputsBy(FilterBuilder.parsePackages("-java, -javax, -sun, -com.sun"))
            .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));

    Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Iri.class, true);
    logger.debug("Search for concepts with reflections resulted in " + annotated.size() + " classes");
    for (Class clazz : annotated) {
        logger.debug("Found concept class: " + clazz.getCanonicalName());
        roleMapper.addConcept(clazz);
    }
}
 
Example 3
Source File: DownloaderAOPFactory.java    From gecco with MIT License 6 votes vote down vote up
public DownloaderAOPFactory(Reflections reflections) {
	this.beforeDownloads = new HashMap<String, BeforeDownload>();
	this.afterDownloads = new HashMap<String, AfterDownload>();
	Set<Class<?>> classes = reflections.getTypesAnnotatedWith(GeccoClass.class);
	for(Class<?> aopClass : classes) {
		GeccoClass geccoClass = (GeccoClass)aopClass.getAnnotation(GeccoClass.class);
		try {
			Class<?>[] geccoClasses = geccoClass.value();
			for(Class<?> c : geccoClasses) {
				String name = c.getName();
				Object o = aopClass.newInstance();
				if(o instanceof BeforeDownload) {
					beforeDownloads.put(name, (BeforeDownload)o);
				} else if(o instanceof AfterDownload) {
					afterDownloads.put(name, (AfterDownload)o);
				}
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}
 
Example 4
Source File: PluginUtils.java    From mjprof with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 5
Source File: SecurityManager.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
private Decryptor findDecrypt(String algorithm) {

        Reflections reflections = new Reflections("ltd.beihu");

        Set<Class<?>> decryptSupportClses = reflections.getTypesAnnotatedWith(DecryptSupport.class);
        for (Class<?> decryptSupportCls : decryptSupportClses) {
            DecryptSupport decryptSupport = AnnotationUtils.findAnnotation(decryptSupportCls, DecryptSupport.class);
            String[] algorithms = decryptSupport.value();
            if (!findAlgorithm(algorithms, algorithm)) {
                continue;
            }


            Set<? extends Class<?>> supertypes = TypeToken.of(decryptSupportCls).getTypes().rawTypes();
            for (Class<?> supertype : supertypes) {
                for (Method method : supertype.getDeclaredMethods()) {
                    if (Objects.equals(decryptMethod, method.getName()) && !method.isSynthetic()) {
                        if (method.getParameterCount() < 1) {
                            logger.warn("Method {} named encrypt but has no parameters.Encrypt methods must have at least 1 parameter",
                                    ReflectionHelper.buildKey(supertype, method));
                            continue;
                        }
                        Object bean = Modifier.isStatic(method.getModifiers()) ? null : beanCache.getUnchecked(decryptSupportCls);
                        Decryptor decryptor = buildDecryptor(bean, method);
                        for (String algo : algorithms) {
                            decryptorCache.put(algo, decryptor);
                        }
                        return decryptor;
                    }
                }
            }
        }
        missingDecryptorCache.put(algorithm, true);
        throw new IllegalArgumentException("unsupported algorithm:" + algorithm);
    }
 
Example 6
Source File: StaticWeavingTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testStaticWeaving() {
    // first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
    Reflections reflections = new Reflections(getClass().getPackage().getName());
    Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
    Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
    Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);

    // next, let's assert that they have been statically weaved
    assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}
 
Example 7
Source File: CollectionMetaData.java    From jsondb-core with MIT License 5 votes vote down vote up
/**
 * A utility builder method to scan through the specified package and find all classes/POJOs
 * that are annotated with the @Document annotation.
 *
 * @param dbConfig the object that holds all the baseScanPackage and other settings.
 * @return A Map of collection classes/POJOs
 */
public static Map<String, CollectionMetaData> builder(JsonDBConfig dbConfig) {
  Map<String, CollectionMetaData> collectionMetaData = new LinkedHashMap<String, CollectionMetaData>();
  Reflections reflections = new Reflections(dbConfig.getBaseScanPackage());
  Set<Class<?>> docClasses = reflections.getTypesAnnotatedWith(Document.class);
  for (Class<?> c : docClasses) {
    Document d = c.getAnnotation(Document.class);
    String collectionName = d.collection();
    String version = d.schemaVersion();
    CollectionMetaData cmd = new CollectionMetaData(collectionName, c, version, dbConfig.getSchemaComparator());
    collectionMetaData.put(collectionName, cmd);
  }
  return collectionMetaData;
}
 
Example 8
Source File: Civs.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
private void instantiateSingletons() {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    FilterBuilder filterBuilder = new FilterBuilder();
    configurationBuilder.addUrls(ClasspathHelper.forPackage("org.redcastlemedia.multitallented.civs"));
    filterBuilder.includePackage("org.redcastlemedia.multitallented.civs")
            .excludePackage("org.redcastlemedia.multitallented.civs.dynmaphook")
            .excludePackage("org.redcastlemedia.multitallented.civs.placeholderexpansion");
    configurationBuilder.filterInputsBy(filterBuilder);
    Reflections reflections = new Reflections(configurationBuilder);
    Set<Class<?>> classes = reflections.getTypesAnnotatedWith(CivsSingleton.class);
    List<Class<?>> classList = new ArrayList<>(classes);
    classList.sort(new Comparator<Class<?>>() {
        @Override
        public int compare(Class<?> o1, Class<?> o2) {
            return o1.getAnnotation(CivsSingleton.class).priority().compareTo(o2.getAnnotation(CivsSingleton.class).priority());
        }
    });
    for (Class<?> currentSingleton : classList) {
        try {
            Method method = currentSingleton.getMethod("getInstance");
            if (method != null) {
                method.invoke(currentSingleton);
            }
        } catch (Exception e) {

        }
    }
}
 
Example 9
Source File: EbeanEntities.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
public static Set<Class> getEntities() {
    Reflections reflections = new Reflections("bo.gotthardt.model");
    Set<Class<?>> entities = reflections.getTypesAnnotatedWith(Entity.class);
    Set<Class<?>> embeddables = reflections.getTypesAnnotatedWith(Embeddable.class);

    return Sets.union(embeddables, entities);
}
 
Example 10
Source File: CustomFieldRenderFactory.java    From gecco with MIT License 5 votes vote down vote up
public CustomFieldRenderFactory(Reflections reflections) {
	this.map = new HashMap<String, CustomFieldRender>();
	Set<Class<?>> classes = reflections.getTypesAnnotatedWith(FieldRenderName.class);
	for(Class<?> clazz : classes) {
		FieldRenderName fieldRenderName = (FieldRenderName)clazz.getAnnotation(FieldRenderName.class);
		try {
			map.put(fieldRenderName.value(), (CustomFieldRender)clazz.newInstance());
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}
 
Example 11
Source File: StaticWeavingTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testStaticWeaving() {
    // first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
    Reflections reflections = new Reflections(
    		PersistableBusinessObjectBase.class.getPackage().getName());
    Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
    Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
    Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);

    // next, let's assert that they have been statically weaved
    assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}
 
Example 12
Source File: DecisionDiscovery.java    From jdmn with Apache License 2.0 5 votes vote down vote up
public Set<Class<?>> discover(String packagePrefix) {
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage(packagePrefix))
            .filterInputsBy(new FilterBuilder().includePackage(packagePrefix))
    );
    return reflections.getTypesAnnotatedWith(DRGElement.class);
}
 
Example 13
Source File: ConsumerFinder.java    From rpcx-java with Apache License 2.0 5 votes vote down vote up
public Set<String> find(String consumerPackage) {
    Reflections reflections = new Reflections(consumerPackage);
    //不包括实现类
    Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(Consumer.class,true);
    return  classesList.stream().map(it->{
        Consumer consumer = it.getAnnotation(Consumer.class);
        return consumer.impl();
    }).collect(Collectors.toSet());
}
 
Example 14
Source File: StaticWeavingTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testStaticWeaving() {
    // first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
    Reflections reflections = new Reflections(getClass().getPackage().getName());
    Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
    Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
    Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);

    // next, let's assert that they have been statically weaved
    assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}
 
Example 15
Source File: PluginUtils.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Obtain plugin manage
 */
@SuppressWarnings("unchecked")
public static PluginManagerUtil getManager(URI uri) {
	log.debug("getManager({})", uri);
	PluginManager pm = PluginManagerFactory.createPluginManager();
	pm.addPluginsFrom(uri);

	if (EnvironmentDetector.isServerJBoss()) {
		// Look for plugins in com.openkm package
		// Required by JBoss and jspf library bug: OKM-900
		Reflections reflections = new Reflections("com.openkm");
		Set<Class<?>> plugins = reflections.getTypesAnnotatedWith(PluginImplementation.class);

		for (Class<?> plugin : plugins) {
			if (Config.PLUGIN_DEBUG) {
				pm.addPluginsFrom(ClassURI.PLUGIN((Class<? extends Plugin>) plugin), new OptionReportAfter());
			} else {
				pm.addPluginsFrom(ClassURI.PLUGIN((Class<? extends Plugin>) plugin));
			}
		}
	}

	if (Config.PLUGIN_DEBUG) {
		pm.addPluginsFrom(Config.PLUGIN_DIR, new OptionReportAfter());
	} else {
		pm.addPluginsFrom(Config.PLUGIN_DIR);
	}


	return new PluginManagerUtil(pm);
}
 
Example 16
Source File: AnnotationLoader.java    From livingdoc-core with GNU General Public License v3.0 4 votes vote down vote up
private void scanClassPath(ConfigurationBuilder configBuilder) {
    Reflections reflections = new Reflections(configBuilder);
    annotatedFixtureClasses = reflections.getTypesAnnotatedWith(FixtureClass.class);
}
 
Example 17
Source File: HomeScreenController.java    From examples-javafx-repos1 with Apache License 2.0 4 votes vote down vote up
public void initializeSubApps(ClassLoader cl, URL[] urls) throws Exception  {

        if( logger.isDebugEnabled() ) {
            logger.debug("[INIT SUBAPPS]");
        }

        Thread.currentThread().setContextClassLoader( cl );  // used by FXMLLoader
        
        Reflections reflections = new Reflections(DEFAULT_PACKAGE_TO_SCAN, cl, urls);

        Set<Class<?>> subapps = reflections.getTypesAnnotatedWith(SubApp.class);

        subapps.stream().sorted(Comparator.comparing(Class::getSimpleName)).forEach(sa -> {

            SubApp saAnnotation = sa.getAnnotation(SubApp.class);

            Button btn = new Button(saAnnotation.buttonTitle());
            btn.setId( saAnnotation.buttonId() );
            btn.setUserData(sa);  // holds the metadata
            btn.setOnAction(evt -> startScreen(evt));

            vbox.getChildren().add(btn);
        });
    }
 
Example 18
Source File: ReflectionScanStatic.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 扫描基本信息
 */
private ScanStaticModel scanBasicInfo(List<String> packNameList) {

    ScanStaticModel scanModel = new ScanStaticModel();

    //
    // 扫描对象
    //
    Reflections reflections = getReflection(packNameList);
    scanModel.setReflections(reflections);

    //
    // 获取DisconfFile class
    //
    Set<Class<?>> classdata = reflections.getTypesAnnotatedWith(DisconfFile.class);
    scanModel.setDisconfFileClassSet(classdata);

    //
    // 获取DisconfFileItem method
    //
    Set<Method> af1 = reflections.getMethodsAnnotatedWith(DisconfFileItem.class);
    scanModel.setDisconfFileItemMethodSet(af1);

    //
    // 获取DisconfItem method
    //
    af1 = reflections.getMethodsAnnotatedWith(DisconfItem.class);
    scanModel.setDisconfItemMethodSet(af1);

    //
    // 获取DisconfActiveBackupService
    //
    classdata = reflections.getTypesAnnotatedWith(DisconfActiveBackupService.class);
    scanModel.setDisconfActiveBackupServiceClassSet(classdata);

    //
    // 获取DisconfUpdateService
    //
    classdata = reflections.getTypesAnnotatedWith(DisconfUpdateService.class);
    scanModel.setDisconfUpdateService(classdata);

    // update pipeline
    Set<Class<? extends IDisconfUpdatePipeline>> iDisconfUpdatePipeline = reflections.getSubTypesOf
            (IDisconfUpdatePipeline
                    .class);
    if (iDisconfUpdatePipeline != null && iDisconfUpdatePipeline.size() != 0) {
        scanModel.setiDisconfUpdatePipeline((Class<IDisconfUpdatePipeline>) iDisconfUpdatePipeline
                .toArray()[0]);
    }

    return scanModel;
}
 
Example 19
Source File: MainMenu.java    From COMP3204 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Finds the class files that have been annotated with the @Demonstration
 * annotation.
 */
private Set<Class<?>> findDemonstrations() {
	final Reflections reflections = new Reflections(this.getClass().getPackage().getName());
	return reflections.getTypesAnnotatedWith(Demonstration.class);
}
 
Example 20
Source File: Controller.java    From usergrid with Apache License 2.0 4 votes vote down vote up
private void setProject( Project project ) {
    // if the project is null which should never really happen we just return
    // and stay in the INACTIVE state waiting for a load to activate this runner
    if ( project == null ) {
        return;
    }

    // setup the valid runner project
    this.project = project;
    LOG.info( "Controller injected with project properties: {}", project );

    // if the project test package base is null there's nothing we can do but
    // return and stay in the inactive state waiting for a load to occur
    if ( project.getTestPackageBase() == null ) {
        return;
    }

    // reflect into package base looking for annotated classes
    Reflections reflections = new Reflections( project.getTestPackageBase() );

    timeChopClasses = reflections.getTypesAnnotatedWith( TimeChop.class );
    LOG.info( "TimeChop classes = {}", timeChopClasses );

    iterationChopClasses = reflections.getTypesAnnotatedWith( IterationChop.class );
    LOG.info( "IterationChop classes = {}", iterationChopClasses );

    // if we don't have a valid project load key then this is bogus
    if ( project.getLoadKey() == null ) {
        state = State.INACTIVE;
        LOG.info( "Null loadKey: controller going into INACTIVE state." );
        return;
    }


    if ( timeChopClasses.isEmpty() && iterationChopClasses.isEmpty() ) {
        state = State.INACTIVE;
        LOG.info( "Nothing to scan: controller going into INACTIVE state." );
        return;
    }

    state = State.READY;
    LOG.info( "We have things to scan and a valid loadKey: controller going into READY state." );
}