Java Code Examples for org.reflections.util.FilterBuilder

The following examples show how to use org.reflections.util.FilterBuilder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
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 2
Source Project: Java2PlantUML   Source File: Parser.java    License: Apache License 2.0 6 votes vote down vote up
private static Collection<? extends Class<?>> getPackageTypes(String packageToPase, Collection<URL> urls) {
    Set<Class<?>> classes = new HashSet<>();
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setScanners(new SubTypesScanner(false /* exclude Object.class */), new ResourcesScanner(), new TypeElementsScanner())
            .setUrls(urls)
            .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageToPase)).exclude("java.*")));

    Set<String> types;
    types = reflections.getStore().get("TypeElementsScanner").keySet();
    for (String type: types) {
        Class<?> aClass = TypesHelper.loadClass(type, CLASS_LOADER);
        boolean wantedElement = StringUtils.startsWith(type, packageToPase);
        if (null != aClass && wantedElement) {
            logger.log(Level.INFO, "looking up for type: " + type);
            classes.add(aClass);
        }
    }
    return classes;
}
 
Example 3
Source Project: anno4j   Source File: RoleClassLoader.java    License: Apache License 2.0 6 votes vote down vote up
private void scanConceptsWithReflections() throws ObjectStoreConfigException {
    logger.debug("Search for concepts with reflections");
    Set<URL> classpath = new HashSet<>();
    classpath.addAll(ClasspathHelper.forClassLoader());
    classpath.addAll(ClasspathHelper.forJavaClassPath());
    classpath.addAll(ClasspathHelper.forManifest());
    classpath.addAll(ClasspathHelper.forPackage(""));
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(classpath)
.useParallelExecutor()
.filterInputsBy(FilterBuilder.parsePackages("-java, -javax, -sun, -com.sun"))
            .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));

    Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Iri.class, true);
    logger.debug("Search for concepts with reflections resulted in " + annotated.size() + " classes");
    for (Class clazz : annotated) {
        logger.debug("Found concept class: " + clazz.getCanonicalName());
        roleMapper.addConcept(clazz);
    }
}
 
Example 4
Source Project: metron   Source File: ClasspathFunctionResolverTest.java    License: 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 5
Source Project: robe   Source File: GuiceBundle.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a {@link org.reflections.Reflections} with the given packages (configuration)
 *
 * @param scanPackages
 */
private void createReflections(String[] scanPackages) {
    if (scanPackages.length < 1) {
        LOGGER.warn("No package defined in configuration (scanPackages)!");
        return;
    }
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    FilterBuilder filterBuilder = new FilterBuilder();
    for (String packageName : scanPackages) {
        configurationBuilder.addUrls(ClasspathHelper.forPackage(packageName));
        filterBuilder.include(FilterBuilder.prefix(packageName));
    }

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

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

    FilterBuilder filter = new FilterBuilder();

    Set<URL> urls = new HashSet();

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

    return new Reflections(new ConfigurationBuilder()
            .addUrls(urls)
            .filterInputsBy(filter)
            .setScanners(new TypeAnnotationsScanner(), new SubTypesScanner()));
}
 
Example 7
Source Project: spring-boot-starter-micro-job   Source File: ClassTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定package下的接口实现类
 *
 * @param scannerPackage 扫描的package
 * @return 实现类集合
 */
public static Set<Class<? extends JobTrigger>> getJobs(String scannerPackage) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setScanners(new TypeAnnotationsScanner(), new SubTypesScanner());
    configurationBuilder.filterInputsBy(new FilterBuilder().includePackage(scannerPackage));
    configurationBuilder.addUrls(ClasspathHelper.forPackage(scannerPackage));
    Reflections reflections = new Reflections(scannerPackage);
    return reflections.getSubTypesOf(JobTrigger.class);
}
 
Example 8
Source Project: api-boot   Source File: ClassTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 初始化反射对象
 *
 * @param scannerPackage 扫描的package
 * @return 反射对象
 */
static Reflections initReflections(String scannerPackage) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setScanners(new TypeAnnotationsScanner(), new SubTypesScanner());
    configurationBuilder.filterInputsBy(new FilterBuilder().includePackage(scannerPackage));
    configurationBuilder.addUrls(ClasspathHelper.forPackage(scannerPackage));
    return new Reflections(scannerPackage);
}
 
Example 9
Source Project: jdmn   Source File: DecisionDiscovery.java    License: 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 10
Source Project: Civs   Source File: Civs.java    License: 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 11
Source Project: jkes   Source File: ClassUtils.java    License: Apache License 2.0 5 votes vote down vote up
static Set<Class<?>> getClasses(String packageName) {
    List<ClassLoader> classLoadersList = new LinkedList<>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

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

    Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);
    return classes;
}
 
Example 12
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 13
Source Project: connect-utils   Source File: TestDataUtils.java    License: 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 14
Source Project: kafka-connect-spooldir   Source File: TestDataUtils.java    License: 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 15
Source Project: funktion-connectors   Source File: ConnectorGenerator.java    License: 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 16
Source Project: typesafeconfig-guice   Source File: TypesafeConfigModule.java    License: 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 17
Source Project: hbase-tools   Source File: Manager.java    License: 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 Project: hbase-tools   Source File: Manager.java    License: 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 Project: hbase-tools   Source File: Manager.java    License: 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 Project: hbase-tools   Source File: Manager.java    License: 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 21
Source Project: hbase-tools   Source File: Manager.java    License: 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 22
Source Project: armeria   Source File: DocStringExtractor.java    License: 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 23
Source Project: brooklyn-server   Source File: ReflectionScanner.java    License: 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 24
Source Project: gauge-java   Source File: ClasspathScanner.java    License: 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 25
Source Project: gauge-java   Source File: ParameterParsingChain.java    License: 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 26
Source Project: arangodb-java-driver   Source File: NativeImageHelper.java    License: 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 27
Source Project: incubator-gobblin   Source File: ClasspathConfigSource.java    License: 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 28
Source Project: valdr-bean-validation   Source File: ClasspathScanner.java    License: 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 29
Source Project: Bats   Source File: ClassPathScanner.java    License: Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param pathsToScan the locations to scan for .class files
 * @param packagePrefixes the whitelist of package prefixes to scan
 * @param parentResult if there was a prescan, its result
 * @return the merged scan
 */
static ScanResult scan(Collection<URL> pathsToScan, Collection<String> packagePrefixes, Collection<String> scannedClasses, Collection<String> scannedAnnotations, ScanResult parentResult) {
  Stopwatch watch = Stopwatch.createStarted();
  try {
    AnnotationScanner annotationScanner = new AnnotationScanner(scannedAnnotations);
    SubTypesScanner subTypesScanner = new SubTypesScanner(parentResult.getImplementations());
    if (packagePrefixes.size() > 0) {
      final FilterBuilder filter = new FilterBuilder();
      for (String prefix : packagePrefixes) {
        filter.include(FilterBuilder.prefix(prefix));
      }
      ConfigurationBuilder conf = new ConfigurationBuilder()
          .setUrls(pathsToScan)
          .setMetadataAdapter(METADATA_ADAPTER) // Scanners depend on this
          .filterInputsBy(filter)
          .setScanners(annotationScanner, subTypesScanner);

      // scans stuff, but don't use the funky storage layer
      new Reflections(conf);
    }
    List<ParentClassDescriptor> implementations = new ArrayList<>();
    for (String baseTypeName: scannedClasses) {
      implementations.add(
          new ParentClassDescriptor(
              baseTypeName,
              new ArrayList<>(subTypesScanner.getChildrenOf(baseTypeName))));
    }
    List<AnnotatedClassDescriptor> annotated = annotationScanner.getAnnotatedClasses();
    verifyClassUnicity(annotated, pathsToScan);
    return new ScanResult(
        packagePrefixes,
        scannedClasses,
        scannedAnnotations,
        annotated,
        implementations);
  } finally {
    logger.info(
        format("Scanning packages %s in locations %s took %dms",
            packagePrefixes, pathsToScan, watch.elapsed(MILLISECONDS)));
  }
}
 
Example 30
Source Project: dremio-oss   Source File: ClassPathScanner.java    License: Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param pathsToScan the locations to scan for .class files
 * @param packagePrefixes the whitelist of package prefixes to scan
 * @param parentResult if there was a prescan, its result
 * @return the merged scan
 */
static ScanResult scan(Collection<URL> pathsToScan, Collection<String> packagePrefixes, Collection<String> scannedClasses, Collection<String> scannedAnnotations, ScanResult parentResult) {
  Stopwatch watch = Stopwatch.createStarted();
  try {
    AnnotationScanner annotationScanner = new AnnotationScanner(scannedAnnotations);
    SubTypesScanner subTypesScanner = new SubTypesScanner(parentResult.getImplementations());
    if (packagePrefixes.size() > 0) {
      final FilterBuilder filter = new FilterBuilder();
      for (String prefix : packagePrefixes) {
        filter.include(FilterBuilder.prefix(prefix));
      }
      ConfigurationBuilder conf = new ConfigurationBuilder()
          .setUrls(pathsToScan)
          .setMetadataAdapter(METADATA_ADAPTER) // Scanners depend on this
          .filterInputsBy(filter)
          .setScanners(annotationScanner, subTypesScanner);

      // scans stuff, but don't use the funky storage layer
      new Reflections(conf);
    }
    List<ParentClassDescriptor> implementations = new ArrayList<>();
    for (String baseTypeName: scannedClasses) {
      implementations.add(
          new ParentClassDescriptor(
              baseTypeName,
              new ArrayList<>(subTypesScanner.getChildrenOf(baseTypeName))));
    }
    List<AnnotatedClassDescriptor> annotated = annotationScanner.getAnnotatedClasses();
    verifyClassUnicity(annotated, pathsToScan);
    return new ScanResult(
        packagePrefixes,
        scannedClasses,
        scannedAnnotations,
        annotated,
        implementations);
  } finally {
    logger.info(
        format("Scanning packages %s in locations %s took %dms",
            packagePrefixes, pathsToScan, watch.elapsed(MILLISECONDS)));
  }
}