Java Code Examples for org.reflections.util.ConfigurationBuilder

The following examples show how to use org.reflections.util.ConfigurationBuilder. 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
Source Project: smart-admin   Source File: DataScopeSqlConfigService.java    License: 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
/**
 * Prepares the logger context. Locates the context and
 * sets the configuration file.
 * @return the logger context
 */
private ServletContextListener prepareAndgetContextListener() {
    try {
        if (StringUtils.isNotBlank(this.loggerContextPackageName)) {
            final Collection<URL> set = ClasspathHelper.forPackage(this.loggerContextPackageName);
            final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner()));
            final Set<Class<? extends ServletContextListener>> subTypesOf = reflections.getSubTypesOf(ServletContextListener.class);
            final ServletContextListener loggingContext = subTypesOf.iterator().next().newInstance();
            this.context.setInitParameter(this.logConfigurationField, this.logConfigurationFile.getURI().toString());
            return loggingContext;
        }
        return null;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source Project: DBus   Source File: JarManagerService.java    License: Apache License 2.0 6 votes vote down vote up
private String getPluginsEncoderTypes(String jarPath) throws Exception {
    URL jar = new URL("file", null, jarPath);
    PluginScanner scanner = new ReflectionsPluginScanner(ConfigurationBuilder.build(jar));
    Iterable<String> encoders = scanner.scan(Encoder.class);
    StringBuilder sb = new StringBuilder();
    if (encoders.iterator().hasNext()) {
        PluginsClassloader classloader = new PluginsClassloader(PluginManager.class.getClassLoader());
        classloader.addJar(jar);
        for (String encoderClass : encoders) {
            Class<?> clazz = classloader.loadClass(encoderClass);
            Encoder e = clazz.getDeclaredAnnotation(Encoder.class);
            sb.append(e.type()).append(",");
        }
    }
    return sb.toString();
}
 
Example 4
Source Project: DBus   Source File: PluginManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * copy on write 机制实现重新加载
 */
private void initialize() throws Exception {
    List<EncodePlugin> plugins = loader.loadPlugins();
    Set<String> urls = new HashSet<>();
    Map<String, ExtEncodeStrategy> map = new ConcurrentHashMap<>();
    for (EncodePlugin plugin : plugins) {
        if (!urls.contains(plugin.getJarPath())) {
            URL jar = new URL(PROTOCOL, null, plugin.getJarPath());
            PluginScanner scanner = new ReflectionsPluginScanner(ConfigurationBuilder.build(jar));
            Iterable<String> classes = scanner.scan(this.annotation);
            buildEncoders(classes, jar, plugin.getId(), map);
            urls.add(plugin.getJarPath());
        }
    }
    this.encoderMap = map;
}
 
Example 5
Source Project: syndesis   Source File: JsonDbDaoTest.java    License: Apache License 2.0 6 votes vote down vote up
public Class<? extends WithUsage>[] getClasses() {
    final Reflections reflections =
        new Reflections(new ConfigurationBuilder()
                            .forPackages("io.syndesis")
                            .filterInputsBy(r -> !r.contains("Immutable")));

    Set<Class<? extends WithUsage>> withUsageSubtypes = new HashSet<Class<? extends WithUsage>>();
    withUsageSubtypes.addAll(reflections.getSubTypesOf(WithUsage.class));
    final Set<Class<?>> immutables =
        reflections.getTypesAnnotatedWith(Value.Immutable.class);
    @SuppressWarnings("rawtypes") final Set<Class<? extends TargetWithDomain>> withDomainClasses =
        reflections.getSubTypesOf(TargetWithDomain.class);

    withUsageSubtypes.retainAll(immutables);
    withUsageSubtypes.removeAll(withDomainClasses);
    // not sure why this is a DAO type
    withUsageSubtypes.remove(ConnectionOverview.class);

    @SuppressWarnings("unchecked")
    final Class<? extends WithUsage>[] classes =
        (Class<? extends WithUsage>[]) withUsageSubtypes.toArray();

    return classes;
}
 
Example 6
Source Project: swagger-maven-plugin   Source File: JaxRSScanner.java    License: MIT License 6 votes vote down vote up
Application applicationInstance() {
    ConfigurationBuilder config = ConfigurationBuilder
            .build(resourcePackages)
            .setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
    Reflections reflections = new Reflections(config);
    Set<Class<? extends Application>> applicationClasses = reflections.getSubTypesOf(Application.class)
            .stream()
            .filter(this::filterClassByResourcePackages)
            .collect(Collectors.toSet());
    if (applicationClasses.isEmpty()) {
        return null;
    }
    if (applicationClasses.size() > 1) {
        log.warn("More than one javax.ws.rs.core.Application classes found on the classpath, skipping");
        return null;
    }
    return ClassUtils.createInstance(applicationClasses.iterator().next());
}
 
Example 7
Source Project: kafka-connect-twitter   Source File: SchemaGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void tweetEntities() {
  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forJavaClassPath())
      .forPackages(TweetEntity.class.getPackage().getName())
  );

  List<Class<?>> allClasses = new ArrayList<>();
  List<Class<? extends TweetEntity>> classes = list(reflections, TweetEntity.class);
  allClasses.add(MediaEntity.Variant.class);
  allClasses.add(MediaEntity.Size.class);
  allClasses.addAll(classes);


  for (Class<?> cls : allClasses) {
    StringBuilder builder = new StringBuilder();
    processClass(cls, builder);

    System.out.println(builder);
  }


}
 
Example 8
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 9
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 10
Source Project: pulsar   Source File: ConnectorDocGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static Reflections newReflections() throws Exception {
    List<URL> urls = new ArrayList<>();
    ClassLoader[] classLoaders = new ClassLoader[] {
        ConnectorDocGenerator.class.getClassLoader(),
        Thread.currentThread().getContextClassLoader()
    };
    for (int i = 0; i < classLoaders.length; i++) {
        if (classLoaders[i] instanceof URLClassLoader) {
            urls.addAll(Arrays.asList(((URLClassLoader) classLoaders[i]).getURLs()));
        } else {
            throw new RuntimeException("ClassLoader '" + classLoaders[i] + " is not an instance of URLClassLoader");
        }
    }
    ConfigurationBuilder confBuilder = new ConfigurationBuilder();
    confBuilder.setUrls(urls);
    return new Reflections(confBuilder);
}
 
Example 11
public void addLoader(ClassLoader loader) {
    if (builder == null) {
        this.builder = new ConfigurationBuilder();
        builder.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
    }
    builder.addClassLoader(loader);
    builder.addUrls(ClasspathHelper.forClassLoader(loader));

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

    scanClassPath(builder);
}
 
Example 12
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 13
Source Project: che   Source File: TypeScriptDtoGenerator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Init stuff is responsible to grab all DTOs found in classpath (classloader) and setup model for
 * String Template
 */
protected void init() {

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

  // keep only DTO interfaces
  Reflections reflections = new Reflections(configurationBuilder);
  List<Class<?>> annotatedWithDtos =
      new ArrayList<>(reflections.getTypesAnnotatedWith(DTO.class));
  List<Class<?>> interfacesDtos =
      annotatedWithDtos
          .stream()
          .filter(clazz -> clazz.isInterface())
          .collect(Collectors.toList());
  interfacesDtos.stream().forEach(this::analyze);
}
 
Example 14
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 15
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 16
Source Project: streams   Source File: ElasticsearchParentChildUpdaterIT.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTestParentChildPersistUpdater() throws Exception {

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

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

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

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

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

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

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

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

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

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

  addSerializer(Period.class, new StreamsPeriodSerializer(Period.class));
  addDeserializer(Period.class, new StreamsPeriodDeserializer(Period.class));
}
 
Example 18
Source Project: streams   Source File: ActivitySerDeTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that defined activity verbs have an example which can be loaded into
 * Activity beans and into verb-specific beans.
 * @throws Exception Exception
 */
@Test
public void testVerbSerDe() throws Exception {

  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forPackage("org.apache.streams.pojo.json"))
      .setScanners(new SubTypesScanner()));
  Set<Class<? extends Activity>> verbs = reflections.getSubTypesOf(Activity.class);

  for ( Class verbClass : verbs) {
    LOGGER.info("Verb: " + verbClass.getSimpleName() );
    Activity activity = (Activity) verbClass.newInstance();
    String verbName = activity.getVerb();
    String testfile = verbName.toLowerCase() + ".json";
    LOGGER.info("Serializing: activities/" + testfile );
    Path testActivityPath = Paths.get("target/dependency/activitystreams-testdata/" + testfile);
    assert (testActivityPath.toFile().exists());
    FileInputStream testActivityFileStream = new FileInputStream(testActivityPath.toFile());
    assert (testActivityFileStream != null);
    activity = MAPPER.convertValue(MAPPER.readValue(testActivityFileStream, verbClass), Activity.class);
    String activityString = MAPPER.writeValueAsString(activity);
    LOGGER.info("Deserialized: " + activityString );
    assert ( !activityString.contains("null") );
    assert ( !activityString.contains("[]") );
  }
}
 
Example 19
Source Project: streams   Source File: StreamsScalaSourceGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * StreamsScalaSourceGenerator constructor.
 * @param config StreamsScalaGenerationConfig
 */
public StreamsScalaSourceGenerator(StreamsScalaGenerationConfig config) {
  this.config = config;
  this.outDir = config.getTargetDirectory().getAbsolutePath();
  reflections = new Reflections(
      new ConfigurationBuilder()
          // TODO
          .forPackages(
              config.getSourcePackages()
                  .toArray(new String[config.getSourcePackages().size()])
          )
          .setScanners(
              new SubTypesScanner(),
              new TypeAnnotationsScanner()));

}
 
Example 20
Source Project: elasticactors   Source File: MessagesScanner.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    String[] basePackages = ScannerHelper.findBasePackagesOnClasspath(applicationContext.getClassLoader());
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

    for (String basePackage : basePackages) {
        configurationBuilder.addUrls(ClasspathHelper.forPackage(basePackage));
    }

    Reflections reflections = new Reflections(configurationBuilder);

    Set<Class<?>> messageClasses = reflections.getTypesAnnotatedWith(Message.class);

    for (Class<?> messageClass : messageClasses) {
        Message messageAnnotation = messageClass.getAnnotation(Message.class);
        // get the serialization framework
        SerializationFramework framework = applicationContext.getBean(messageAnnotation.serializationFramework());
        framework.register(messageClass);
    }
}
 
Example 21
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 22
Source Project: Flink-CEPplus   Source File: CheckForbiddenMethodsUsage.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoDefaultEncoding() throws Exception {
	final Reflections reflections = new Reflections(new ConfigurationBuilder()
		.useParallelExecutor(Runtime.getRuntime().availableProcessors())
		.addUrls(ClasspathHelper.forPackage("org.apache.flink"))
		.addScanners(new MemberUsageScanner()));

	for (ForbiddenCall forbiddenCall : forbiddenCalls) {
		final Set<Member> methodUsages = forbiddenCall.getUsages(reflections);
		methodUsages.removeAll(forbiddenCall.getExclusions());
		assertEquals("Unexpected calls: " + methodUsages, 0, methodUsages.size());
	}
}
 
Example 23
Source Project: flink   Source File: CheckForbiddenMethodsUsage.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoDefaultEncoding() throws Exception {
	final Reflections reflections = new Reflections(new ConfigurationBuilder()
		.useParallelExecutor(Runtime.getRuntime().availableProcessors())
		.addUrls(ClasspathHelper.forPackage("org.apache.flink"))
		.addScanners(new MemberUsageScanner()));

	for (ForbiddenCall forbiddenCall : forbiddenCalls) {
		final Set<Member> methodUsages = forbiddenCall.getUsages(reflections);
		methodUsages.removeAll(forbiddenCall.getExclusions());
		assertEquals("Unexpected calls: " + methodUsages, 0, methodUsages.size());
	}
}
 
Example 24
Source Project: marble   Source File: HiveSqlOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
public HiveSqlOperatorTable() {
  for (SqlOperator op : operatorListOfSqlStdOperatorTable) {
    operatorMapOfSqlStdOperatorTable.put(op.getName() + "_" + op.getSyntax(),
        op);
  }
  //register hive operator
  ConfigurationBuilder builder = new ConfigurationBuilder();
  hiveFunctionPackages.add("org.apache.hadoop.hive.ql");
  builder.forPackages(hiveFunctionPackages.toArray(new String[0]));
  builder.setExpandSuperTypes(false);
  Reflections reflections = new Reflections(builder);
  registerUDF(reflections);
  registerUDAF(reflections);
}
 
Example 25
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 26
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 27
public Set<String> getConfigs() {
    Set<String> configs = new HashSet<>();
    Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(pacakgePath)).setScanners(new MethodParameterScanner()));
    Set<Method> methodsAnnotatedWith = reflections.getMethodsWithAnyParamAnnotated(ParamsValidate.class);
    Iterator<Method> it = methodsAnnotatedWith.iterator();
    while (it.hasNext()) {
        Method method = it.next();
        String classAndMethod = method.getDeclaringClass().getCanonicalName() + "." + method.getName();
        //生成expression配置
        String expression = "execution (* " + classAndMethod + "(..))";
        configs.add(expression);
    }
    return configs;
}
 
Example 28
Source Project: springboot-shiro-cas-mybatis   Source File: CasLoggerFactory.java    License: MIT License 5 votes vote down vote up
/**
 * Instantiates a new Cas logger factory.
 * Configures the reflection scanning engine to be prepared to scan <code>org.slf4j.impl</code>
 * in order to find other available factories.
 */
public CasLoggerFactory() {
    this.loggerMap = new ConcurrentHashMap<>();
    final Collection<URL> set = ClasspathHelper.forPackage(PACKAGE_TO_SCAN);
    final Reflections reflections = new Reflections(new ConfigurationBuilder().addUrls(set).setScanners(new SubTypesScanner()));

    final Set<Class<? extends ILoggerFactory>> subTypesOf = reflections.getSubTypesOf(ILoggerFactory.class);
    subTypesOf.remove(this.getClass());

    if (subTypesOf.size() > 1) {
        Util.report("Multiple ILoggerFactory bindings are found on the classpath:");
        for (final Class<? extends ILoggerFactory> c : subTypesOf) {
            Util.report("* " + c.getCanonicalName());
        }
    }

    if (subTypesOf.isEmpty()) {
        final RuntimeException e = new RuntimeException("No ILoggerFactory could be found on the classpath."
                + " CAS cannot determine the logging framework."
                + " Examine the project dependencies and ensure that there is one and only one logging framework available.");

        Util.report(e.getMessage(), e);
        throw e;
    }
    this.realLoggerFactoryClass = subTypesOf.iterator().next();
    Util.report("ILoggerFactory to be used for logging is: " + this.realLoggerFactoryClass.getName());
}
 
Example 29
Source Project: azure-gradle-plugins   Source File: AnnotationHandlerImpl.java    License: MIT License 5 votes vote down vote up
@Override
public Set<Method> findFunctions(final List<URL> urls) {
    return new Reflections(
            new ConfigurationBuilder()
                    .addUrls(urls)
                    .setScanners(new MethodAnnotationsScanner())
                    .addClassLoader(getClassLoader(urls)))
            .getMethodsAnnotatedWith(FunctionName.class);
}
 
Example 30
Source Project: code-examples   Source File: CustomProviderVerifier.java    License: MIT License 5 votes vote down vote up
@Override
public boolean verifyResponseByInvokingProviderMethods(ProviderInfo providerInfo, ConsumerInfo consumer,
																											 Object interaction, String interactionMessage, Map failures) {
	try {

		ConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
						.setScanners(new MethodAnnotationsScanner())
						.forPackages(packagesToScan.toArray(new String[]{}));

		Reflections reflections = new Reflections(configurationBuilder);
		Set<Method> methodsAnnotatedWith = reflections.getMethodsAnnotatedWith(PactVerifyProvider.class);
		Set<Method> providerMethods = methodsAnnotatedWith.stream()
						.filter(m -> {
							PactVerifyProvider annotation = m.getAnnotation(PactVerifyProvider.class);
							return annotation.value().equals(((Interaction)interaction).getDescription());
						})
						.collect(Collectors.toSet());

		if (providerMethods.isEmpty()) {
			throw new RuntimeException("No annotated methods were found for interaction " +
							"'${interaction.description}'. You need to provide a method annotated with " +
							"@PactVerifyProvider(\"${interaction.description}\") that returns the message contents.");
		} else {
			if (interaction instanceof Message) {
				verifyMessagePact(providerMethods, (Message) interaction, interactionMessage, failures);
			} else {
				throw new RuntimeException("only supports Message interactions!");
			}
		}
	} catch (Exception e) {
		throw new RuntimeException("verification failed", e);
	}
	return true;
}