org.reflections.Reflections Java Examples

The following examples show how to use org.reflections.Reflections. 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: DataScopeSqlConfigService.java    From smart-admin with MIT License 7 votes vote down vote up
/**
 * 刷新 所有添加数据范围注解的接口方法配置<class.method,DataScopeSqlConfigDTO></>
 *
 * @return
 */
private Map<String, DataScopeSqlConfigDTO> refreshDataScopeMethodMap() {
    Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(scanPackage)).setScanners(new MethodAnnotationsScanner()));
    Set<Method> methods = reflections.getMethodsAnnotatedWith(DataScope.class);
    for (Method method : methods) {
        DataScope dataScopeAnnotation = method.getAnnotation(DataScope.class);
        if (dataScopeAnnotation != null) {
            DataScopeSqlConfigDTO configDTO = new DataScopeSqlConfigDTO();
            configDTO.setDataScopeType(dataScopeAnnotation.dataScopeType().getType());
            configDTO.setJoinSql(dataScopeAnnotation.joinSql());
            configDTO.setWhereIndex(dataScopeAnnotation.whereIndex());
            dataScopeMethodMap.put(method.getDeclaringClass().getSimpleName() + "." + method.getName(), configDTO);
        }
    }
    return dataScopeMethodMap;
}
 
Example #2
Source File: SetupDao.java    From usergrid with Apache License 2.0 7 votes vote down vote up
public void setup() throws IOException, NoSuchFieldException, IllegalAccessException {
    String key;
    CreateIndexResponse ciResp;

    Reflections reflections = new Reflections("org.apache.usergrid.chop.webapp.dao");
    Set<Class<? extends Dao>> daoClasses = reflections.getSubTypesOf(Dao.class);

    IndicesAdminClient client = elasticSearchClient.getClient().admin().indices();

    for (Class<? extends Dao> daoClass : daoClasses) {

        key = daoClass.getDeclaredField("DAO_INDEX_KEY").get(null).toString();

        if (!client.exists(new IndicesExistsRequest(key)).actionGet().isExists()) {
            ciResp = client.create(new CreateIndexRequest(key)).actionGet();
            if (ciResp.isAcknowledged()) {
                LOG.debug("Index for key {} didn't exist, now created", key);
            } else {
                LOG.debug("Could not create index for key: {}", key);
            }
        } else {
            LOG.debug("Key {} already exists", key);
        }
    }
}
 
Example #3
Source File: PluginUtils.java    From mjprof with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static HashMap<Class, Class> getAllPlugins() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, ClassNotFoundException {
  HashMap<Class, Class> map = new HashMap<>();
  //TODO
  Reflections reflections = new Reflections("com.performizeit");
  Set<Class<?>> annotatedPlugin = reflections.getTypesAnnotatedWith(Plugin.class);

  for (Class cla : annotatedPlugin) {
    if (BasePlugin.class.isAssignableFrom(cla)) {
      invokeGetHelpLine(cla);
      map.put(cla, cla);
    } else {
      System.out.println("ERROR: class " + cla.getName() + " needs to extend BasePlugin child");
    }
  }
  return map;
}
 
Example #4
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 #5
Source File: StateHandleSerializationTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void ensureStateHandlesHaveSerialVersionUID() {
	try {
		Reflections reflections = new Reflections("org.apache.flink");

		// check all state handles

		@SuppressWarnings("unchecked")
		Set<Class<?>> stateHandleImplementations = (Set<Class<?>>) (Set<?>)
				reflections.getSubTypesOf(StateObject.class);

		for (Class<?> clazz : stateHandleImplementations) {
			validataSerialVersionUID(clazz);
		}
	}
	catch (Exception e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example #6
Source File: AnnotationUtils.java    From Alink with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Map<String, Wrapper<BaseDB>> loadDBClasses() {
    Reflections reflections = new Reflections("com.alibaba.alink");
    Map<String, Wrapper<BaseDB>> map = new HashMap<>();
    Set<Class<?>> set = reflections.getTypesAnnotatedWith(DBAnnotation.class);
    for (Class<?> clazz : set) {
        if (!BaseDB.class.isAssignableFrom(clazz)) {
            LOG.error("DB class annotated with @DBAnnotation should be subclass of BaseDB: {}",
                    clazz.getCanonicalName());
            continue;
        }

        DBAnnotation annotation = clazz.getAnnotation(DBAnnotation.class);
        String name = annotation.name();
        boolean hasTimestamp = annotation.hasTimestamp();
        Wrapper<BaseDB> origin = map.put(name, new Wrapper<>((Class<? extends BaseDB>) clazz, hasTimestamp));
        if (origin != null) {
            LOG.error("Multiple DB class with same name {}: {} and {}",
                    name, origin.clazz.getCanonicalName(), clazz.getCanonicalName());
        }
    }

    return ImmutableMap.copyOf(map);
}
 
Example #7
Source File: DiskSelectionFilter.java    From drftpd with GNU General Public License v2.0 6 votes vote down vote up
private void initFilters() {
    CaseInsensitiveHashMap<String, Class<? extends DiskFilter>> filtersMap = new CaseInsensitiveHashMap<>();
    // TODO [DONE] @k2r Load Filters
    Set<Class<? extends DiskFilter>> aFilters = new Reflections("org.drftpd")
            .getSubTypesOf(DiskFilter.class);
    List<Class<? extends DiskFilter>> filters = aFilters.stream()
            .filter(aClass -> !Modifier.isAbstract(aClass.getModifiers())).collect(Collectors.toList());
    try {
        for (Class<? extends DiskFilter> filterClass : filters) {
            String filterName = filterClass.getSimpleName().replace("Filter", "");
            filtersMap.put(filterName, filterClass);
        }
    } catch (Exception e) {
        logger.error("Failed to load plugins for slave extension point 'Handler', possibly the slave"
                + " extension point definition has changed in the plugin.xml", e);
    }
    _filtersMap = filtersMap;
}
 
Example #8
Source File: ConfigJsonCoverageTrackingTests.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void before(){

    //Collect all classes implementing TextConfig interface (i.e., has JSON and YAML conversion support)

    Reflections reflections = new Reflections("ai.konduit");
    Set<Class<? extends TextConfig>> subTypes = reflections.getSubTypesOf(TextConfig.class);

    System.out.println(String.format("All subtypes of %s:", TextConfig.class.getCanonicalName()));
    for(Class<? extends TextConfig> c : subTypes ){
        int mod = c.getModifiers();
        if(Modifier.isAbstract(mod) || Modifier.isInterface(mod))
            continue;
        allClasses.add(c);
        System.out.println(c);
    }
}
 
Example #9
Source File: FontVerter.java    From FontVerter with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void registerFontAdapters() {
    synchronized (adapterLock) {
        if (adapters == null) {
            Reflections reflections = new Reflections("org.mabb.fontverter");
            Set<Class<? extends FVFont>> adapterClasses = reflections.getSubTypesOf(FVFont.class);
            Class[] adapterArr = adapterClasses.toArray(new Class[adapterClasses.size()]);
            adapters = Arrays.asList(adapterArr);

            // CFF always last to try
            Class cffAdapter = null;
            for (Class adapterOn : adapters) {
                if (adapterOn.getSimpleName().contains("CffFont"))
                    cffAdapter = adapterOn;
            }

            int cffIndex = adapters.indexOf(cffAdapter);
            adapters.set(cffIndex, adapters.get(adapters.size() - 1));
            adapters.set(adapters.size() - 1, cffAdapter);

            adapters = removeAbstractClasses(adapters);
        }
    }
}
 
Example #10
Source File: GnarlyGenotyperEngine.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public GnarlyGenotyperEngine(final boolean keepAllSites, final int maxAltAllelesToOutput, final boolean summarizePls, final boolean stripASAnnotations) {
    this.maxAltAllelesToOutput = maxAltAllelesToOutput;
    this.summarizePls = summarizePls;
    this.keepAllSites = keepAllSites;
    this.stripASAnnotations = stripASAnnotations;

    if (!summarizePls) {
        final GenotypeLikelihoodCalculators GLCprovider = new GenotypeLikelihoodCalculators();

        //initialize PL size cache -- HTSJDK cache only goes up to 4 alts, but I need 6
        likelihoodSizeCache = new int[maxAltAllelesToOutput + 1 + 1]; //+1 for ref and +1 so index == numAlleles
        glcCache.add(null); //add a null at index zero because zero alleles (incl. ref) makes no sense
        for (final int numAlleles : IntStream.rangeClosed(1, maxAltAllelesToOutput + 1).boxed().collect(Collectors.toList())) {
            likelihoodSizeCache[numAlleles] = GenotypeLikelihoods.numLikelihoods(numAlleles, ASSUMED_PLOIDY);
            //GL calculator cache is indexed by the total number of alleles, including ref
            glcCache.add(numAlleles, GLCprovider.getInstance(ASSUMED_PLOIDY, numAlleles));
        }
    }

    //TODO: fix weird reflection logging?
    final Reflections reflections = new Reflections("org.broadinstitute.hellbender.tools.walkers.annotator.allelespecific");
    allASAnnotations = reflections.getSubTypesOf(InfoFieldAnnotation.class);
    allASAnnotations.addAll(reflections.getSubTypesOf(AS_StrandBiasTest.class));
    allASAnnotations.addAll(reflections.getSubTypesOf(AS_RankSumTest.class));
}
 
Example #11
Source File: CustomScreenshotScanner.java    From gauge-java with Apache License 2.0 6 votes vote down vote up
public void scan(Reflections reflections) {
    Set<Class<? extends ICustomScreenshotGrabber>> customScreenshotGrabbers = reflections.getSubTypesOf(ICustomScreenshotGrabber.class);

    if (customScreenshotGrabbers.size() > 0) {
        Class<? extends ICustomScreenshotGrabber> customScreenGrabber = customScreenshotGrabbers.iterator().next();
        Logger.debug(String.format("Using %s as custom screenshot grabber", customScreenGrabber.getName()));
        ScreenshotFactory.setCustomScreenshotGrabber(customScreenGrabber);
    }

    Set<Class<? extends CustomScreenshotWriter>> customScreenshotWriters = reflections.getSubTypesOf(CustomScreenshotWriter.class);

    if (customScreenshotWriters.size() > 0) {
        Class<? extends CustomScreenshotWriter> customScreenWriter = customScreenshotWriters.iterator().next();
        Logger.debug(String.format("Using %s as custom screenshot grabber", customScreenWriter.getName()));
        ScreenshotFactory.setCustomScreenshotGrabber(customScreenWriter);
    }
}
 
Example #12
Source File: StepsScannerTest.java    From gauge-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildStepRegistryForExternalReference() {
    HashSet<Method> steps = new HashSet<>();
    steps.add(method2);

    Reflections reflections = mock(Reflections.class);
    when(reflections.getMethodsAnnotatedWith(Step.class)).thenReturn(steps);

    StepRegistry registry = mock(StepRegistry.class);
    String stepTemplateText = "hello world {}";
    when(registry.contains(stepTemplateText)).thenReturn(false);

    new StepsScanner(registry).scan(reflections);

    ArgumentCaptor<StepValue> stepValueArgumentCaptor = ArgumentCaptor.forClass(StepValue.class);
    ArgumentCaptor<Method> methodArgumentCaptor = ArgumentCaptor.forClass(Method.class);
    ArgumentCaptor<Boolean> booleanArgumentCaptor = ArgumentCaptor.forClass(Boolean.class);

    verify(registry, times(1)).addStepImplementation(stepValueArgumentCaptor.capture(), methodArgumentCaptor.capture(), booleanArgumentCaptor.capture());

    assertEquals(stepTemplateText, stepValueArgumentCaptor.getValue().getStepText());
    assertEquals(method2, methodArgumentCaptor.getValue());
    assertTrue(booleanArgumentCaptor.getValue());
}
 
Example #13
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 #14
Source File: ScalaObjectScanner.java    From java-flagz with MIT License 6 votes vote down vote up
static synchronized Set<Object> scanFlagObjects(List<String> packagePrefixes) {

    Reflections reflections = ReflectionsCache.reflectionsForPrefixes(packagePrefixes);
    Set<Object> objects = new HashSet<>();
    for (Class<?> clazz : reflections.getSubTypesOf(FlagContainer.class)) {
      checkDelayedInit(clazz);
      // Scala objects have a MODULE$ static field.
      // http://grahamhackingscala.blogspot.co.uk/2009/11/scala-under-hood-of-hello-world.html
      try {
        Field staticModuleField = clazz.getDeclaredField("MODULE$");
        boolean wasAccessible = staticModuleField.isAccessible();
        if (!wasAccessible) {
          staticModuleField.setAccessible(true);
        }
        objects.add(staticModuleField.get(null));  // null is fine, this is a static field.
        staticModuleField.setAccessible(wasAccessible);
      } catch (NoSuchFieldException | IllegalAccessException exception) {
        throw new IllegalArgumentException(
            "Error reflecting on Scala object. " + clazz.getCanonicalName(), exception);
      }
    }
    return objects;
  }
 
Example #15
Source File: StepsScannerTest.java    From gauge-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildStepRegistryUpdatesReflectedMethod() {
    HashSet<Method> steps = new HashSet<>();
    steps.add(method2);
    String expectedMethodName = method2.getName();

    StepRegistryEntry entry = new StepRegistryEntry();
    entry.setFullyQualifiedName(method2.getName()); // simulate static scan of this method

    Reflections reflections = mock(Reflections.class);
    when(reflections.getMethodsAnnotatedWith(Step.class)).thenReturn(steps);

    StepRegistry registry = mock(StepRegistry.class);
    String stepTemplateText = "hello world {}";
    when(registry.contains(stepTemplateText)).thenReturn(true);
    when(registry.getForCurrentProject(stepTemplateText, method2)).thenReturn(entry);

    new StepsScanner(registry).scan(reflections);

    assertNotNull(entry.getMethodInfo());
    assertEquals(expectedMethodName, entry.getMethodInfo().getName());
}
 
Example #16
Source File: ScanPrinterUtils.java    From disconf with Apache License 2.0 6 votes vote down vote up
/**
 * 打印出StoreMap的数据
 */
public static void printStoreMap(Reflections reflections) {

    LOGGER.info("Now we will print store map......");

    Store store = reflections.getStore();
    Map<String/* indexName */, Multimap<String, String>> storeMap = store.getStoreMap();
    for (String indexName : storeMap.keySet()) {

        LOGGER.info("====================================");
        LOGGER.info("indexName:" + indexName);

        Multimap<String, String> multimap = storeMap.get(indexName);

        for (String firstName : multimap.keySet()) {
            Collection<String> lastNames = multimap.get(firstName);
            LOGGER.info("\t\t" + firstName + ": " + lastNames);
        }

    }
}
 
Example #17
Source File: GlyphedModal.java    From ure with 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 #18
Source File: RenderFactory.java    From gecco with MIT License 5 votes vote down vote up
public RenderFactory(Reflections reflections) {
	CustomFieldRenderFactory customFieldRenderFactory = new CustomFieldRenderFactory(reflections);
	renders = new HashMap<RenderType, Render>();
	
	AbstractRender htmlRender = createHtmlRender();
	htmlRender.setCustomFieldRenderFactory(customFieldRenderFactory);
	
	AbstractRender jsonRender = createJsonRender();
	jsonRender.setCustomFieldRenderFactory(customFieldRenderFactory);
	
	renders.put(RenderType.HTML, htmlRender);
	renders.put(RenderType.JSON, jsonRender);
}
 
Example #19
Source File: ConfigManager.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Load all connected handlers.
 */
private void loadConfigHandlers() {
    HashMap<String, ConfigContainer> directivesMap = new HashMap<>();

    Set<Class<? extends ExtendedPermissions>> extendedPermissions = new Reflections("org.drftpd").getSubTypesOf(ExtendedPermissions.class);
    try {
        for (Class<? extends ExtendedPermissions> extendedPermission : extendedPermissions) {
            ExtendedPermissions perms = extendedPermission.getConstructor().newInstance();
            for (PermissionDefinition permission : perms.permissions()) {
                Class<? extends ConfigHandler> handler = permission.getHandler();
                String directive = permission.getDirective();
                if (directivesMap.containsKey(directive)) {
                    logger.debug("A handler for {} already loaded, check your plugin.xml's", directive);
                    continue;
                }
                String method = permission.getMethod();
                ConfigHandler handlerInstance = handler.getConstructor().newInstance();
                Method methodInstance = handler.getMethod(method, String.class, StringTokenizer.class);
                ConfigContainer cc = new ConfigContainer(handlerInstance, methodInstance);
                directivesMap.put(directive, cc);
                logger.debug("Added directive {} to our directives map", directive);
            }
        }
        // Finally set the map once we processed all of the classes
        _directivesMap = directivesMap;
    } catch (Exception e) {
        logger.error("Failed to load plugins for master extension point 'ExtendedPermissions. The map is left as is or empty", e);
    }
    logger.debug("Loaded {} ExtendedPermissions classes", _directivesMap.size());
}
 
Example #20
Source File: OWLSchemaPersistingManagerTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testContradictoryExistingSchema() throws Exception {
    Anno4j anno4j = new Anno4j();

    Transaction setupTransaction = anno4j.createTransaction();
    setupTransaction.begin();
    setupTransaction.getConnection().prepareUpdate("INSERT DATA {" +
            "  <http://example.de/#validly_annotated_person> rdfs:subClassOf _:restr . " +
            "  _:restr a owl:Restriction . " +
            "  _:restr owl:onProperty <http://example.de/#id> . " +
            "  _:restr owl:minCardinality '42'^^xsd:nonNegativeInteger . " +
            "}").execute();
    setupTransaction.commit();

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

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

    boolean exceptionThrown = false;
    try {
        persistingManager.persistSchema(types);
    } catch (SchemaPersistingManager.ContradictorySchemaException e) {
        exceptionThrown = true;
    }
    assertTrue(exceptionThrown);
}
 
Example #21
Source File: EbeanEntities.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
public static Set<Class> getEntities() {
    Reflections reflections = new Reflections("bo.gotthardt.model");
    Set<Class<?>> entities = reflections.getTypesAnnotatedWith(Entity.class);
    Set<Class<?>> embeddables = reflections.getTypesAnnotatedWith(Embeddable.class);

    return Sets.union(embeddables, entities);
}
 
Example #22
Source File: AnnotationUtils.java    From Alink with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static Table<String, IOType, Wrapper<AlgoOperator>> loadIoOpClasses() {
    Reflections reflections = new Reflections("com.alibaba.alink");
    Table<String, IOType, Wrapper<AlgoOperator>> table = HashBasedTable.create();
    for (Class<?> clazz : reflections.getTypesAnnotatedWith(IoOpAnnotation.class)) {
        if (!AlgoOperator.class.isAssignableFrom(clazz)) {
            LOG.error("Class annotated with @IoOpAnnotation should be subclass of AlgoOperator: {}",
                    clazz.getCanonicalName());
            continue;
        }

        IoOpAnnotation annotation = clazz.getAnnotation(IoOpAnnotation.class);
        String name = annotation.name();
        IOType ioType = annotation.ioType();
        boolean hasTimestamp = annotation.hasTimestamp();

        Wrapper<AlgoOperator> origin = table.put(name, ioType,
                new Wrapper<>((Class<? extends AlgoOperator>) clazz, hasTimestamp));


        if (origin != null) {
            LOG.error("Multiple IO Operator class with same name {} and IOType: {}: {} and {}",
                    name, ioType, origin.clazz.getCanonicalName(), clazz.getCanonicalName());
        }
    }

    return ImmutableTable.copyOf(table);
}
 
Example #23
Source File: ClasspathConfigSource.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Scan the classpath for {@link #classpathRootName} and return all resources under it.
 * {@inheritDoc}
 * @see org.apache.gobblin.config.store.deploy.DeployableConfigSource#getDeployableConfigPaths()
 */
private Set<String> getDeployableConfigPaths() {

  ConfigurationBuilder cb =
      new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader()).setScanners(new ResourcesScanner())
          .filterInputsBy(new FilterBuilder().include(String.format(".*%s.*", this.classpathRootName)));

  Reflections reflections = new Reflections(cb);
  Pattern pattern = Pattern.compile(".*");

  return reflections.getResources(pattern);
}
 
Example #24
Source File: UpgradeActions.java    From irontest with Apache License 2.0 5 votes vote down vote up
/**
 * Result is sorted by fromVersion.
 * @param oldVersion
 * @param newVersion
 * @param subPackage
 * @param prefix
 * @param extension
 * @return
 */
private List<ResourceFile> getApplicableUpgradeResourceFiles(DefaultArtifactVersion oldVersion,
                                                             DefaultArtifactVersion newVersion, String subPackage,
                                                             String prefix, String extension) {
    List<ResourceFile> result = new ArrayList<>();

    Reflections reflections = new Reflections(
            getClass().getPackage().getName() + "." + subPackage, new ResourcesScanner());
    Set<String> upgradeFilePaths =
            reflections.getResources(Pattern.compile(prefix + ".*\\." + extension));
    for (String upgradeFilePath: upgradeFilePaths) {
        String[] upgradeFilePathFragments = upgradeFilePath.split("/");
        String upgradeFileName = upgradeFilePathFragments[upgradeFilePathFragments.length - 1];
        String[] versionsInUpgradeFileName = upgradeFileName.replace(prefix + "_", "").
                replace("." + extension, "").split("_To_");
        DefaultArtifactVersion fromVersionInUpgradeFileName = new DefaultArtifactVersion(
                versionsInUpgradeFileName[0].replace("_", "."));
        DefaultArtifactVersion toVersionInUpgradeFileName = new DefaultArtifactVersion(
                versionsInUpgradeFileName[1].replace("_", "."));
        if (fromVersionInUpgradeFileName.compareTo(oldVersion) >= 0 &&
                toVersionInUpgradeFileName.compareTo(newVersion) <=0) {
            ResourceFile upgradeResourceFile = new ResourceFile();
            upgradeResourceFile.setResourcePath(upgradeFilePath);
            upgradeResourceFile.setFromVersion(fromVersionInUpgradeFileName);
            upgradeResourceFile.setToVersion(toVersionInUpgradeFileName);
            result.add(upgradeResourceFile);
        }
    }

    Collections.sort(result);

    return result;
}
 
Example #25
Source File: ConfigurationManagerImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void generateConstantPythonClass(StringBuilder sb, List<String> basePkgs) {
    Reflections reflections = Platform.getReflections();
    Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(PythonClass.class);
    for (Class<?> clazz : annotated.stream().sorted((c1, c2) -> {
        return c1.getSimpleName().compareTo(c2.getSimpleName());
    }).collect(Collectors.toList())) {
        try {
            generateConstantFromClassField(sb, clazz);
        } catch (Exception e) {
            logger.warn(String.format("Unable to generate python class for %s", clazz.getName()), e);
        }
    }
}
 
Example #26
Source File: StaticWeavingTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testStaticWeaving() {
    // first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
    Reflections reflections = new Reflections(getClass().getPackage().getName());
    Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
    Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
    Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);

    // next, let's assert that they have been statically weaved
    assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}
 
Example #27
Source File: JaxRSScanner.java    From swagger-maven-plugin with 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 #28
Source File: AvroTestTools.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
static Set<String> getJsonFileSetByResourceRootName(String baseResource) {
  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .forPackages(baseResource)
      .filterInputsBy(name -> name.startsWith(baseResource))
      .setScanners(new ResourcesScanner()));

  return reflections.getResources(url -> url.endsWith(".json"));
}
 
Example #29
Source File: SVCHandler.java    From ARMStrong with Mozilla Public License 2.0 5 votes vote down vote up
public void findIOSyscalls() {
	Reflections reflections = new Reflections("projetarm_v2.simulator.core.syscalls.io");

	Set<Class<? extends SVCIOCall>> calls = reflections.getSubTypesOf(SVCIOCall.class);
	
	for (Class<? extends SVCIOCall> classCall : calls) {
		try {
			SVCCall call = (SVCIOCall)(classCall.getDeclaredConstructor(Cpu.class, FileDescriptors.class).newInstance(this.cpu, this.fileDescriptors));
			this.interruptVector.put(call.getSvcNumber(),call);
		} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {}
	}
}
 
Example #30
Source File: ConsumerFinder.java    From rpcx-java with Apache License 2.0 5 votes vote down vote up
public Set<String> find(String consumerPackage) {
    Reflections reflections = new Reflections(consumerPackage);
    //不包括实现类
    Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(Consumer.class,true);
    return  classesList.stream().map(it->{
        Consumer consumer = it.getAnnotation(Consumer.class);
        return consumer.impl();
    }).collect(Collectors.toSet());
}