org.reflections.util.FilterBuilder Java Examples

The following examples show how to use org.reflections.util.FilterBuilder. 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: 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 #2
Source File: RoleClassLoader.java    From anno4j with Apache License 2.0 6 votes vote down vote up
private void scanConceptsWithReflections() throws ObjectStoreConfigException {
    logger.debug("Search for concepts with reflections");
    Set<URL> classpath = new HashSet<>();
    classpath.addAll(ClasspathHelper.forClassLoader());
    classpath.addAll(ClasspathHelper.forJavaClassPath());
    classpath.addAll(ClasspathHelper.forManifest());
    classpath.addAll(ClasspathHelper.forPackage(""));
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(classpath)
.useParallelExecutor()
.filterInputsBy(FilterBuilder.parsePackages("-java, -javax, -sun, -com.sun"))
            .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));

    Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Iri.class, true);
    logger.debug("Search for concepts with reflections resulted in " + annotated.size() + " classes");
    for (Class clazz : annotated) {
        logger.debug("Found concept class: " + clazz.getCanonicalName());
        roleMapper.addConcept(clazz);
    }
}
 
Example #3
Source File: 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 #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: ClasspathFunctionResolverTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidStellarClass() {
  StellarFunction goodFunc = mock(StellarFunction.class);
  StellarFunction badFunc = mock(StellarFunction.class);
  ClasspathFunctionResolver resolver = new ClasspathFunctionResolver() {
    @Override
    protected Iterable<Class<?>> getStellarClasses(ClassLoader cl) {
      return ImmutableList.of(goodFunc.getClass(), badFunc.getClass());
    }

    @Override
    protected boolean includeClass(Class<?> c, FilterBuilder filterBuilder) {
      if(c != goodFunc.getClass()) {
        throw new LinkageError("failed!");
      }
      return true;
    }
  };
  Set<Class<? extends StellarFunction>> funcs = resolver.resolvables();
  assertEquals(1, funcs.size());
  assertEquals(goodFunc.getClass(), Iterables.getFirst(funcs, null));
}
 
Example #6
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 #7
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 #8
Source File: ClasspathScanner.java    From gauge-java with Apache License 2.0 5 votes vote down vote up
private boolean shouldScan(String s) {
    final String packagesToScan = System.getenv(PACKAGE_TO_SCAN);
    if (packagesToScan == null || packagesToScan.isEmpty()) {
        return new FilterBuilder().include(".+\\.class").apply(s);
    }
    final String[] packages = packagesToScan.split(",");
    for (String packageToScan : packages) {
        String regex = String.format(".?\\.??%s\\..+\\.class", packageToScan);
        if (new FilterBuilder().include(regex).apply(s)) {
            return true;
        }
    }
    return false;
}
 
Example #9
Source File: ReflectionScanner.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** as {@link #ReflectionScanner(Iterable, String, Predicate, ClassLoader...)} using the prefix as the base for the filter */
public ReflectionScanner(
        final Iterable<URL> urlsToScan, 
        final String optionalPrefix,
        final ClassLoader ...classLoaders) {
    this(urlsToScan, optionalPrefix, 
        Strings.isNonEmpty(optionalPrefix) ? new FilterBuilder.Include(FilterBuilder.prefix(optionalPrefix)) : null,
        classLoaders);
}
 
Example #10
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 #11
Source File: DocStringExtractor.java    From armeria with Apache License 2.0 5 votes vote down vote up
private Map<String, String> getAllDocStrings0(ClassLoader classLoader) {
    final Configuration configuration = new ConfigurationBuilder()
            .filterInputsBy(new FilterBuilder().includePackage(path))
            .setUrls(ClasspathHelper.forPackage(path, classLoader))
            .addClassLoader(classLoader)
            .setScanners(new ResourcesScanner());
    if (configuration.getUrls() == null || configuration.getUrls().isEmpty()) {
        // No resource folders were found.
        return ImmutableMap.of();
    }

    final Reflections reflections = new Reflections(configuration);
    final Store store = reflections.getStore();
    if (!store.keySet().contains(ResourcesScanner.class.getSimpleName())) {
        // No resources were found.
        return ImmutableMap.of();
    }

    final Map<String, byte[]> files = reflections
            .getResources(this::acceptFile).stream()
            .map(f -> {
                try {
                    final URL url = classLoader.getResource(f);
                    if (url == null) {
                        throw new IllegalStateException("not found: " + f);
                    }
                    return Maps.immutableEntry(f, Resources.toByteArray(url));
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            })
            .collect(toImmutableMap(Entry::getKey, Entry::getValue));

    return getDocStringsFromFiles(files);
}
 
Example #12
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 #13
Source File: ClasspathScanner.java    From valdr-bean-validation with MIT License 5 votes vote down vote up
private Predicate<String> buildPackagePredicates() {
  FilterBuilder filterBuilder = new FilterBuilder();
  // Include package names
  for (String packageName : options.getModelPackages()) {
    filterBuilder.include(FilterBuilder.prefix(packageName));
  }
  // Exclude class names
  for (String excludedClassName : options.getExcludedClasses()) {
    filterBuilder.exclude("^" + StringUtils.replace(excludedClassName, ".", "\\.") + "\\.class$");
  }
  return filterBuilder;
}
 
Example #14
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 #15
Source File: ClassTools.java    From spring-boot-starter-micro-job with 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 #16
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 #17
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 #18
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 #19
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 #20
Source File: TypesafeConfigModule.java    From typesafeconfig-guice with Apache License 2.0 5 votes vote down vote up
public static Reflections createPackageScanningReflections(String packageNamePrefix){
	ConfigurationBuilder configBuilder =
			new ConfigurationBuilder()
					.filterInputsBy(new FilterBuilder().includePackage(packageNamePrefix))
					.setUrls(ClasspathHelper.forPackage(packageNamePrefix))
					.setScanners(
							new TypeAnnotationsScanner(),
							new MethodParameterScanner(),
							new MethodAnnotationsScanner(),
							new FieldAnnotationsScanner()
					);
	return new Reflections(configBuilder);
}
 
Example #21
Source File: ConnectorGenerator.java    From funktion-connectors with Apache License 2.0 5 votes vote down vote up
private CamelCatalog createCamelCatalog() throws IOException{
    CamelCatalog result = new DefaultCamelCatalog(true);
    //add funktion camel components

    Predicate<String> filter = new FilterBuilder().includePackage("io.fabric8.funktion.camel");
    Reflections resources = new Reflections(new ConfigurationBuilder()
                                                .filterInputsBy(filter)
                                                .setScanners(new ResourcesScanner())
                                                .setUrls(ClasspathHelper.forJavaClassPath()));


    Set<String> jsonFiles = resources.getResources(Pattern.compile(".*\\.json"));


    LOG.info("Processing Funktion Camel components ...");
    for (String jsonFile: jsonFiles){
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(jsonFile);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(inputStream);
        JsonNode component = root.path("component");
        if (!component.isMissingNode()) {
            String scheme = component.path("scheme").asText();
            String componentName = component.path("javaType").asText();
            result.addComponent(scheme,componentName);
            LOG.info("Processed component " + scheme);
        }else{
            LOG.error("Failed to find Component for " + jsonFile);
        }
    }
    return result;
}
 
Example #22
Source File: TestDataUtils.java    From kafka-connect-spooldir with Apache License 2.0 5 votes vote down vote up
public static <T extends NamedTest> List<T> loadJsonResourceFiles(String packageName, Class<T> cls) throws IOException {
    Preconditions.checkNotNull(packageName, "packageName cannot be null");
    log.info("packageName = {}", packageName);
//    Preconditions.checkState(packageName.startsWith("/"), "packageName must start with a /.");
    Reflections reflections = new Reflections(packageName, new ResourcesScanner());
    Set<String> resources = reflections.getResources(new FilterBuilder.Include("^.*\\.json$"));
    List<T> datas = new ArrayList<T>(resources.size());
    Path packagePath = Paths.get("/" + packageName.replace(".", "/"));
    for (String resource : resources) {
      log.trace("Loading resource {}", resource);
      Path resourcePath = Paths.get("/" + resource);
      Path relativePath = packagePath.relativize(resourcePath);
      File resourceFile = new File("/" + resource);
      T data;
      try (InputStream inputStream = cls.getResourceAsStream(resourceFile.getAbsolutePath())) {
        data = ObjectMapperFactory.INSTANCE.readValue(inputStream, cls);
      } catch (IOException ex) {
        if (log.isErrorEnabled()) {
          log.error("Exception thrown while loading {}", resourcePath, ex);
        }
        throw ex;
      }

      if (null != relativePath.getParent()) {
        data.path(relativePath);
      } else {
        data.path(relativePath);
      }
      datas.add(data);
    }
    return datas;
  }
 
Example #23
Source File: TestDataUtils.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
public static <T extends NamedTest> List<T> loadJsonResourceFiles(String packageName, Class<T> cls) throws IOException {
  Preconditions.checkNotNull(packageName, "packageName cannot be null");
  Reflections reflections = new Reflections(packageName, new ResourcesScanner());
  Set<String> resources = reflections.getResources(new FilterBuilder.Include(".*"));
  List<T> datas = new ArrayList<>(resources.size());
  Path packagePath = Paths.get("/" + packageName.replace(".", "/"));
  for (String resource : resources) {
    log.trace("Loading resource {}", resource);
    Path resourcePath = Paths.get("/" + resource);
    Path relativePath = packagePath.relativize(resourcePath);
    File resourceFile = new File("/" + resource);
    T data;
    try (InputStream inputStream = cls.getResourceAsStream(resourceFile.getAbsolutePath())) {
      data = ObjectMapperFactory.INSTANCE.readValue(inputStream, cls);
    } catch (IOException ex) {
      if (log.isErrorEnabled()) {
        log.error("Exception thrown while loading {}", resourcePath, ex);
      }
      throw ex;
    }
    String nameWithoutExtension = Files.getNameWithoutExtension(resource);
    if (null != relativePath.getParent()) {
      String parentName = relativePath.getParent().getFileName().toString();
      data.testName(parentName + "/" + nameWithoutExtension);
    } else {
      data.testName(nameWithoutExtension);
    }
    datas.add(data);
  }
  return datas;
}
 
Example #24
Source File: DemoLauncher.java    From coordination_oru with GNU General Public License v3.0 5 votes vote down vote up
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 #25
Source File: ClassUtils.java    From jkes with 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 File: Civs.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
private void instantiateSingletons() {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    FilterBuilder filterBuilder = new FilterBuilder();
    configurationBuilder.addUrls(ClasspathHelper.forPackage("org.redcastlemedia.multitallented.civs"));
    filterBuilder.includePackage("org.redcastlemedia.multitallented.civs")
            .excludePackage("org.redcastlemedia.multitallented.civs.dynmaphook")
            .excludePackage("org.redcastlemedia.multitallented.civs.placeholderexpansion");
    configurationBuilder.filterInputsBy(filterBuilder);
    Reflections reflections = new Reflections(configurationBuilder);
    Set<Class<?>> classes = reflections.getTypesAnnotatedWith(CivsSingleton.class);
    List<Class<?>> classList = new ArrayList<>(classes);
    classList.sort(new Comparator<Class<?>>() {
        @Override
        public int compare(Class<?> o1, Class<?> o2) {
            return o1.getAnnotation(CivsSingleton.class).priority().compareTo(o2.getAnnotation(CivsSingleton.class).priority());
        }
    });
    for (Class<?> currentSingleton : classList) {
        try {
            Method method = currentSingleton.getMethod("getInstance");
            if (method != null) {
                method.invoke(currentSingleton);
            }
        } catch (Exception e) {

        }
    }
}
 
Example #27
Source File: DecisionDiscovery.java    From jdmn with Apache License 2.0 5 votes vote down vote up
public Set<Class<?>> discover(String packagePrefix) {
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage(packagePrefix))
            .filterInputsBy(new FilterBuilder().includePackage(packagePrefix))
    );
    return reflections.getTypesAnnotatedWith(DRGElement.class);
}
 
Example #28
Source File: ClassTools.java    From api-boot with 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 #29
Source File: ReflectionBasedUdfResolver.java    From samza with Apache License 2.0 4 votes vote down vote up
public ReflectionBasedUdfResolver(Config udfConfig) {
  // Searching the entire classpath to discover the subtypes of SamzaSqlUdf is expensive. To reduce the search space,
  // the search is limited to the set of package prefixes defined in the configuration.
  String samzaSqlUdfPackagePrefix = udfConfig.getOrDefault(CONFIG_PACKAGE_PREFIX, "org.apache.samza");
  String samzaSqlUdfFilter = udfConfig.getOrDefault(CONFIG_PACKAGE_FILTER, ".*");

  // 1. Build the reflections instance  with appropriate configuration.
  ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
  // Include only the SamzaSqlUDFClass implementations defined in the package prefix.
  configurationBuilder.forPackages(samzaSqlUdfPackagePrefix.split(","));
  configurationBuilder.filterInputsBy(new FilterBuilder().includePackage(samzaSqlUdfFilter));
  // Manually add the resource urls if they're configured.
  configurationBuilder.addUrls(getUrls(udfConfig));

  configurationBuilder.addClassLoader(Thread.currentThread().getContextClassLoader());
  Reflections reflections = new Reflections(configurationBuilder);

  // 2. Get all the sub-types of SamzaSqlUdf.
  Set<Class<?>> typesAnnotatedWithSamzaSqlUdf = reflections.getTypesAnnotatedWith(SamzaSqlUdf.class);

  for (Class<?> udfClass : typesAnnotatedWithSamzaSqlUdf) {
    // 3. Get all the methods that are annotated with SamzaSqlUdfMethod
    List<Method> methodsAnnotatedWithSamzaSqlMethod = MethodUtils.getMethodsListWithAnnotation(udfClass, SamzaSqlUdfMethod.class);

    if (methodsAnnotatedWithSamzaSqlMethod.isEmpty()) {
      String msg = String.format("Udf class: %s doesn't have any methods annotated with: %s", udfClass.getName(), SamzaSqlUdfMethod.class.getName());
      LOG.error(msg);
      throw new SamzaException(msg);
    }

    SamzaSqlUdf sqlUdf = udfClass.getAnnotation(SamzaSqlUdf.class);
    // 4. If the udf is enabled, then add the udf information of the methods to the udfs list.
    if (sqlUdf.enabled()) {
      String udfName = sqlUdf.name();
      methodsAnnotatedWithSamzaSqlMethod.forEach(method -> {
        SamzaSqlUdfMethod samzaSqlUdfMethod = method.getAnnotation(SamzaSqlUdfMethod.class);
        List<SamzaSqlFieldType> params = Arrays.asList(samzaSqlUdfMethod.params());
        udfs.add(new UdfMetadata(udfName, sqlUdf.description(), method, udfConfig.subset(udfName + "."), params,
                samzaSqlUdfMethod.returns(), samzaSqlUdfMethod.disableArgumentCheck()));
      });
    }
  }
}
 
Example #30
Source File: Anno4j.java    From anno4j with Apache License 2.0 4 votes vote down vote up
public Anno4j(Repository repository, IDGenerator idGenerator, URI defaultContext, boolean persistSchemaAnnotations, Set<URL> additionalClasses) throws RepositoryConfigException, RepositoryException {
    this.idGenerator = idGenerator;
    this.defaultContext = defaultContext;

    classpath = new HashSet<>();
    classpath.addAll(ClasspathHelper.forClassLoader());
    classpath.addAll(ClasspathHelper.forJavaClassPath());
    classpath.addAll(ClasspathHelper.forManifest());
    classpath.addAll(ClasspathHelper.forPackage(""));
    if(additionalClasses != null) {
        classpath.addAll(additionalClasses);
    }

    Reflections annotatedClasses = new Reflections(new ConfigurationBuilder()
            .setUrls(classpath)
            .useParallelExecutor()
            .filterInputsBy(FilterBuilder.parsePackages("-java, -javax, -sun, -com.sun"))
            .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner(), new MethodAnnotationsScanner(), new FieldAnnotationsScanner()));

    // Bugfix: Searching for Reflections creates a lot ot Threads, that are not closed at the end by themselves,
    // so we close them manually.
    annotatedClasses.getConfiguration().getExecutorService().shutdown();

    // Index conceptsByIri with @Iri annotation:
    indexConcepts(annotatedClasses);

    // find classes with @Partial annotation
    this.partialClasses = annotatedClasses.getTypesAnnotatedWith(Partial.class, true);

    scanForEvaluators(annotatedClasses);

    if(!repository.isInitialized()) {
        repository.initialize();
    }

    this.setRepository(repository, additionalClasses, additionalClasses);

    // Persist schema information to repository:
    if(persistSchemaAnnotations) {
        persistSchemaAnnotations(annotatedClasses);
    }
}