Java Code Examples for org.reflections.Reflections

The following are top voted examples for showing how to use org.reflections.Reflections. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Lukkit   File: EventCallbackGenerator.java   Source Code and License 11 votes vote down vote up
public static void main(String[] args) throws Exception {
    Reflections reflections = new Reflections();
    LukkitPlus.BUKKIT_EVENTS = reflections.getSubTypesOf(Event.class);
    ClassPool classpath = ClassPool.getDefault();
    CtClass eventClass = classpath.makeClass("online.pizzacrust.lukkitplus" +
            ".EventCallback");
    for (Class<? extends Event> event : LukkitPlus.BUKKIT_EVENTS) {
        CtMethod eventMethod = CtNewMethod.make(CtClass.voidType, "on" + event.getSimpleName
                (), new CtClass[] { classpath.get(event.getName()) }, new CtClass[0], "online" +
                ".pizzacrust.lukkitplus.EventCallbackGenerator.call($1);", eventClass);
        eventClass.addMethod(eventMethod);
        AnnotationsAttribute attribute = new AnnotationsAttribute(eventClass.getClassFile()
                .getConstPool(), AnnotationsAttribute.visibleTag);
        Annotation eventHandlerAnnt = new Annotation(EventHandler.class.getName(), eventClass
                .getClassFile().getConstPool());
        attribute.addAnnotation(eventHandlerAnnt);
        eventMethod.getMethodInfo().addAttribute(attribute);
    }
    System.out.println("Done!");
    eventClass.writeFile();
}
 
Example 2
Project: yadi   File: PackageScanModule.java   Source Code and License 9 votes vote down vote up
@SuppressWarnings("unchecked")
private void registerAnnotations() {
    final Reflections reflections = new Reflections(packagePrefix);
    final Set<Class<?>> namedClasses = reflections.getTypesAnnotatedWith(Named.class);
    for (final Class<?> namedClass : namedClasses) {
        final ServiceReference reference = namedClassReference(namedClass);
        final Constructor<?> namedConstructor = constructorFinder.apply(namedClass);
        final ServiceReference<?>[] parameters = stream(namedConstructor.getParameterTypes())
                .map(NamedClassReference::namedClassReference)
                .toArray(ServiceReference<?>[]::new);
        accept(serviceDefinition(
                namedClassReference(namedClass),
                constructor(reference, namedConstructor, parameters),
                postConstructDependencyFinder.apply(namedClass)
        ));
        stream(serviceFromMethodFinder.apply(namedClass)).forEach(this);
    }
}
 
Example 3
Project: outland   File: GuiceApplication.java   Source Code and License 8 votes vote down vote up
protected GuiceApplication(String... basePackages) {
  final ConfigurationBuilder confBuilder = new ConfigurationBuilder();
  final FilterBuilder filterBuilder = new FilterBuilder();

  if (basePackages.length == 0) {
    basePackages = new String[] {};
  }

  logger.info("op=create, auto_scan_packages={}", (Object[]) basePackages);

  for (String pkg : basePackages) {
    confBuilder.addUrls(ClasspathHelper.forPackage(pkg));
    filterBuilder.include(FilterBuilder.prefix(pkg));
  }

  confBuilder.filterInputsBy(filterBuilder)
      .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());

  this.reflections = new Reflections(confBuilder);
}
 
Example 4
Project: travny   File: CustomRecords.java   Source Code and License 7 votes vote down vote up
private static void loadSchemas() {
    Set<String> scan = SchemaScanSettings.SCAN_CLASSPATH;
    Map<Integer, NamedSchema> tmp = Maps.newHashMap();
    for (String pkg : scan) {
        Reflections reflections = new Reflections(pkg);
        Set<Class<? extends CustomRecord>> classes = reflections.getSubTypesOf(CustomRecord.class);
        for (Class<? extends CustomRecord> cls : classes) {
            RecordSchema schema = getSchema(cls);
            if (!schema.isIdSchema() && schema.getType() != Type.ENUM) {
                System.out.println("Found schema " + schema.getName() + " with id " + schema.getShortId());
                tmp.put(schema.getShortId(), schema);
            }
        }
    }
    idToName.putAll(tmp);
}
 
Example 5
Project: loom   File: LoomServiceImpl.java   Source Code and License 7 votes vote down vote up
@Override
@RequestMapping(value = ApiConfig.PROVIDERS_BASE + "/schema", method = RequestMethod.GET,
        headers = ApiConfig.API_HEADERS, produces = {ApiConfig.API_PRODUCES})
@ResponseBody
public String getRelationships(
        @CookieValue(value = SessionManager.SESSION_COOKIE, required = false) final String sessionId,
        final HttpServletResponse response) throws NoSuchProviderException, NoSuchSessionException {
    GenerateSchema drawer = new GenerateSchema();
    List<Class<? extends Item>> items = new ArrayList<>();
    if (rateLimiter.tryAcquire()) {
        Reflections reflections = new Reflections("com");
        Set<Class<? extends Item>> subTypes = reflections.getSubTypesOf(Item.class);
        for (Class<? extends Item> class1 : subTypes) {
            items.add(class1);
        }
    }

    Session session = modelValidator.validateSession(sessionId, response);

    return drawer.process(stitcher, items, session.getProviders().keySet());
}
 
Example 6
Project: hermes-java   File: HermesRegister.java   Source Code and License 7 votes vote down vote up
/**
 * 获取方法映射map
 *
 * @param reflections 反射类列表
 * @return 方法映射map
 */
private Map<String, ServerMethod> getMethodMap(Reflections reflections)
        throws IllegalAccessException, InstantiationException {
    // 获取HermesService注解类
    Set<Class<?>> classes = reflections.getTypesAnnotatedWith(HermesService.class);
    Map<String, ServerMethod> map = new TreeMap<>();
    for (Class<?> c : classes) {
        for (Method method : c.getDeclaredMethods()) {
            Object object = c.newInstance();
            HermesMapping hermesMapping = method.getAnnotation(HermesMapping.class);
            if (hermesMapping != null) {
                map.put(hermesMapping.value(), new ServerMethod(object, method));
            }
        }
    }
    return map;
}
 
Example 7
Project: DMS   File: RouteRegister.java   Source Code and License 7 votes vote down vote up
private void searchRouters(RouteRegister register, String pacakge) {
    Reflections reflections = new Reflections(pacakge);
    Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Route.class);
    for (Class<?> c : annotated) {
        Route annotation = c.getAnnotation(Route.class);
        try {
            if (annotation.method().length > 0)
                register.registerRouter(annotation.method()[0], annotation.path(),
                        (Handler<RoutingContext>) c.newInstance());
            else
                register.registerRouter(annotation.path(), (Handler<RoutingContext>) c.newInstance());
        } catch (InstantiationException | IllegalAccessException | RegisterException e) {
            e.printStackTrace();
        }
    }
}
 
Example 8
Project: Razor   File: ContainerBuilder.java   Source Code and License 7 votes vote down vote up
/**
 * Auto register classes annotated with `Service`
 */
private void autoRegister() {

    Reflections reflections = ReflectKit.getReflections(appClass);

    // scan inject annotated class
    Set<Class<?>> types = reflections.getTypesAnnotatedWith(Service.class);
    types.forEach(this::recursiveRegisterType);

    // cache constructors
    types.forEach(t -> {
        try {

            ConstructorWalker.findInjectConstructor(t);
        } catch (Exception e) {

            log.error(e.getMessage());
        }
    });
}
 
Example 9
Project: oryx2   File: OryxApplication.java   Source Code and License 7 votes vote down vote up
private Set<Class<?>> doGetClasses() {
  String packages =
      servletContext.getInitParameter(OryxApplication.class.getName() + ".packages");
  log.info("Creating JAX-RS from endpoints in package(s) {}", packages);
  Objects.requireNonNull(packages);
  Set<Class<?>> classes = new HashSet<>();
  for (String thePackage : packages.split(",")) {
    Reflections reflections = new Reflections(thePackage);
    classes.addAll(getClassesInPackageAnnotatedBy(thePackage, reflections, Path.class));
    classes.addAll(getClassesInPackageAnnotatedBy(thePackage, reflections, Produces.class));
    classes.addAll(getClassesInPackageAnnotatedBy(thePackage, reflections, Provider.class));
  }
  // Want to configure these globally, but not depend on Jersey, even though it's
  // what will be used in practice by the provided apps.
  for (String optionalJerseyClass : new String[] {
        "org.glassfish.jersey.message.DeflateEncoder",
        "org.glassfish.jersey.message.GZipEncoder",
        "org.glassfish.jersey.server.filter.EncodingFilter"}) {
    if (ClassUtils.classExists(optionalJerseyClass)) {
      classes.add(ClassUtils.loadClass(optionalJerseyClass));
    }
  }
  log.debug("Found JAX-RS resources: {}", classes);
  return classes;
}
 
Example 10
Project: avaire   File: AvaIre.java   Source Code and License 7 votes vote down vote up
private void autoloadPackage(String path, Consumer<Reflectionable> callback) {
    Set<Class<? extends Reflectionable>> types = new Reflections(path).getSubTypesOf(Reflectionable.class);

    Class[] arguments = new Class[1];
    arguments[0] = AvaIre.class;

    for (Class<? extends Reflectionable> reflectionClass : types) {
        if (reflectionClass.getPackage().getName().contains("contracts")) {
            continue;
        }

        try {
            callback.accept(reflectionClass.getDeclaredConstructor(arguments).newInstance(this));
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            getLogger().error("Failed to create a new instance of package {}", reflectionClass.getName(), e);
        }
    }
}
 
Example 11
Project: Lahiya   File: LahiyaTestCaseReport.java   Source Code and License 6 votes vote down vote up
public void generateReport(String packageName,List<String> flagList) throws IOException
{

    URL testClassesURL = Paths.get("target/test-classes").toUri().toURL();

    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{testClassesURL},
            ClasspathHelper.staticClassLoader());

    reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage(packageName,classLoader))
            .addClassLoader(classLoader)
            .filterInputsBy(new FilterBuilder().includePackage(packageName))
            .setScanners(new MethodAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner())
    );


    List<Map<String, TestClass>> list = new ArrayList<>();

    for (String flag : flagList)
    {
        list.add(printMethods(flag));
    }

    Gson gson = new Gson();
    String overviewTemplate = IOUtils.toString(getClass().getResourceAsStream("/index.tpl.html"));


    String editedTemplate = overviewTemplate.replace("##TEST_DATA##", gson.toJson(list));

    FileUtils.writeStringToFile(new File("target/test-list-html-report/index.html"), editedTemplate);
    logger.info("report file generated");
}
 
Example 12
Project: Razor   File: Razor.java   Source Code and License 6 votes vote down vote up
/**
 * Initialize customized implements of some features
 */
private void initImplements() {

    Reflections reflections = ReflectKit.getReflections(appClass);

    // Exception handler
    Set<Class<? extends ExceptionHandler>> exceptionHandlers = reflections.getSubTypesOf(ExceptionHandler.class);
    if (exceptionHandlers.size() > 0) {

        this.exceptionHandler = ioc.resolve(exceptionHandlers.iterator().next());
    }

    // Session manager
    Set<Class<? extends SessionManager>> sessionManagers = reflections.getSubTypesOf(SessionManager.class);
    if (sessionManagers.size() > 0) {

        this.sessionManager = ioc.resolve(sessionManagers.iterator().next());
    }
}
 
Example 13
Project: mq-aliyun   File: OnsImpl.java   Source Code and License 6 votes vote down vote up
public void start() {
    Reflections reflections = new Reflections(packages);
    Set<Class<? extends ConsumerAble>> subTypes = reflections.getSubTypesOf(ConsumerAble.class);
    for(Class<? extends ConsumerAble> consumerAble : subTypes){
        ConsumerAble consumer = ArgumentExtractors.instantiateComponent(beanFactory,consumerAble,null);
        consumer.init(this);
    }
    consumerMap.forEach((cid, consumerId) -> {
        Map<String, Tag> tagMap = consumerId.getTagMap();
        for (Map.Entry<String, Tag> tagEntry : tagMap.entrySet()) {
            Tag tag = tagEntry.getValue();
            Object invokeObj = ArgumentExtractors.instantiateComponent(beanFactory, tag.getInvokeCls(), null);
            tagEntry.getValue().setInvokeObject(invokeObj);
        }

        new ConsumerRun(accessKey, secretKey, suffix, consumerId).start();
    });
}
 
Example 14
Project: FSTestTools   File: FirstSpiritConnectionRule.java   Source Code and License 6 votes vote down vote up
private static void populateMap(final Map<String, FsConnRuleCommand<FsConnRuleCmdParamBean, FsConnRuleCmdResultBean>> commands) {
    final String commandPackage = "com.espirit.moddev.fstesttools.rules.firstspirit.commands";
    LOGGER.info("Scanning class path in '{}' for command classes...", commandPackage);
    Reflections reflections = new Reflections(commandPackage);
    Set<Class<? extends FsConnRuleCommand>> commandsFromPackage = reflections.getSubTypesOf(FsConnRuleCommand.class);

    int counter = 0;
    for (Class<? extends FsConnRuleCommand> commandClass : commandsFromPackage) {
        if (commandClass.isAnonymousClass()) {
            continue;
        }
        LOGGER.debug("Processing '{}'...", commandClass.getSimpleName());
        counter = handleEnumCommands(commands, counter, commandClass);
        counter = handleSimpleCommands(commands, counter, commandClass);
    }
    LOGGER.info("Loaded {} commands!", counter);
}
 
Example 15
Project: soundwave   File: EsMapper.java   Source Code and License 6 votes vote down vote up
/**
 * Get fields for a type. It extracts all JsonProperty fields
 * @param type
 * @return
 */
public static String[] getIncludeFields(Class type) {
  if (!fieldsCache.containsKey(type.getTypeName())) {
    Reflections
        reflections =
        new Reflections(type.getCanonicalName(), new FieldAnnotationsScanner());
    List<String> ret = new ArrayList<>();
    for (Field field : reflections.getFieldsAnnotatedWith(JsonProperty.class)) {
      JsonProperty property = field.getAnnotation(JsonProperty.class);
      ret.add(property.value());
    }

    if (type.getSuperclass() != null) {
      ret.addAll(Arrays.asList(getIncludeFields(type.getSuperclass())));
    }

    fieldsCache.putIfAbsent(type.getTypeName(), ret.toArray(new String[ret.size()]));
  }
  return fieldsCache.get(type.getTypeName());
}
 
Example 16
Project: BaseClient   File: Managers.java   Source Code and License 6 votes vote down vote up
public void load() {
	Reflections reflect = new Reflections(new Object[]{Manager.class});
	Set managers = reflect.getSubTypesOf(Manager.class);
	float progress = 0;
	for (Object obj : managers) {
		Class objClass = (Class)obj;
		try {
			progress += 100.0f / managers.size();
			Manager manager = (Manager)objClass.newInstance();

			this.managers.add(manager);

			ScaledResolution scaledresolution = new ScaledResolution(Minecraft.getMinecraft());
			ProgressBar progressBar = new ProgressBar(scaledresolution.getScaledWidth() / 2, scaledresolution.getScaledHeight() / 2, 100, 10, progress, "Loading Managers " + this.managers.size() + " / " + managers.size(), -1);
			ProgressBarList.addProgress(0, progressBar);

			Thread.sleep(10);
		} catch (Exception e) {;}
	}

	this.managers.sort((o2, o1) -> o2.getLoadLevel() - o1.getLoadLevel());
}
 
Example 17
Project: api.teiler.io   File: EndpointTestResources.java   Source Code and License 6 votes vote down vote up
private static int getAmountOfEndpointTests() {
    Reflections reflections = new Reflections("io.teiler.server.endpoints");
    Set<Class<? extends BaseEndpointControllerTest>> allClasses =
            reflections.getSubTypesOf(BaseEndpointControllerTest.class);
    
    LOGGER.trace("Amount of test classes: " + allClasses.size());
    
    int amountOfTestMethods = 0;
    for (Class<? extends BaseEndpointControllerTest> c : allClasses) {
        for (Method m : c.getDeclaredMethods()) {
            if (m.isAnnotationPresent(Test.class)) {
                amountOfTestMethods++;
            }
        }
    }
    
    LOGGER.trace("Amount of test methods: " + amountOfTestMethods);
    
    return amountOfTestMethods;
}
 
Example 18
Project: Hobbes-v1   File: CommandHandler.java   Source Code and License 6 votes vote down vote up
public CommandHandler() {
  try {
    Set<URL> classPathList = new HashSet<>();
    classPathList.addAll(ClasspathHelper.forJavaClassPath());
    Set<Class<? extends Command>> result = new Reflections(
        new ConfigurationBuilder().setScanners(new SubTypesScanner()).setUrls(classPathList))
        .getSubTypesOf(Command.class);

    for (Class<? extends Command> c : result) {
      String[] categoryString = c.getPackage().toString().split("\\.");
      String category = categoryString[categoryString.length - 1];
      if (category.equalsIgnoreCase("commands")) {
        category = "default";
      }
      Command command = c.newInstance();
      command.getSettings().setCategory(category);
      commands.add(command);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 19
Project: JukeBot   File: EventListener.java   Source Code and License 6 votes vote down vote up
EventListener() {
    final Reflections loader = new Reflections("jukebot.commands");

    Set<Class<?>> discoveredCommands = loader.getTypesAnnotatedWith(CommandProperties.class);
    JukeBot.LOG.info("Discovered " + discoveredCommands.size() + " commands");

    for (Class klass : discoveredCommands) {
        try {
            final Command cmd = (Command) klass.newInstance();

            if (!cmd.properties().enabled())
                continue;

            commands.put(cmd.name().toLowerCase(), cmd);
        } catch (InstantiationException | IllegalAccessException e) {
            JukeBot.LOG.error("An error occurred while creating a new instance of command '" + klass.getName() + "'");
        }
    }
}
 
Example 20
Project: metadata-qa-marc   File: MarcTagLister.java   Source Code and License 6 votes vote down vote up
public static List<Class<? extends DataFieldDefinition>> listTags() {
	Reflections reflections = new Reflections("de.gwdg.metadataqa.marc.definition.tags");

	Set<Class<? extends DataFieldDefinition>> subTypes = reflections.getSubTypesOf(DataFieldDefinition.class);

	Comparator<Class<? extends DataFieldDefinition>> byTag = (e1, e2) ->
		e1.getSimpleName().compareTo(e2.getSimpleName());

	List<Class<? extends DataFieldDefinition>> tags = new ArrayList<>();

	subTypes
		.stream()
		.sorted(byTag)
		.forEach((Class tagClass) -> {
			tags.add(tagClass);
		});

	return tags;
}
 
Example 21
Project: matrix-embedded-federation   File: RouteFinder.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws FileNotFoundException {
    if (args.length != 1) throw new IllegalArgumentException("Missing argument 0: Path to write routes");

    Reflections reflections = new Reflections("io.t2l.matrix.homeserver.federation.transport.http.routes");
    Set<Class<?>> routedClasses = reflections.getTypesAnnotatedWith(Route.class);

    try (PrintWriter writer = new PrintWriter(args[0])) {
        writer.println("# !!!!! This file is automatically generated !!!!!");
        writer.println("# !  Any changes you make may not be saved. Use  !");
        writer.println("# !  `gradle buildRoutes` to change these routes !");
        writer.println("# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        for (Class<?> clazz : routedClasses) {
            String route = clazz.getAnnotation(Route.class).value();
            writer.println("rest." + route + "=" + clazz.getName());
            System.out.println("Writing route " + route + " for class " + clazz.getName());
        }
    }
}
 
Example 22
Project: Shadbot   File: CommandManager.java   Source Code and License 6 votes vote down vote up
public static boolean init() {
	LogUtils.infof("Initializing commands...");

	Reflections reflections = new Reflections(Shadbot.class.getPackage().getName(), new SubTypesScanner(), new TypeAnnotationsScanner());
	for(Class<?> cmdClass : reflections.getTypesAnnotatedWith(Command.class)) {
		if(!AbstractCommand.class.isAssignableFrom(cmdClass)) {
			LogUtils.errorf("An error occurred while generating command, %s cannot be cast to AbstractCommand.", cmdClass.getSimpleName());
			continue;
		}

		try {
			AbstractCommand cmd = (AbstractCommand) cmdClass.newInstance();

			List<String> names = cmd.getNames();
			if(!cmd.getAlias().isEmpty()) {
				names.add(cmd.getAlias());
			}

			for(String name : names) {
				if(COMMANDS_MAP.putIfAbsent(name, cmd) != null) {
					LogUtils.errorf(String.format("Command name collision between %s and %s",
							cmdClass.getSimpleName(), COMMANDS_MAP.get(name).getClass().getSimpleName()));
					continue;
				}
			}
		} catch (InstantiationException | IllegalAccessException err) {
			LogUtils.errorf(err, "An error occurred while initializing command %s.", cmdClass.getDeclaringClass().getSimpleName());
			return false;
		}
	}

	LogUtils.infof("%s initialized.", StringUtils.pluralOf((int) COMMANDS_MAP.values().stream().distinct().count(), "command"));
	return true;
}
 
Example 23
Project: algorithm.annotation   File: AlgorithmServiceImpl.java   Source Code and License 6 votes vote down vote up
public AlgorithmServiceImpl() {
	map = new HashMap<>();
	List<URL> urlList = new ArrayList<>();
	for(String f:System.getProperty("java.class.path").split(":")){
		System.err.println(f);
		try {
			urlList.add(new File(f).toURI().toURL());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	URL[] urls = urlList.toArray(new URL[0]);
	Reflections reflections = new Reflections("jobreading.algorithm.experiment",new MethodAnnotationsScanner(),urls);
	for(Method method : reflections.getMethodsAnnotatedWith(Algorithm.class)){
		final Algorithm my = method.getAnnotation(Algorithm.class);
		Class<?> clazz = method.getDeclaringClass();
		if (null != my) {
			map.put(my.name(), clazz);
		}
	}
}
 
Example 24
Project: kafka-0.11.0.0-src-with-comment   File: DelegatingClassLoader.java   Source Code and License 6 votes vote down vote up
private <T> Collection<PluginDesc<T>> getPluginDesc(
        Reflections reflections,
        Class<T> klass,
        ClassLoader loader
) throws InstantiationException, IllegalAccessException {
    Set<Class<? extends T>> plugins = reflections.getSubTypesOf(klass);

    Collection<PluginDesc<T>> result = new ArrayList<>();
    for (Class<? extends T> plugin : plugins) {
        if (PluginUtils.isConcrete(plugin)) {
            // Temporary workaround until all the plugins are versioned.
            if (Connector.class.isAssignableFrom(plugin)) {
                result.add(
                        new PluginDesc<>(
                                plugin,
                                ((Connector) plugin.newInstance()).version(),
                                loader
                        )
                );
            } else {
                result.add(new PluginDesc<>(plugin, "undefined", loader));
            }
        }
    }
    return result;
}
 
Example 25
Project: satisfy   File: ScanningStepsFactory.java   Source Code and License 6 votes vote down vote up
private Set<Class<?>> scanTypes(String packageName) {
    Reflections reflections = new Reflections(packageName,
            new MethodAnnotationsScanner());
    Set<Class<?>> types = new HashSet<>();
    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));
    types.addAll(typesAnnotatedWith(reflections, AsParameterConverter
            .class));
    return types;
}
 
Example 26
Project: VISNode   File: ProcessLoader.java   Source Code and License 5 votes vote down vote up
/**
 * Loads the processes
 *
 * @return {@code Set<Class<? extends Process>>}
 */
private Set<Class<? extends Process>> loadProcesses() {
    Reflections reflections = new Reflections();
    Set<Class<? extends Process>> classes = reflections.
            getSubTypesOf(Process.class).stream().
            collect(Collectors.toSet());
    classes.add(DynamicPixelProcess.class);
    classes.add(ObjectExtractionProcess.class);
    classes.add(InputProcess.class);
    return Collections.unmodifiableSet(classes);
}
 
Example 27
Project: springboot-shiro-cas-mybatis   File: CasLoggerFactory.java   Source Code and License 5 votes vote down vote up
private Set<Class<? extends ILoggerFactory>> scanContextForLoggerFactories() {
    final Set<Class<? extends ILoggerFactory>> loggerFactories;
    final Collection<URL> set = ClasspathHelper.forPackage(PACKAGE_TO_SCAN);
    final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner()));

    loggerFactories = reflections.getSubTypesOf(ILoggerFactory.class);
    loggerFactories.remove(this.getClass());
    return loggerFactories;
}
 
Example 28
Project: springboot-shiro-cas-mybatis   File: CasLoggerFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Instantiates a new Cas logger factory.
 * Configures the reflection scanning engine to be prepared to scan <code>org.slf4j.impl</code>
 * in order to find other available factories.
 */
public CasLoggerFactory() {
    this.loggerMap = new ConcurrentHashMap<>();
    final Collection<URL> set = ClasspathHelper.forPackage(PACKAGE_TO_SCAN);
    final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner()));

    final Set<Class<? extends ILoggerFactory>> subTypesOf = reflections.getSubTypesOf(ILoggerFactory.class);
    subTypesOf.remove(this.getClass());

    if (subTypesOf.size() > 1) {
        Util.report("Multiple ILoggerFactory bindings are found on the classpath:");
        for (final Class<? extends ILoggerFactory> c : subTypesOf) {
            Util.report("* " + c.getCanonicalName());
        }
    }

    if (subTypesOf.isEmpty()) {
        final RuntimeException e = new RuntimeException("No ILoggerFactory could be found on the classpath."
                + " CAS cannot determine the logging framework."
                + " Examine the project dependencies and ensure that there is one and only one logging framework available.");

        Util.report(e.getMessage(), e);
        throw e;
    }
    this.realLoggerFactoryClass = subTypesOf.iterator().next();
    Util.report("ILoggerFactory to be used for logging is: " + this.realLoggerFactoryClass.getName());
}
 
Example 29
Project: swagger-java-diff-cli   File: RuleParserV1.java   Source Code and License 5 votes vote down vote up
private Map<String, Rule> gatherRules() {
    Map<String, Rule> defaultRules = new HashMap<>();
    Reflections reflections = new Reflections("com.rdavis.swagger.rules.impl");
    Set<Class<? extends RuleV2>> classes = reflections.getSubTypesOf(RuleV2.class);
    for (Class classRule : classes) {
        try {
            RuleV2 rule = (RuleV2) classRule.newInstance();
            defaultRules.put(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, rule.getRuleName()), rule);
        } catch (Exception e) {
            LOGGER.error("Exception occurred creating rule " + classRule, e);
        }
    }
    return defaultRules;
}
 
Example 30
Project: ysoserial-plus   File: ObjectPayload.java   Source Code and License 5 votes vote down vote up
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 31
Project: cas-5.1.0   File: OidcProfileScopeToAttributesFilter.java   Source Code and License 5 votes vote down vote up
public OidcProfileScopeToAttributesFilter(final PrincipalFactory principalFactory,
                                          final ServicesManager servicesManager,
                                          final Collection<BaseOidcScopeAttributeReleasePolicy> userScopes,
                                          final OidcAttributeToScopeClaimMapper attributeToScopeClaimMapper) {
    this.attributeToScopeClaimMapper = attributeToScopeClaimMapper;
    this.filters = new HashMap<>();

    final String packageName = BaseOidcScopeAttributeReleasePolicy.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 BaseOidcScopeAttributeReleasePolicy>> subTypes =
            reflections.getSubTypesOf(BaseOidcScopeAttributeReleasePolicy.class);
    subTypes.forEach(Unchecked.consumer(t -> {
        final BaseOidcScopeAttributeReleasePolicy ex = t.newInstance();
        filters.put(ex.getScopeName(), ex);
    }));

    userScopes.forEach(t -> filters.put(t.getScopeName(), t));

    this.principalFactory = principalFactory;
    this.servicesManager = servicesManager;
    this.userScopes = userScopes;
}
 
Example 32
Project: oryx2   File: OryxApplication.java   Source Code and License 5 votes vote down vote up
private static Collection<Class<?>> getClassesInPackageAnnotatedBy(
    String thePackage,
    Reflections reflections,
    Class<? extends Annotation> annotation) {
  // Filter classes actually in subpackages
  return reflections.getTypesAnnotatedWith(annotation).stream().
      filter(c -> c.getPackage().getName().equals(thePackage)).
      collect(Collectors.toList());
}
 
Example 33
Project: limberest   File: Initializer.java   Source Code and License 5 votes vote down vote up
public void scan(List<String> scanPackages) {
    ExecutionTimer timer = new ExecutionTimer(LogLevel.Info, true);
    for (String scanPackage : scanPackages) {
        logger.debug("Scanning for limberest services in package: {}", scanPackage);
        Reflections reflect = new Reflections(scanPackage);
        // service classes
        for (Class<?> classWithPath : reflect.getTypesAnnotatedWith(Path.class)) {
            logger.info("Found service class: {}", classWithPath.getName());
            Path pathAnnotation = classWithPath.getAnnotation(Path.class);
            if (pathAnnotation != null) {
                String path = pathAnnotation.value();
                if (path != null) {
                    logger.info("  -> and registering with path: {}", path);
                    Produces producesAnnotation = classWithPath.getAnnotation(Produces.class);
                    if (producesAnnotation != null && producesAnnotation.value() != null) {
                        // TODO can only produce one thing and consume if present must match produce
                        Consumes consumesAnnotation = classWithPath.getAnnotation(Consumes.class);
                        for (String contentType : producesAnnotation.value()) {
                            logger.info("  -> for content-type: {}", contentType);
                            @SuppressWarnings({"unchecked", "rawtypes"})
                            Class<? extends RestService<?>> serviceClass = (Class)classWithPath.asSubclass(RestService.class);
                            if (!RestService.class.isAssignableFrom(serviceClass))
                                throw new IllegalArgumentException(serviceClass + " does not extend " + RestService.class);
                            RegistryKey key = new RegistryKey(new ResourcePath(path), contentType);
                            ServiceRegistry.getInstance().put(key, serviceClass);
                        }
                    }
                }
            }
        }
    }
    if (timer.isEnabled())
        timer.log("limberest initializer scanned " + scanPackages.size() + " packages in ");
}
 
Example 34
Project: xm-commons   File: ReflectionConfig.java   Source Code and License 5 votes vote down vote up
/**
 * {@link Reflections} bean.
 *
 * @return bean
 */
@Bean
public Reflections reflections() {
    return new Reflections(new ConfigurationBuilder()
                               .setUrls(ClasspathHelper.forPackage(SCAN_PACKAGE))
                               .setScanners(new MethodAnnotationsScanner()));
}
 
Example 35
Project: lambda-selenium   File: LambdaTestSuite.java   Source Code and License 5 votes vote down vote up
private static List<Class> getTestClasses(String folderName) {
    Reflections reflections = new Reflections(folderName);
    Set<Class<? extends LambdaBaseTest>> allClasses = reflections.getSubTypesOf(LambdaBaseTest.class);
    List<Class> classes = new ArrayList<>();
    classes.addAll(allClasses);
    return classes;
}
 
Example 36
Project: gaffer-doc   File: PropertiesWalkthrough.java   Source Code and License 5 votes vote down vote up
private static List<Class> getSubClasses(final Class<?> clazz) {
    final Set<URL> urls = new HashSet<>();
    urls.addAll(ClasspathHelper.forPackage("uk.gov.gchq"));

    final List<Class> classes = new ArrayList<Class>(new Reflections(urls).getSubTypesOf(clazz));
    keepPublicConcreteClasses(classes);
    classes.removeIf(c -> c.getName().contains("uk.gov.gchq.gaffer.doc"));
    classes.removeAll(SYSTEM_CLASSES);
    classes.sort(Comparator.comparing(Class::getName));

    return classes;

}
 
Example 37
Project: gaffer-doc   File: ExampleDocRunner.java   Source Code and License 5 votes vote down vote up
private <CLASS> LinkedHashSet<Class<? extends CLASS>> getSubClasses(final Class<?> clazz, final String packageName) {
    final Set<URL> urls = new HashSet<>(ClasspathHelper.forPackage("gaffer"));

    final List<Class<? extends CLASS>> classes = new ArrayList(new Reflections(urls).getSubTypesOf(clazz));
    keepPublicConcreteClasses(classes);
    keepClassesInPackage(classes, packageName);
    Collections.sort(classes, new Comparator<Class>() {
        @Override
        public int compare(final Class class1, final Class class2) {
            return class1.getName().compareTo(class2.getName());
        }
    });

    return Sets.newLinkedHashSet((Iterable) classes);
}
 
Example 38
Project: APacheSynapseSimplePOC   File: ObjectPayload.java   Source Code and License 5 votes vote down vote up
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 39
Project: sentry   File: TaskService.java   Source Code and License 5 votes vote down vote up
@Autowired
public TaskService(TaskRepository taskRepository, TaskMapper taskMapper, Scheduler scheduler) {
    this.taskRepository = taskRepository;
    this.taskMapper = taskMapper;
    this.scheduler = scheduler;
    this.jobTypeSet = new Reflections(Constants.JOBS_PACKAGE).getSubTypesOf(Job.class);
}
 
Example 40
Project: sentry   File: FlowService.java   Source Code and License 5 votes vote down vote up
@Autowired
public FlowService(FlowRepository flowRepository, FlowMapper flowMapper, SubscriberService subscriberService) {
    this.flowRepository = flowRepository;
    this.flowMapper = flowMapper;
    this.subscriberService = subscriberService;
    this.eventTypeSet = new Reflections(Constants.EVENTS_PACKAGE).getSubTypesOf(SentryEvent.class);
}
 
Example 41
Project: nettyRpc   File: RpcServer.java   Source Code and License 5 votes vote down vote up
/**
 * 发现服务, 查找所有扩展了abstractService的类, 这些类保存下来作为service
 */
private static void findService() {
    try {
        Reflections reflections = new Reflections("com.recklessMo.rpc");
        Set<Class<?>> classSet = reflections.getTypesAnnotatedWith(RpcServiceFlag.class, true);
        for (Class<?> inner : classSet) {
            RpcServiceFlag rpcServiceFlag = inner.getAnnotation(RpcServiceFlag.class);
            if (!serverMap.containsKey(rpcServiceFlag.value())) {
                serverMap.put(rpcServiceFlag.value(), inner.newInstance());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 42
Project: sweet-junit-runner   File: SuiteComponentsScanner.java   Source Code and License 5 votes vote down vote up
public Set<Class<?>> loadClasses() {
  Reflections reflections =
          new Reflections(
                  new ConfigurationBuilder()
                          .setUrls(ClasspathHelper.forPackage(packageToScan))
                          .setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner())
                          .filterInputsBy(new FilterBuilder().includePackage(packageToScan)));

  Set<Class<?>> result = new LinkedHashSet<>();
  result.addAll(getClasses(reflections));
  return result;
}
 
Example 43
Project: app-ms   File: SwaggerHandler.java   Source Code and License 5 votes vote down vote up
public SwaggerHandler(
    final Class<? extends Application> applicationClass) {

    final ApplicationPath annotation = applicationClass.getAnnotation(ApplicationPath.class);
    if (annotation != null) {
        baseUri = URI.create(annotation.value()).normalize();
    } else {
        baseUri = URI.create("/");
    }

    Application application;
    try {
        application = applicationClass.newInstance();
    } catch (InstantiationException
        | IllegalAccessException e) {
        throw new ExceptionInInitializerError(e);
    }

    swagger = new ClonableSwagger();
    final Reader swaggerReader = new Reader(swagger);
    final Set<Class<?>> resourceClasses = application.getClasses();
    if (resourceClasses.isEmpty()) {
        final String packageName = applicationClass.getPackage().getName();
        final Reflections reflections = new Reflections(packageName);
        reflections.getTypesAnnotatedWith(Api.class).forEach(swaggerReader::read);
        reflections.getTypesAnnotatedWith(SwaggerDefinition.class).forEach(swaggerReader::read);
    } else {
        swaggerReader.read(applicationClass);
        resourceClasses.forEach(swaggerReader::read);
    }

}
 
Example 44
Project: azure-maven-plugins   File: AnnotationHandlerImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Set<Method> findFunctions(final URL url) {
    return new Reflections(
            new ConfigurationBuilder()
                    .addUrls(url)
                    .setScanners(new MethodAnnotationsScanner())
                    .addClassLoader(getClassLoader(url)))
            .getMethodsAnnotatedWith(FunctionName.class);
}
 
Example 45
Project: cas-server-4.2.1   File: CasLoggerFactory.java   Source Code and License 5 votes vote down vote up
private Set<Class<? extends ILoggerFactory>> scanContextForLoggerFactories() {
    final Set<Class<? extends ILoggerFactory>> loggerFactories;
    final Collection<URL> set = ClasspathHelper.forPackage(PACKAGE_TO_SCAN);
    final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner()));

    loggerFactories = reflections.getSubTypesOf(ILoggerFactory.class);
    loggerFactories.remove(this.getClass());
    return loggerFactories;
}
 
Example 46
Project: Razor   File: ReflectKit.java   Source Code and License 5 votes vote down vote up
public static Reflections getReflections(Class<?> appClass) {

        String packageName = appClass.getPackage().getName();

        return new Reflections(
                packageName,
                new SubTypesScanner(),
                new TypeAnnotationsScanner(),
                new FilterBuilder.Exclude(".*.xml")
        );
    }
 
Example 47
Project: bittrex4j   File: DaoTests.java   Source Code and License 5 votes vote down vote up
@Parameters(name="{0}")
public static Collection<Class<? extends Object>> testParameters() {
    Set<Class<?>> classes = new Reflections(DaoTests.class.getPackage().getName(),
            new SubTypesScanner(false)).getSubTypesOf(Object.class);

    //Dont want to test the tester class itself
    classes.remove(DaoTests.class);
    return classes;
}
 
Example 48
Project: CriteriaBuilder   File: AppConfig.java   Source Code and License 5 votes vote down vote up
@Bean
public Map<String, Class<?>> entityList() {
	Map<String, Class<?>> result = new HashMap<>();
	Reflections reflections = new Reflections("com.bats.criteriagenerator.entity");
	Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Entity.class);
	for (Class<?> clazz : annotated)
	{
		Entity entity = clazz.getAnnotation(Entity.class);
		result.put(entity.name(), clazz);
	}
	return result;
}
 
Example 49
Project: BaseClient   File: ModuleManager.java   Source Code and License 5 votes vote down vote up
public static void init() throws InstantiationException, IllegalAccessException {
    ModuleManager.MODULE_EMPTY.name = "null";
    final Reflections reflections = new Reflections("client.modules", new Scanner[0]);
    final Set<Class<? extends Module>> classes = (Set<Class<? extends Module>>)reflections.getSubTypesOf((Class)Module.class);
    for (final Class<? extends Module> clazz : classes) {
        try {
            final Module loadedModule = (Module)clazz.newInstance();
            if (!clazz.isAnnotationPresent(Mod.class)) {
                continue;
            }
            final Mod modAnnotation = clazz.getAnnotation(Mod.class);
            loadedModule.realName = clazz.getSimpleName();
            loadedModule.name = (modAnnotation.name().equalsIgnoreCase("null") ? clazz.getSimpleName() : modAnnotation.name());
            loadedModule.keyBind = modAnnotation.keybind();
            loadedModule.shown = modAnnotation.shown();
            loadedModule.suffix = modAnnotation.suffix();
            final String categoryString = clazz.getPackage().getName().split("modules.")[1];
            loadedModule.category = Category.valueOf(categoryString.toUpperCase());
            if (modAnnotation.enabled()) {
                loadedModule.onEnable();
            }
            loadedModule.preInit();
            ModuleManager.moduleList.add(loadedModule);
        }
        catch (Exception ex) {}
    }
    load();
    save();
    ModuleManager.moduleList.sort(new Comparator<Module>() {
        @Override
        public int compare(final Module m1, final Module m2) {
            final String s1 = m1.name;
            final String s2 = m2.name;
            return s1.compareTo(s2);
        }
    });
    EventManager.register(new ModuleManager());
}
 
Example 50
Project: BaseClient   File: CommandManager.java   Source Code and License 5 votes vote down vote up
public static void init() throws InstantiationException, IllegalAccessException {
    final Reflections reflections = new Reflections("obsidian.commands", new Scanner[0]);
    final Set<Class<? extends Command>> classes = (Set<Class<? extends Command>>)reflections.getSubTypesOf((Class)Command.class);
    for (final Class<? extends Command> clazz : classes) {
        final Command loadedCommand = (Command)clazz.newInstance();
        if (clazz.isAnnotationPresent(Com.class)) {
            final Com comAnnotation = clazz.getAnnotation(Com.class);
            loadedCommand.names = comAnnotation.names();
            CommandManager.commandList.add(loadedCommand);
        }
    }
    CommandManager.commandList.add(CommandManager.optionCommand);
}
 
Example 51
Project: Biliomi   File: ReflectionUtils.java   Source Code and License 5 votes vote down vote up
public <T> EStream<Class<? extends T>, Exception> subTypes(Class<T> type) {
  return EStream
      .from(new Reflections(new ConfigurationBuilder()
          .forPackages(packages))
          .getSubTypesOf(type))
      .filter(c -> !Modifier.isAbstract(c.getModifiers()));
}
 
Example 52
Project: QDrill   File: PathScanner.java   Source Code and License 5 votes vote down vote up
/**
 * Gets URLs of any classpath resources with given resource pathname.
 *
 * @param  resourcePathname  resource pathname of classpath resource instances
 *           to scan for (relative to specified class loaders' classpath roots)
 * @param  returnRootPathname  whether to collect classpath root portion of
 *           URL for each resource instead of full URL of each resource
 * @param  classLoaders  not currently used (was: "set of class loaders in
 *           which to look up resource; none (empty array) to specify to use
 *           current thread's context class loader and {@link Reflections}'s
 *           class loader")
 * @returns  ...; empty set if none
 */
public static Set<URL> forResource(final String resourcePathname,
                                   final boolean returnRootPathname,
                                   final ClassLoader... classLoaders) {
  logger.debug("Scanning classpath for resources with pathname \"{}\".",
               resourcePathname);
  final Set<URL> resultUrlSet = Sets.newHashSet();

  final ClassLoader classLoader = PathScanner.class.getClassLoader();
  try {
    final Enumeration<URL> resourceUrls =
        classLoader.getResources(resourcePathname);
    while (resourceUrls.hasMoreElements()) {
      final URL resourceUrl = resourceUrls.nextElement();
      logger.trace("- found a(n) {} at {}.", resourcePathname, resourceUrl);

      int index = resourceUrl.toExternalForm().lastIndexOf(resourcePathname);
      if (index != -1 && returnRootPathname) {
        final URL classpathRootUrl =
            new URL(resourceUrl.toExternalForm().substring(0, index));
        resultUrlSet.add(classpathRootUrl);
        logger.debug("- collected resource's classpath root URL {}.",
            classpathRootUrl);
      } else {
        resultUrlSet.add(resourceUrl);
        logger.debug("- collected resource URL {}.", resourceUrl);
      }
    }
  } catch (IOException e) {
    if (Reflections.log != null) {
      Reflections.log.error(
          "Error scanning for resources named " + resourcePathname, e);
    }
  }

  return resultUrlSet;
}
 
Example 53
Project: MMORPG_Prototype   File: PacketsRegisterer.java   Source Code and License 5 votes vote down vote up
public static Kryo registerAllAnnotated(Kryo destination, Class<? extends Annotation> annotationType,
          String sourcePackageName)
  {
Reflections reflections = new Reflections(getUsedPackageName());
      Set<Class<?>> registerableTypes = reflections.getTypesAnnotatedWith(annotationType);
      destination = registerCollection(destination, registerableTypes);
      Set<Class<?>> registerableBaseTypes = reflections.getTypesAnnotatedWith(defaultAnnotationBase);
      destination = registerSubTypesOf(destination, registerableBaseTypes);
      return destination;
  }
 
Example 54
Project: MMORPG_Prototype   File: PacketsRegisterer.java   Source Code and License 5 votes vote down vote up
public static <T> Kryo registerAllSubtypes(Kryo destination, Class<T> baseType, String sourcePackageName)
{
    Reflections reflections = new Reflections(sourcePackageName);
    @SuppressWarnings("unchecked")
    Set<Class<?>> subtypes = (Set<Class<?>>) (Set<?>) reflections.getSubTypesOf(baseType);
    registerCollection(destination, subtypes);
    return destination;
}
 
Example 55
Project: MMORPG_Prototype   File: Assets.java   Source Code and License 5 votes vote down vote up
private static Set<String> getClasspathResources(Set<String> filesExtensions)
  {
Collection<URL> classpathJars = classpathJars();
System.out.println(classpathJars.size());
classpathJars.forEach(System.out::println);
ConfigurationBuilder configuration = new ConfigurationBuilder()
              .setUrls(classpathJars)
              .setScanners(new ResourcesScanner());
      configuration.setInputsFilter(Assets::isValidResourcePath);
      Reflections reflections = new Reflections(configuration);
      Set<String> resources = reflections.getResources(getResourcePattern(filesExtensions));
      return resources;
  }
 
Example 56
Project: MMORPG_Prototype   File: ReflectionResourceUtils.java   Source Code and License 5 votes vote down vote up
public static Set<String> getClasspathResources(Set<String> filesExtensions, Predicate<String> inputsFilter)
{
	Collection<URL> classpathJars = getUsedJars();
	System.out.println(classpathJars.size());
	classpathJars.forEach(System.out::println);
	ConfigurationBuilder configuration = new ConfigurationBuilder().setUrls(classpathJars)
			.setScanners(new ResourcesScanner());
	configuration.setInputsFilter(inputsFilter);
	Reflections reflections = new Reflections(configuration);
	Set<String> resources = reflections.getResources(getResourcePattern(filesExtensions));
	return resources;
}
 
Example 57
Project: MMORPG_Prototype   File: HibernateUtil.java   Source Code and License 5 votes vote down vote up
private static void registerEntityTypes(Configuration config)
{
	Reflections reflections = new Reflections("pl.mmorpg.prototype.server.database.entities");
	Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Table.class);
	for (Class<?> type : entityTypes)
		config = config.addAnnotatedClass(type);
}
 
Example 58
Project: MMORPG_Prototype   File: DatabaseSeedCommand.java   Source Code and License 5 votes vote down vote up
private void assertAllSeedersAreUsed(Collection<TableSeeder> seeders)
{
	Reflections reflections = new Reflections(TableSeeder.class.getPackage().getName());
	Set<Class<? extends TableSeeder>> subTypes = reflections.getSubTypesOf(TableSeeder.class);
	if(subTypes.size() != seeders.size())
		Log.warn("Used seeders: " + seeders.size() + ", but there are total " + subTypes.size());
}
 
Example 59
Project: Ferma-OrientDB   File: ElementTypeClassCache.java   Source Code and License 5 votes vote down vote up
public Class forName(final String className) {
	return this.classStringCache.computeIfAbsent(className, (key) -> {
		for (String basePath : basePaths) {
			Set<Class<?>> graphTypeClasses = new Reflections(basePath).getTypesAnnotatedWith(GraphElement.class);
			for (Class<?> clazz : graphTypeClasses) {
				if (clazz.getSimpleName().equals(key)) {
					return clazz;
				}
			}
		}
		throw new IllegalStateException("The class {" + className + "} cannot be found for basePaths {" + Arrays.toString(basePaths) + "}");
	});
}
 
Example 60
Project: ysoserial-modified   File: ObjectPayload.java   Source Code and License 5 votes vote down vote up
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;
}