org.reflections.scanners.SubTypesScanner Java Examples

The following examples show how to use org.reflections.scanners.SubTypesScanner. 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: AnnotationStatementScanner.java    From mybatis-jpa with 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 #2
Source File: Parser.java    From Java2PlantUML with 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 #3
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 #4
Source File: ReflectionsServiceDiscovery.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
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 File: TypeScriptDtoGenerator.java    From che with 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 #6
Source File: RealizationRegistry.java    From Kylin with 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 #7
Source File: ClassloaderScanner.java    From yawp with 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 #8
Source File: ElasticsearchParentChildUpdaterIT.java    From streams with 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 #9
Source File: AnnotationLoader.java    From livingdoc-core with GNU General Public License v3.0 6 votes vote down vote up
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 #10
Source File: JaxRSScanner.java    From swagger-maven-plugin with 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 #11
Source File: StreamsJacksonModule.java    From streams with 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 #12
Source File: ActivitySerDeTest.java    From streams with 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 #13
Source File: StreamsScalaSourceGenerator.java    From streams with 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 #14
Source File: AnalyticsLoader.java    From foxtrot with 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 #15
Source File: CasLoggerContextInitializer.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * 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 #16
Source File: TestUtils.java    From foxtrot with 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 #17
Source File: ModelInfoLookup.java    From archie with 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 #18
Source File: ModelTest.java    From java-telegram-bot-api with 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 #19
Source File: GuiceBundle.java    From robe with 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 #20
Source File: ClassFinder.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static <T extends BrooklynObject> Set<Class<? extends T>> findClasses(Collection<URL> urls, Class<T> clazz) {
    ClassLoader classLoader = new UrlClassLoader(urls.toArray(new URL[urls.size()]));
    
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .addClassLoader(classLoader)
            .addScanners(new SubTypesScanner(), new TypeAnnotationsScanner(), new FieldAnnotationsScanner())
            .addUrls(urls));
    
    Set<Class<? extends T>> types = reflections.getSubTypesOf(clazz);
    
    return types;
}
 
Example #21
Source File: ClasspathScanner.java    From valdr-bean-validation with MIT License 5 votes vote down vote up
/**
 * Scans the classpath to find all classes that are in the configured model packages. It ignores excluded classes.
 *
 * @return classes to parse
 * @see Options
 */
public Set<Class<?>> findClassesToParse() {
  Reflections reflections = new Reflections(new ConfigurationBuilder().
    setUrls(buildClassLoaderUrls()).setScanners(new SubTypesScanner(false)).filterInputsBy(buildPackagePredicates()));

  return reflections.getSubTypesOf(Object.class);
}
 
Example #22
Source File: VertxNubes.java    From nubes with Apache License 2.0 5 votes vote down vote up
/**
 * @param vertx the vertx instance
 */
public VertxNubes(Vertx vertx, JsonObject json) {
  this.vertx = vertx;
  config = Config.fromJsonObject(json, vertx);
  deploymentIds = new ArrayList<>();
  registry = new ParameterAdapterRegistry();
  marshallers = new HashMap<>();
  config.setMarshallers(marshallers);
  config.createAnnotInjectors(registry);

  // marshalling
  TemplateEngineManager templManager = new TemplateEngineManager(config);
  registerAnnotationProcessor(View.class, new ViewProcessorFactory(templManager));
  registerAnnotationProcessor(File.class, new FileProcessorFactory());
  registerMarshaller("text/plain", new PlainTextMarshaller());
  registerMarshaller("application/json", new JacksonPayloadMarshaller());
  String domainPackage = config.getDomainPackage();
  if (domainPackage != null) {
    try {
      Reflections reflections = new Reflections(domainPackage, new SubTypesScanner(false));
      registerMarshaller("application/xml", new JAXBPayloadMarshaller(reflections.getSubTypesOf(Object.class)));
    } catch (JAXBException je) {
      throw new VertxException(je);
    }
  }
  failureHandler = new DefaultErrorHandler(config, templManager, marshallers);

  // default processors/handlers
  CookieHandler cookieHandler = CookieHandler.create();
  registerAnnotationHandler(Cookies.class, cookieHandler);
  registerAnnotationHandler(CookieValue.class, cookieHandler);
  registerAnnotationHandler(Throttled.class, RateLimitationHandler.create(config));
  registerTypeProcessor(PaginationContext.class, new PaginationProcessor());
  registerTypeProcessor(Payload.class, new PayloadTypeProcessor(marshallers));
  registerAnnotationProcessor(Redirect.class, new ClientRedirectProcessorFactory());
  registerAnnotationProcessor(ContentType.class, new ContentTypeProcessorFactory());
  registerAnnotationProcessor(Logout.class, new LogoutProcessor());
}
 
Example #23
Source File: Manager.java    From hbase-tools with Apache License 2.0 5 votes vote down vote up
private static Reflections createReflections() {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    return new Reflections(new ConfigurationBuilder()
        .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
        .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader(
            classLoadersList.toArray(new ClassLoader[classLoadersList.size()]))))
        .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command"))));
}
 
Example #24
Source File: Manager.java    From hbase-tools with Apache License 2.0 5 votes vote down vote up
private static Reflections createReflections() {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    return new Reflections(new ConfigurationBuilder()
        .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
        .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader(
            classLoadersList.toArray(new ClassLoader[classLoadersList.size()]))))
        .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command"))));
}
 
Example #25
Source File: Manager.java    From hbase-tools with Apache License 2.0 5 votes vote down vote up
private static Reflections createReflections() {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    return new Reflections(new ConfigurationBuilder()
        .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
        .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader(
            classLoadersList.toArray(new ClassLoader[classLoadersList.size()]))))
        .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command"))));
}
 
Example #26
Source File: ReflectionScanner.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** scanner which will look in the given urls 
 * (or if those are null attempt to infer from the first entry in the classloaders,
 * although currently that seems to only pick up directories, not JAR's),
 * optionally filtering for the given prefix;
 * any or all arguments can be null to accept all (and use default classpath for classloading).
 **/
public ReflectionScanner(
        final Iterable<URL> urlsToScan, 
        final String optionalPrefix,
        final Predicate<String> filter,
        final ClassLoader ...classLoaders) {
    if (Reflections.log==null) {
        Reflections.log = log;
    }
    reflections = new Reflections(new ConfigurationBuilder() {
        {
            if (urlsToScan!=null)
                setUrls(ImmutableSet.copyOf(urlsToScan));
            else if (classLoaders.length>0 && classLoaders[0]!=null)
                setUrls(
                        ClasspathHelper.forPackage(Strings.isNonEmpty(optionalPrefix) ? optionalPrefix : "",
                                asClassLoaderVarArgs(classLoaders[0])));
            
            if (filter!=null) filterInputsBy(filter);

            Scanner typeScanner = new TypeAnnotationsScanner();
            if (filter!=null) typeScanner = typeScanner.filterResultsBy(filter);
            Scanner subTypeScanner = new SubTypesScanner();
            if (filter!=null) subTypeScanner = subTypeScanner.filterResultsBy(filter);
            setScanners(typeScanner, subTypeScanner);
            
            for (ClassLoader cl: classLoaders)
                if (cl!=null) addClassLoader(cl);
        }
    });
    this.classLoaders = Iterables.toArray(Iterables.filter(Arrays.asList(classLoaders), Predicates.notNull()), ClassLoader.class);
}
 
Example #27
Source File: ParameterParsingChain.java    From gauge-java with Apache License 2.0 5 votes vote down vote up
private Reflections createReflections() {
    Configuration config = new ConfigurationBuilder()
            .setScanners(new SubTypesScanner())
            .addUrls(ClasspathHelper.getUrls())
            .filterInputsBy(new FilterBuilder().include(".+\\.class"));
    return new Reflections(config);
}
 
Example #28
Source File: NativeImageHelper.java    From arangodb-java-driver with Apache License 2.0 5 votes vote down vote up
private static void generateReflectConfig() throws JsonProcessingException {
    System.out.println("---------------------------");
    System.out.println("--- reflect-config.json ---");
    System.out.println("---------------------------");

    List<String> packages = Arrays.asList("com.arangodb.entity", "com.arangodb.model");

    ObjectMapper mapper = new ObjectMapper();
    ArrayNode rootNode = mapper.createArrayNode();
    ObjectNode noArgConstructor = mapper.createObjectNode();
    noArgConstructor.put("name", "<init>");
    noArgConstructor.set("parameterTypes", mapper.createArrayNode());
    ArrayNode methods = mapper.createArrayNode();
    methods.add(noArgConstructor);

    packages.stream()
            .flatMap(p -> {
                final ConfigurationBuilder config = new ConfigurationBuilder()
                        .setScanners(new ResourcesScanner(), new SubTypesScanner(false))
                        .setUrls(ClasspathHelper.forPackage(p))
                        .filterInputsBy(new FilterBuilder().includePackage(p));

                return new Reflections(config).getSubTypesOf(Object.class).stream();
            })
            .map(Class::getName)
            .map(className -> {
                ObjectNode entry = mapper.createObjectNode();
                entry.put("name", className);
                entry.put("allDeclaredFields", true);
                entry.set("methods", methods);
                return entry;
            })
            .forEach(rootNode::add);

    String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
    System.out.println(jsonString);
}
 
Example #29
Source File: ReflectionsApp.java    From tutorials with MIT License 5 votes vote down vote up
public Set<Class<? extends Scanner>> getReflectionsSubTypesUsingBuilder() {
    Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections"))
        .setScanners(new SubTypesScanner()));

    Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class);
    return scannersSet;
}
 
Example #30
Source File: ElasticsearchParentChildWriterIT.java    From streams with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void prepareTestParentChildPersistWriter() throws Exception {

  testConfiguration = new ComponentConfigurator<>(ElasticsearchWriterConfiguration.class).detectConfiguration("ElasticsearchParentChildWriterIT");
  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();
  if (indicesExistsResponse.isExists()) {
    DeleteIndexRequest deleteIndexRequest = Requests.deleteIndexRequest(testConfiguration.getIndex());
    DeleteIndexResponse deleteIndexResponse = testClient.admin().indices().delete(deleteIndexRequest).actionGet();
    assertTrue(deleteIndexResponse.isAcknowledged());
  }

  PutIndexTemplateRequestBuilder putTemplateRequestBuilder = testClient.admin().indices().preparePutTemplate("mappings");
  URL templateURL = ElasticsearchParentChildWriterIT.class.getResource("/ActivityChildObjectParent.json");
  ObjectNode template = MAPPER.readValue(templateURL, ObjectNode.class);
  String templateSource = MAPPER.writeValueAsString(template);
  putTemplateRequestBuilder.setSource(templateSource);

  testClient.admin().indices().putTemplate(putTemplateRequestBuilder.request()).actionGet();

  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());

  assert( files.size() > 0);
}