Java Code Examples for org.reflections.scanners.SubTypesScanner

The following examples show how to use org.reflections.scanners.SubTypesScanner. These examples are extracted from open source projects. 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
/**
 * Prepares the logger context. Locates the context and
 * sets the configuration file.
 * @return the logger context
 */
private ServletContextListener prepareAndgetContextListener() {
    try {
        if (StringUtils.isNotBlank(this.loggerContextPackageName)) {
            final Collection<URL> set = ClasspathHelper.forPackage(this.loggerContextPackageName);
            final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner()));
            final Set<Class<? extends ServletContextListener>> subTypesOf = reflections.getSubTypesOf(ServletContextListener.class);
            final ServletContextListener loggingContext = subTypesOf.iterator().next().newInstance();
            this.context.setInitParameter(this.logConfigurationField, this.logConfigurationFile.getURI().toString());
            return loggingContext;
        }
        return null;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source Project: mybatis-jpa   Source File: AnnotationStatementScanner.java    License: Apache License 2.0 6 votes vote down vote up
public void scan() {
  for (String basePackage : basePackages) {
    Reflections reflections = new Reflections(basePackage, new TypeAnnotationsScanner(),
        new SubTypesScanner(), new MethodAnnotationsScanner());
    Set<Class<?>> mappers = reflections.getTypesAnnotatedWith(Mapper.class);
    for (Class<?> mapperClass : mappers) {
      Method[] methods = mapperClass.getMethods();
      for (Method method : methods) {
        Annotation[] annotations = method.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
          StatementFactory statementFactory = annotationStatementRegistry
              .findFactory(annotation.annotationType());
          if (statementFactory != null) {
            MappedStatement statement = statementFactory.parseStatement(configuration, method, mapperClass);
            configuration.addMappedStatement(statement);
          }
        }

      }
    }
  }
  parsePendingMethods();
}
 
Example 3
Source Project: swagger-maven-plugin   Source File: JaxRSScanner.java    License: MIT License 6 votes vote down vote up
Application applicationInstance() {
    ConfigurationBuilder config = ConfigurationBuilder
            .build(resourcePackages)
            .setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
    Reflections reflections = new Reflections(config);
    Set<Class<? extends Application>> applicationClasses = reflections.getSubTypesOf(Application.class)
            .stream()
            .filter(this::filterClassByResourcePackages)
            .collect(Collectors.toSet());
    if (applicationClasses.isEmpty()) {
        return null;
    }
    if (applicationClasses.size() > 1) {
        log.warn("More than one javax.ws.rs.core.Application classes found on the classpath, skipping");
        return null;
    }
    return ClassUtils.createInstance(applicationClasses.iterator().next());
}
 
Example 4
public ReflectionsServiceDiscovery(String resourceSearchPackages, JsonServiceLocator locator) {
	this.locator = locator;

	ConfigurationBuilder builder = new ConfigurationBuilder();

	PreconditionUtil.assertNotNull("no resourceSearchPackage configured", resourceSearchPackages);

	FilterBuilder filter = new FilterBuilder();
	for (String resourceSearchPackage : resourceSearchPackages.split(",")) {
		builder = builder.addUrls(ClasspathHelper.forPackage(resourceSearchPackage));
		filter.includePackage(resourceSearchPackage);
	}
	filter.includePackage(Repository.class.getPackage().getName());
	filter.includePackage(ResourceRepository.class.getPackage().getName());
	builder = builder.filterInputsBy(filter);

	builder = builder.addUrls(ClasspathHelper.forClass(Repository.class));
	builder = builder.addUrls(ClasspathHelper.forClass(ResourceRepository.class));
	builder = builder.addUrls(ClasspathHelper.forClass(ResourceRepositoryV2.class));

	builder = builder.setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner());
	reflections = new Reflections(builder);
}
 
Example 5
Source Project: Java2PlantUML   Source File: Parser.java    License: Apache License 2.0 6 votes vote down vote up
private static Collection<? extends Class<?>> getPackageTypes(String packageToPase, Collection<URL> urls) {
    Set<Class<?>> classes = new HashSet<>();
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setScanners(new SubTypesScanner(false /* exclude Object.class */), new ResourcesScanner(), new TypeElementsScanner())
            .setUrls(urls)
            .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageToPase)).exclude("java.*")));

    Set<String> types;
    types = reflections.getStore().get("TypeElementsScanner").keySet();
    for (String type: types) {
        Class<?> aClass = TypesHelper.loadClass(type, CLASS_LOADER);
        boolean wantedElement = StringUtils.startsWith(type, packageToPase);
        if (null != aClass && wantedElement) {
            logger.log(Level.INFO, "looking up for type: " + type);
            classes.add(aClass);
        }
    }
    return classes;
}
 
Example 6
public void addLoader(ClassLoader loader) {
    if (builder == null) {
        this.builder = new ConfigurationBuilder();
        builder.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
    }
    builder.addClassLoader(loader);
    builder.addUrls(ClasspathHelper.forClassLoader(loader));

    if(loader instanceof JoinClassLoader) {
        // When the object "reflections" is created in the method scanClassPath(), are scanned the URLs so
        // it is necessary to add the URLs from the enclosing class loader in the JoinClassLoader that it
        // contains the fixture classpath (see org.reflections.Reflections.scan()).
        builder.addUrls(ClasspathHelper.forClassLoader(((JoinClassLoader) loader).getEnclosingClassLoader()));
    }

    scanClassPath(builder);
}
 
Example 7
Source Project: java-telegram-bot-api   Source File: ModelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setClasses() {
    String modelPackage = Animation.class.getPackage().getName();
    String passportPackage = Credentials.class.getPackage().getName();
    List<String> packages = Arrays.asList(modelPackage, passportPackage);

    classes = new Reflections(packages, new SubTypesScanner(false))
            .getSubTypesOf(Object.class)
            .stream()
            .filter(clazz -> packages.contains(clazz.getPackage().getName())
                    && !clazz.getSimpleName().startsWith("PassportElementError")
                    && !Modifier.isAbstract(clazz.getModifiers())
            ).collect(Collectors.toSet());

    // classes from model/request available in responses
    classes.add(InlineKeyboardMarkup.class);
    classes.add(InlineKeyboardButton.class);
    customInstance.put(InlineKeyboardMarkup.class, InlineKeyboardMarkup::new);
    customInstance.put(InlineKeyboardButton.class, () -> new InlineKeyboardButton(""));
}
 
Example 8
Source Project: anno4j   Source File: RoleClassLoader.java    License: 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 9
Source Project: che   Source File: TypeScriptDtoGenerator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Init stuff is responsible to grab all DTOs found in classpath (classloader) and setup model for
 * String Template
 */
protected void init() {

  ConfigurationBuilder configurationBuilder =
      new ConfigurationBuilder().setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
  if (useClassPath) {
    configurationBuilder.setUrls(forJavaClassPath());
  } else {
    configurationBuilder.setUrls(forClassLoader());
  }

  // keep only DTO interfaces
  Reflections reflections = new Reflections(configurationBuilder);
  List<Class<?>> annotatedWithDtos =
      new ArrayList<>(reflections.getTypesAnnotatedWith(DTO.class));
  List<Class<?>> interfacesDtos =
      annotatedWithDtos
          .stream()
          .filter(clazz -> clazz.isInterface())
          .collect(Collectors.toList());
  interfacesDtos.stream().forEach(this::analyze);
}
 
Example 10
Source Project: archie   Source File: ModelInfoLookup.java    License: Apache License 2.0 6 votes vote down vote up
public ModelInfoLookup(ModelNamingStrategy namingStrategy, String packageName, ClassLoader classLoader) {
    this.packageName = packageName;
    this.namingStrategy = namingStrategy;

    this.classLoader = classLoader;
    Reflections reflections = new Reflections(packageName, new SubTypesScanner(false));
    Set<String> typeNames = reflections.getAllTypes();

    System.out.println("type names size: " + typeNames.size());
    typeNames.forEach(typeName -> {
        try {
            addClass(classLoader.loadClass(typeName));
        } catch (ClassNotFoundException e) {
            logger.error("error loading model info lookup", e);
        }
    });
    addSuperAndSubclassInfo();
    inConstructor = false;
}
 
Example 11
Source Project: robe   Source File: GuiceBundle.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a {@link org.reflections.Reflections} with the given packages (configuration)
 *
 * @param scanPackages
 */
private void createReflections(String[] scanPackages) {
    if (scanPackages.length < 1) {
        LOGGER.warn("No package defined in configuration (scanPackages)!");
        return;
    }
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    FilterBuilder filterBuilder = new FilterBuilder();
    for (String packageName : scanPackages) {
        configurationBuilder.addUrls(ClasspathHelper.forPackage(packageName));
        filterBuilder.include(FilterBuilder.prefix(packageName));
    }

    configurationBuilder.filterInputsBy(filterBuilder).setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
    this.reflections = new Reflections(configurationBuilder);

}
 
Example 12
Source Project: Kylin   Source File: RealizationRegistry.java    License: Apache License 2.0 6 votes vote down vote up
private void init() {
    providers = Maps.newConcurrentMap();

    // use reflection to load providers
    final Set<Class<? extends IRealizationProvider>> realizationProviders = new Reflections("org.apache.kylin", new SubTypesScanner()).getSubTypesOf(IRealizationProvider.class);
    List<Throwable> es = Lists.newArrayList();
    for (Class<? extends IRealizationProvider> cls : realizationProviders) {
        try {
            IRealizationProvider p = (IRealizationProvider) cls.getMethod("getInstance", KylinConfig.class).invoke(null, config);
            providers.put(p.getRealizationType(), p);

        } catch (Exception | NoClassDefFoundError e) {
            es.add(e);
        }

        if (es.size() > 0) {
            for (Throwable exceptionOrError : es) {
                logger.error("Create new store instance failed ", exceptionOrError);
            }
            throw new IllegalArgumentException("Failed to find metadata store by url: " + config.getMetadataUrl());
        }
    }

    logger.info("RealizationRegistry is " + providers);
}
 
Example 13
Source Project: yawp   Source File: ClassloaderScanner.java    License: MIT License 6 votes vote down vote up
private Reflections buildReflections(String packages) {
    String[] packagesArray = packages.replaceAll(" ", "").split(",");

    FilterBuilder filter = new FilterBuilder();

    Set<URL> urls = new HashSet();

    for (String packageStr : packagesArray) {
        urls.addAll(ClasspathHelper.forPackage(packageStr));
        filter.include(FilterBuilder.prefix(packageStr));
    }

    return new Reflections(new ConfigurationBuilder()
            .addUrls(urls)
            .filterInputsBy(filter)
            .setScanners(new TypeAnnotationsScanner(), new SubTypesScanner()));
}
 
Example 14
Source Project: streams   Source File: ElasticsearchParentChildUpdaterIT.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTestParentChildPersistUpdater() throws Exception {

  testConfiguration = new ComponentConfigurator<>(ElasticsearchWriterConfiguration.class).detectConfiguration( "ElasticsearchParentChildUpdaterIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getIndex());
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  assertTrue(indicesExistsResponse.isExists());

  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forPackage("org.apache.streams.pojo.json"))
      .setScanners(new SubTypesScanner()));
  objectTypes = reflections.getSubTypesOf(ActivityObject.class);

  Path testdataDir = Paths.get("target/dependency/activitystreams-testdata");
  files = Files.list(testdataDir).collect(Collectors.toList());

}
 
Example 15
Source Project: streams   Source File: StreamsJacksonModule.java    License: Apache License 2.0 6 votes vote down vote up
public StreamsJacksonModule() {
  super();

  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forPackage("org.apache.streams.jackson"))
      .setScanners(new SubTypesScanner()));

  Set<Class<? extends StreamsDateTimeFormat>> dateTimeFormatClasses = reflections.getSubTypesOf(StreamsDateTimeFormat.class);

  List<String> dateTimeFormats = new ArrayList<>();
  for (Class dateTimeFormatClass : dateTimeFormatClasses) {
    try {
      dateTimeFormats.add(((StreamsDateTimeFormat) (dateTimeFormatClass.newInstance())).getFormat());
    } catch (Exception ex) {
      LOGGER.warn("Exception getting format from " + dateTimeFormatClass);
    }
  }

  addSerializer(DateTime.class, new StreamsDateTimeSerializer(DateTime.class));
  addDeserializer(DateTime.class, new StreamsDateTimeDeserializer(DateTime.class, dateTimeFormats));

  addSerializer(Period.class, new StreamsPeriodSerializer(Period.class));
  addDeserializer(Period.class, new StreamsPeriodDeserializer(Period.class));
}
 
Example 16
Source Project: streams   Source File: ActivitySerDeTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 );
    Path testActivityPath = Paths.get("target/dependency/activitystreams-testdata/" + testfile);
    assert (testActivityPath.toFile().exists());
    FileInputStream testActivityFileStream = new FileInputStream(testActivityPath.toFile());
    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 17
Source Project: streams   Source File: StreamsScalaSourceGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * StreamsScalaSourceGenerator constructor.
 * @param config StreamsScalaGenerationConfig
 */
public StreamsScalaSourceGenerator(StreamsScalaGenerationConfig config) {
  this.config = config;
  this.outDir = config.getTargetDirectory().getAbsolutePath();
  reflections = new Reflections(
      new ConfigurationBuilder()
          // TODO
          .forPackages(
              config.getSourcePackages()
                  .toArray(new String[config.getSourcePackages().size()])
          )
          .setScanners(
              new SubTypesScanner(),
              new TypeAnnotationsScanner()));

}
 
Example 18
Source Project: foxtrot   Source File: AnalyticsLoader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    Reflections reflections = new Reflections("com.flipkart.foxtrot", new SubTypesScanner());
    Set<Class<? extends Action>> actionSet = reflections.getSubTypesOf(Action.class);
    if (actionSet.isEmpty()) {
        throw new AnalyticsActionLoaderException("No analytics actions found!!");
    }
    List<NamedType> types = new ArrayList<>();
    for (Class<? extends Action> action : actionSet) {
        AnalyticsProvider analyticsProvider = action.getAnnotation(AnalyticsProvider.class);
        final String opcode = analyticsProvider.opcode();
        if (Strings.isNullOrEmpty(opcode)) {
            throw new AnalyticsActionLoaderException("Invalid annotation on " + action.getCanonicalName());
        }
        register(new ActionMetadata(analyticsProvider.request(), action, analyticsProvider.cacheable()),
                 analyticsProvider.opcode());
        types.add(new NamedType(analyticsProvider.request(), opcode));
        types.add(new NamedType(analyticsProvider.response(), opcode));
        logger.info("Registered action: {}", action.getCanonicalName());
    }
    objectMapper.getSubtypeResolver()
            .registerSubtypes(types.toArray(new NamedType[0]));
}
 
Example 19
Source Project: foxtrot   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void registerActions(AnalyticsLoader analyticsLoader, ObjectMapper mapper) throws Exception {
    Reflections reflections = new Reflections("com.flipkart.foxtrot", new SubTypesScanner());
    Set<Class<? extends Action>> actions = reflections.getSubTypesOf(Action.class);
    if(actions.isEmpty()) {
        throw new Exception("No analytics actions found!!");
    }
    List<NamedType> types = new Vector<>();
    for(Class<? extends Action> action : actions) {
        AnalyticsProvider analyticsProvider = action.getAnnotation(AnalyticsProvider.class);
        final String opcode = analyticsProvider.opcode();
        if(Strings.isNullOrEmpty(opcode)) {
            throw new Exception("Invalid annotation on " + action.getCanonicalName());
        }

        analyticsLoader.register(
                new ActionMetadata(analyticsProvider.request(), action, analyticsProvider.cacheable()), analyticsProvider.opcode());
        if(analyticsProvider.cacheable()) {
            analyticsLoader.registerCache(opcode);
        }
        types.add(new NamedType(analyticsProvider.request(), opcode));
        types.add(new NamedType(analyticsProvider.response(), opcode));
        logger.info("Registered action: " + action.getCanonicalName());
    }
    mapper.getSubtypeResolver()
            .registerSubtypes(types.toArray(new NamedType[types.size()]));
}
 
Example 20
Source Project: spring-boot-starter-micro-job   Source File: ClassTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定package下的接口实现类
 *
 * @param scannerPackage 扫描的package
 * @return 实现类集合
 */
public static Set<Class<? extends JobTrigger>> getJobs(String scannerPackage) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setScanners(new TypeAnnotationsScanner(), new SubTypesScanner());
    configurationBuilder.filterInputsBy(new FilterBuilder().includePackage(scannerPackage));
    configurationBuilder.addUrls(ClasspathHelper.forPackage(scannerPackage));
    Reflections reflections = new Reflections(scannerPackage);
    return reflections.getSubTypesOf(JobTrigger.class);
}
 
Example 21
Source Project: jsonschema-generator   Source File: SchemaGeneratorMojo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get all the names of classes on the classpath.
 *
 * @return A set of class names as found on the classpath
 */
private Set<String> getAllClassNames() {
    if (this.allTypes == null) {
        Reflections reflections = new Reflections("", new SubTypesScanner(false), this.getClassLoader());
        allTypes = reflections.getAllTypes();
    }

    return allTypes;
}
 
Example 22
Source Project: api-boot   Source File: ClassTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 初始化反射对象
 *
 * @param scannerPackage 扫描的package
 * @return 反射对象
 */
static Reflections initReflections(String scannerPackage) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setScanners(new TypeAnnotationsScanner(), new SubTypesScanner());
    configurationBuilder.filterInputsBy(new FilterBuilder().includePackage(scannerPackage));
    configurationBuilder.addUrls(ClasspathHelper.forPackage(scannerPackage));
    return new Reflections(scannerPackage);
}
 
Example 23
Source Project: ure   Source File: GlyphedModal.java    License: MIT License 5 votes vote down vote up
void getAllTypes() {
    Reflections reflections = new Reflections("ure", new SubTypesScanner());
    iconClasses = reflections.getSubTypesOf(Icon.class);
    iconTypes = new ArrayList<>();
    for (Class<? extends Icon> iclass : iconClasses) {
        try {
            iconTypes.add(((Icon)(iclass.newInstance())).getTYPE());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 24
Source Project: springboot-shiro-cas-mybatis   Source File: CasLoggerFactory.java    License: MIT 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 25
Source Project: jkes   Source File: ClassUtils.java    License: Apache License 2.0 5 votes vote down vote up
static Set<Class<?>> getClasses(String packageName) {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
            .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
            .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName))));

    Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);
    return classes;
}
 
Example 26
Source Project: swagger-maven-plugin   Source File: JaxRSScanner.java    License: MIT License 5 votes vote down vote up
Set<Class<?>> classes() {
    ConfigurationBuilder config = ConfigurationBuilder
            .build(resourcePackages)
            .setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
    Reflections reflections = new Reflections(config);
    Stream<Class<?>> apiClasses = reflections.getTypesAnnotatedWith(Path.class)
            .stream()
            .filter(this::filterClassByResourcePackages);
    Stream<Class<?>> defClasses = reflections.getTypesAnnotatedWith(OpenAPIDefinition.class)
            .stream()
            .filter(this::filterClassByResourcePackages);
    return Stream.concat(apiClasses, defClasses).collect(Collectors.toSet());
}
 
Example 27
Source Project: lambda-monitoring   Source File: MetricsFinder.java    License: Apache License 2.0 5 votes vote down vote up
public Map<String, Field> find() throws MalformedURLException {

        Reflections reflections = new Reflections(
                new ConfigurationBuilder()
                        .setUrls(classpathUrls)
                        .addClassLoader(new URLClassLoader(classpathUrls.toArray(new URL[0]), getClass().getClassLoader()))
                        .setScanners(new SubTypesScanner()));

        Map<String, Field> metricFields = new HashMap<>();
        for (Class<? extends LambdaMetricSet> type : reflections.getSubTypesOf(LambdaMetricSet.class)) {
            metricFields.putAll(MetricsUtils.findAnnotatedFields(type));
        }

        return metricFields;
    }
 
Example 28
private static void printUsage() {

		System.out.println("Usage: ./gradlew run -Pdemo=<demo>\n\nAvailable options for <demo>");

		List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
		classLoadersList.add(ClasspathHelper.contextClassLoader());
		classLoadersList.add(ClasspathHelper.staticClassLoader());

		Reflections reflections = new Reflections(new ConfigurationBuilder()
		    .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
		    .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
		    .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(testsPackage))));
		
		Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);
		TreeSet<String> sortedClasses = new TreeSet<String>();
		HashMap<String,String> classDescriptions = new HashMap<String, String>();
		for (Class<? extends Object> cl : classes) {
			if (!cl.getSimpleName().equals("")) {
				sortedClasses.add(cl.getName().replace(testsPackage+".",""));
				String descString = "";
				if (cl.getAnnotation(DemoDescription.class) != null) descString = cl.getAnnotation(DemoDescription.class).desc();
				classDescriptions.put(cl.getName().replace(testsPackage+".",""),descString);
			}
		}
		for (String className : sortedClasses) {
			System.out.println();				
			List<String> descStrings = StringUtils.description("   \u001B[1m\u001b[32m"+className+"\u001b[0m: ", classDescriptions.get(className), 72, 6);
			for (String ds : descStrings) System.out.println(ds);
		}
		
		System.out.println();
		String note = "Most examples require the ReedsSheppCarPlanner motion planner, which is provided via a"
				+ "linked library that has to be built and depends on ompl (http://ompl.kavrakilab.org/)"
				+ "and mrpt (http://www.mrpt.org/). See REAME.md for building instructions.";
		List<String> formattedNote = StringUtils.description("NOTE: ", note, 72);
		for (String line : formattedNote) System.out.println(line);
		
	}
 
Example 29
Source Project: java-flagz   Source File: ReflectionsCache.java    License: MIT License 5 votes vote down vote up
static synchronized Reflections reflectionsForPrefixes(List<String> prefixes) {
  if (packagePrefixesToReflections.containsKey(prefixes)) {
    return packagePrefixesToReflections.get(prefixes);
  }
  ConfigurationBuilder builder = new ConfigurationBuilder()
      .setUrls(urlsToReflect(prefixes))
      .setScanners(
          new FieldAnnotationsScanner(),
          new SubTypesScanner());
  Reflections reflections = new Reflections(builder);
  packagePrefixesToReflections.put(prefixes, reflections);
  return reflections;
}
 
Example 30
Source Project: anno4j   Source File: OWLSchemaPersistingManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMatchingExistingSchema() throws Exception {
    Anno4j anno4j = new Anno4j();

    OWLClazz myPerson = anno4j.createObject(OWLClazz.class, (Resource) new URIImpl("http://example.de/#validly_annotated_person"));
    RDFSProperty bossProperty = anno4j.createObject(RDFSProperty.class, (Resource) new URIImpl("http://example.de/#has_boss"));

    Restriction bossAllValuesFromRestr = anno4j.createObject(Restriction.class);
    bossAllValuesFromRestr.setOnClazz(Sets.newHashSet(myPerson));
    bossAllValuesFromRestr.setOnProperty(Sets.newHashSet(bossProperty));
    bossAllValuesFromRestr.setAllValuesFrom(Sets.<OWLClazz>newHashSet(myPerson));

    Reflections types = new Reflections(
            new ConfigurationBuilder()
                    .setUrls(
                            ClasspathHelper.forClass(Person.class, ClasspathHelper.staticClassLoader()),
                            ClasspathHelper.forClass(PersonSupport.class, ClasspathHelper.staticClassLoader())
                    )
                    .setScanners(new MethodAnnotationsScanner(), new FieldAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner())
    );

    Transaction transaction = anno4j.createTransaction();
    transaction.begin();
    SchemaPersistingManager persistingManager = new OWLSchemaPersistingManager(transaction.getConnection());

    boolean exceptionThrown = false;
    try {
        persistingManager.persistSchema(types);
    } catch (SchemaPersistingManager.ContradictorySchemaException e) {
        exceptionThrown = true;
    }
    assertFalse(exceptionThrown);
}