Java 类org.springframework.core.type.filter.AssignableTypeFilter 实例源码

项目:tipi-engine    文件:TipiAnnotationClassRegistrarTest.java   
/**
 * Ce test vérifie que la propriété <i>excludeFilters</i> fonctionne bien et que les filtres spécifiés permettent d'exclure certain process de l'enregistrement
 * automatique.
 */
@Test
public void testExcludeFilters() throws Exception {

    TipiRegistry registry = new TipiRegistryImpl();
    AnnotationActivityRegistrar registrar = new AnnotationActivityRegistrar();
    registrar.setaPackage("ch.sharedvd.tipi.engine.client");
    registrar.setRegistry(registry);
    registrar.setExcludeFilters(Arrays.asList(new AssignableTypeFilter(AnnotedTopProcess2.class)));
    registrar.afterPropertiesSet();

    // le AnnotedTopProcess2 devrait être exclu
    List<TopProcessMetaModel> topProcessesMeta = registry.getAllTopProcesses();
    Assert.assertEquals(1, topProcessesMeta.size());
    TopProcessMetaModel meta = topProcessesMeta.get(0);
    Assert.assertEquals("AnnotedTopProcess1", meta.getDescription());
    Assert.assertEquals(AnnotedTopProcess1.class.getSimpleName(), meta.getSimpleName());
    Assert.assertEquals(false, meta.isShownInUI());
    Assert.assertEquals(false, meta.isDeleteWhenFinished());
    Assert.assertEquals(5, meta.getPriority());
    Assert.assertEquals(1, meta.getNbMaxTopConcurrent());
    Assert.assertEquals(4, meta.getNbMaxConcurrent());
    Assert.assertEquals(false, meta.isStartable());
}
项目:tipi-engine    文件:HibernateMetaDataHelper.java   
/**
 * Retourne les classes d'une package
 *
 * @param packageName
 * @return
 * @throws Exception
 */
public static List<Class> getClasses(String packageName) {
    final List<Class> list = new ArrayList<>();

    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(Object.class));
    final Set<BeanDefinition> bds = scanner.findCandidateComponents(packageName);
    try {
        for (BeanDefinition bd : bds) {
            final Class<?> tc = Class.forName(bd.getBeanClassName());
            if (tc.getAnnotation(Entity.class) != null) {
                list.add(tc);
            }
        }
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    return list;
}
项目:alfresco-repository    文件:AJExtensionsCompileTest.java   
@Test
public void testCompileExtendedServices() throws Exception
{
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
    provider.addIncludeFilter(new AssignableTypeFilter(Extensible.class));

    Set<BeanDefinition> components = provider.findCandidateComponents("org/alfresco/*");
    Set<Class<? extends Extensible>> extensibles = new HashSet<>();
    for (BeanDefinition component : components)
    {
        @SuppressWarnings("unchecked")
        Class<? extends Extensible> extensibleClass = (Class<? extends Extensible>) Class.forName(component
                    .getBeanClassName());
        extensibles.add(extensibleClass);

    }
    compile(extensibles);
}
项目:taboola-cronyx    文件:ConfigUtil.java   
public static <T> List<Pair<Class, T>> cronyxQuartzConverterPairs(Class<T> tClass) {

        List<Pair<Class, T>> results = new ArrayList<>();

        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AssignableTypeFilter(tClass));

        Set<BeanDefinition> components = provider.findCandidateComponents(PACKAGE);
        for (BeanDefinition component : components) {
            try {
                Class cls = Class.forName(component.getBeanClassName());
                Class<?> typeArgument = GenericTypeResolver.resolveTypeArgument(cls, tClass);
                results.add(new ImmutablePair<>(typeArgument, (T) cls.newInstance()));

            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                throw new CronyxException("Could not instantiate cronyxToQuartzConverters", e);
            }
        }
        return results;
    }
项目:springboot-analysis    文件:ConsumerRegistrar.java   
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AnnotationTypeFilter(Consumer.class));
    provider.addIncludeFilter(new AssignableTypeFilter(IConsumer.class));
    Set<BeanDefinition> beanDefinitionSet = provider.findCandidateComponents("spring.study.componentprovider.bean");

    for(BeanDefinition beanDefinition : beanDefinitionSet) {
        String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry);
        if(!registry.containsBeanDefinition(beanName)) {
            registry.registerBeanDefinition(beanName, beanDefinition);
            registry.registerBeanDefinition("11", beanDefinition);
        }
    }

}
项目:cqrs-es-kafka    文件:CommandHandlerUtils.java   
public static Map<String, CommandHandler> buildCommandHandlersRegistry(final String basePackage,
                                                                       final ApplicationContext context) {

    final Map<String, CommandHandler> registry = new HashMap<>();
    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
    scanner.addIncludeFilter(new AssignableTypeFilter(CommandHandler.class));

    CommandHandler currentHandler = null;

    for (BeanDefinition bean : scanner.findCandidateComponents(basePackage)) {
        currentHandler = (CommandHandler) beanFactory.createBean(ClassUtils.resolveClassName(bean.getBeanClassName(), context.getClassLoader()),
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
        registry.put(currentHandler.getInterest(), currentHandler);
    }

    return registry;
}
项目:feign-error-decoder    文件:CachedSpringClassHierarchySupplier.java   
public CachedSpringClassHierarchySupplier(Class<?> baseClass, String basePackage) {
  if (!baseClassSubClassesCache.containsKey(baseClass)) {
    ClassPathScanningCandidateComponentProvider provider =
        new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AssignableTypeFilter(baseClass));

    Set<Class<?>> subClasses = new HashSet<>();
    for (BeanDefinition beanDefinition : provider.findCandidateComponents(basePackage)) {
      try {
        subClasses.add(Class.forName(beanDefinition.getBeanClassName()));
      } catch (ClassNotFoundException e) {
        throw new IllegalStateException(
            String.format("Could not load child class '%s'.", beanDefinition.getBeanClassName()),
            e);
      }
    }
    baseClassSubClassesCache.put(baseClass, subClasses);
  }
  subClasses = baseClassSubClassesCache.get(baseClass);
}
项目:feign-error-decoder    文件:SpringClassHierarchySupplier.java   
@Override
public Set<Class<?>> getSubClasses(Class<?> clazz, String basePackage) {
  ClassPathScanningCandidateComponentProvider provider =
      new ClassPathScanningCandidateComponentProvider(false);
  provider.addIncludeFilter(new AssignableTypeFilter(clazz));

  Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);

  return components
      .stream()
      .map(
          component -> {
            try {
              return Class.forName(component.getBeanClassName());
            } catch (ClassNotFoundException e) {
              throw new IllegalStateException(
                  String.format("Could not load child class '%s'.", component.getBeanClassName()),
                  e);
            }
          })
      .collect(Collectors.toSet());
}
项目:spring4-understanding    文件:ClassPathBeanDefinitionScannerTests.java   
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaults() {
    GenericApplicationContext context = new GenericApplicationContext();
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
    scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
    int beanCount = scanner.scan(BASE_PACKAGE);
    assertEquals(11, beanCount);
    assertFalse(context.containsBean("fooServiceImpl"));
    assertTrue(context.containsBean("serviceInvocationCounter"));
    assertTrue(context.containsBean("stubFooDao"));
    assertTrue(context.containsBean("myNamedComponent"));
    assertTrue(context.containsBean("myNamedDao"));
    assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
项目:spring4-understanding    文件:ClassPathBeanDefinitionScannerTests.java   
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaultsWithoutPostProcessors() {
    GenericApplicationContext context = new GenericApplicationContext();
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
    scanner.setIncludeAnnotationConfig(false);
    scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
    int beanCount = scanner.scan(BASE_PACKAGE);
    assertEquals(5, beanCount);
    assertFalse(context.containsBean("fooServiceImpl"));
    assertTrue(context.containsBean("serviceInvocationCounter"));
    assertTrue(context.containsBean("stubFooDao"));
    assertTrue(context.containsBean("myNamedComponent"));
    assertTrue(context.containsBean("myNamedDao"));
    assertFalse(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertFalse(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertFalse(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
项目:spring4-understanding    文件:ClassPathBeanDefinitionScannerTests.java   
@Test
public void testMultipleCustomExcludeFiltersAndDefaults() {
    GenericApplicationContext context = new GenericApplicationContext();
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
    scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Aspect.class));
    int beanCount = scanner.scan(BASE_PACKAGE);
    assertEquals(10, beanCount);
    assertFalse(context.containsBean("fooServiceImpl"));
    assertFalse(context.containsBean("serviceInvocationCounter"));
    assertTrue(context.containsBean("stubFooDao"));
    assertTrue(context.containsBean("myNamedComponent"));
    assertTrue(context.containsBean("myNamedDao"));
    assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME));
}
项目:spring-data-jest    文件:ElasticsearchJestAutoConfiguration.java   
/**
 * List all official ES plugins available on ClassPath.
 * @return List of plugins class
 */
@SuppressWarnings("unchecked")
private static Collection<Class<? extends Plugin>> scanPlugins() {
    ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(false);
    componentProvider.addIncludeFilter(new AssignableTypeFilter(Plugin.class));

    return componentProvider.findCandidateComponents("org.elasticsearch.plugin").stream()
            .map(BeanDefinition::getBeanClassName)
            .map(name -> {
                try {
                    return (Class<? extends Plugin>) Class.forName(name);
                } catch (ClassNotFoundException e) {
                    logger.warn("Cannot load class on plugin detection", e);
                    return null;
                }
            })
            .collect(Collectors.toSet());
}
项目:acme-solution    文件:CommandHandlerUtils.java   
public static Map<String, CommandHandler> buildCommandHandlersRegistry(final String basePackage,
                                                                       final ApplicationContext context) {

    final Map<String, CommandHandler> registry = new HashMap<>();
    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
    scanner.addIncludeFilter(new AssignableTypeFilter(CommandHandler.class));

    CommandHandler currentHandler = null;

    for (BeanDefinition bean : scanner.findCandidateComponents(basePackage)) {
        currentHandler = (CommandHandler) beanFactory.createBean(ClassUtils.resolveClassName(bean.getBeanClassName(), context.getClassLoader()),
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
        registry.put(currentHandler.getInterest().getName(), currentHandler);
    }

    return registry;
}
项目:acme-solution    文件:EventHandlerUtils.java   
public static Map<String, EventHandler> buildEventHandlersRegistry(final String basePackage,
                                                                   final ApplicationContext context) {

    final Map<String, EventHandler> registry = new HashMap<>();
    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
    scanner.addIncludeFilter(new AssignableTypeFilter(EventHandler.class));

    EventHandler currentHandler = null;

    for (BeanDefinition bean : scanner.findCandidateComponents(basePackage)) {
        currentHandler = (EventHandler) beanFactory.createBean(ClassUtils.resolveClassName(bean.getBeanClassName(), context.getClassLoader()),
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
        registry.put(currentHandler.getInterest(), currentHandler);
    }

    return registry;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:FilterAnnotations.java   
@SuppressWarnings("unchecked")
private TypeFilter createTypeFilter(FilterType filterType, Class<?> filterClass) {
    switch (filterType) {
    case ANNOTATION:
        Assert.isAssignable(Annotation.class, filterClass,
                "An error occurred while processing a ANNOTATION type filter: ");
        return new AnnotationTypeFilter((Class<Annotation>) filterClass);
    case ASSIGNABLE_TYPE:
        return new AssignableTypeFilter(filterClass);
    case CUSTOM:
        Assert.isAssignable(TypeFilter.class, filterClass,
                "An error occurred while processing a CUSTOM type filter: ");
        return BeanUtils.instantiateClass(filterClass, TypeFilter.class);
    }
    throw new IllegalArgumentException(
            "Filter type not supported with Class value: " + filterType);
}
项目:invesdwin-context-persistence    文件:JpaRepositoryScanContextLocation.java   
private Map<Class<?>, Set<Class<?>>> scanForJpaRepositories(final String basePackage) {
    final Map<Class<?>, Set<Class<?>>> jpaRepositories = new HashMap<Class<?>, Set<Class<?>>>();
    final ClassPathScanner scanner = new ClassPathScanner().withInterfacesOnly();
    scanner.addIncludeFilter(new AssignableTypeFilter(JpaRepository.class));

    final Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(basePackage);
    for (final BeanDefinition bd : candidateComponents) {
        final String beanClassName = bd.getBeanClassName();
        final Class<?> repositoryClass = Reflections.classForName(beanClassName);
        if (!IDao.class.isAssignableFrom(repositoryClass)) {
            final Class<?>[] typeArguments = Reflections.resolveTypeArguments(repositoryClass, JpaRepository.class);
            Assertions.assertThat(typeArguments.length).isEqualTo(2);
            final Class<?> entity = typeArguments[0];
            Set<Class<?>> set = jpaRepositories.get(entity);
            if (set == null) {
                set = new HashSet<Class<?>>();
                jpaRepositories.put(entity, set);
            }
            Assertions.assertThat(set.add(repositoryClass)).isTrue();
        }
    }
    return jpaRepositories;
}
项目:spring-boot-concourse    文件:FilterAnnotations.java   
@SuppressWarnings("unchecked")
private TypeFilter createTypeFilter(FilterType filterType, Class<?> filterClass) {
    switch (filterType) {
    case ANNOTATION:
        Assert.isAssignable(Annotation.class, filterClass,
                "An error occurred while processing a ANNOTATION type filter: ");
        return new AnnotationTypeFilter((Class<Annotation>) filterClass);
    case ASSIGNABLE_TYPE:
        return new AssignableTypeFilter(filterClass);
    case CUSTOM:
        Assert.isAssignable(TypeFilter.class, filterClass,
                "An error occurred while processing a CUSTOM type filter: ");
        return BeanUtils.instantiateClass(filterClass, TypeFilter.class);
    }
    throw new IllegalArgumentException(
            "Filter type not supported with Class value: " + filterType);
}
项目:putput    文件:JerseyConfig.java   
@PostConstruct
public void registerResources() {
  ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
  provider.addIncludeFilter(new AssignableTypeFilter(BaseResource.class));

  for (BeanDefinition component : provider.findCandidateComponents("org/putput")) {
    try {
      Class<?> resourceClass = Class.forName(component.getBeanClassName());
      org.slf4j.LoggerFactory.getLogger(JerseyConfig.class).info("registering " + resourceClass.getName());
      register(resourceClass);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }

}
项目:kc-rice    文件:QueryByCriteriaJaxbTest.java   
/**
 * Search the classes in the PREDICATE_BASE_PACKAGE and build a list of all simple (non-composite) Predicate classes
 * @return a list of simple Predicate classes
 * @throws ClassNotFoundException
 */
private ArrayList<Class<?>> discoverSimplePredicateClasses() throws ClassNotFoundException {
    ArrayList<Class<?>> discoveredPredicateClasses = new ArrayList<Class<?>>();

    // This technique was copped from:
    // http://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
    provider.addIncludeFilter(new AssignableTypeFilter(Predicate.class));

    // scan in org.example.package
    Set<BeanDefinition> components = provider.findCandidateComponents(PREDICATE_BASE_PACKAGE);
    for (BeanDefinition component : components)
    {
        Class cls = Class.forName(component.getBeanClassName());
        if (!cls.isMemberClass()                             // filter out inner class predicates from test packages
            && Predicate.class.isAssignableFrom(cls)         // filter out any non-predicate classes
            && !CompositePredicate.class.isAssignableFrom(cls)) // filter out 'and' and 'or' predicates
        {
            discoveredPredicateClasses.add(cls);
            // use class cls found
            LOG.debug("discovered " + cls.toString());
        }
    }
    return discoveredPredicateClasses;
}
项目:moserp    文件:RestConfiguration.java   
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
    provider.addIncludeFilter(new AssignableTypeFilter(IdentifiableEntity.class));
    Set<BeanDefinition> components = provider.findCandidateComponents(this.getClass().getPackage().getName());
    List<Class<?>> classes = new ArrayList<>();

    components.forEach(component -> {
        try {
            classes.add(Class.forName(component.getBeanClassName()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

    config.exposeIdsFor(classes.toArray(new Class[classes.size()]));
}
项目:brooklyn-tosca    文件:TypeScanner.java   
public static Set<Class<?>> scanTypes(String basePackage, Class<?> targetType) throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    if (resourceLoader!=null) {
        scanner.setResourceLoader(resourceLoader);
    }

    AssignableTypeFilter filter = new AssignableTypeFilter(targetType);
    scanner.addIncludeFilter(filter);
    Set<BeanDefinition> beanSet = scanner.findCandidateComponents(basePackage);

    Set<Class<?>> classSet = new HashSet<Class<?>>();
    for (BeanDefinition beanDef : beanSet) {
        // log.debug("found candidate bean = {}", beanDef.getBeanClassName());

        Class<?> clazz;

        clazz = Class.forName(beanDef.getBeanClassName(), true, Thread.currentThread().getContextClassLoader());
        classSet.add(clazz);
    }

    return classSet;
}
项目:zstack    文件:ConfigurationManagerImpl.java   
private void generateApiMessageGroovyClass(StringBuilder sb, List<String> basePkgs) {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(APIMessage.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(APIReply.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(APIEvent.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Component.class));
    for (String pkg : basePkgs) {
        for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
            try {
                Class<?> clazz = Class.forName(bd.getBeanClassName());
                //classToApiMessageGroovyClass(sb, clazz);
                classToApiMessageGroovyInformation(sb, clazz);
            } catch (ClassNotFoundException e) {
                logger.warn(String.format("Unable to generate groovy class for %s", bd.getBeanClassName()), e);
            }
        }
    }
}
项目:zstack    文件:Deployer.java   
private void scanDeployer() {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(AbstractDeployer.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(org.springframework.stereotype.Component.class));
    for (BeanDefinition bd : scanner.findCandidateComponents("org.zstack.test")) {
        try {
            Class<?> clazz = Class.forName(bd.getBeanClassName());
            AbstractDeployer d = (AbstractDeployer) clazz.newInstance();
            deployers.put(d.getSupportedDeployerClassType(), d);
            logger.debug(String.format("Scanned a deployer[%s] supporting %s", d.getClass().getName(), d.getSupportedDeployerClassType()));
        } catch (Exception e) {
            logger.warn(String.format("unable to create deployer[%s], it's probably there are some beans requried by deployer is not loaded, skip it. error message:\n%s", bd.getBeanClassName(), e.getMessage()));
        }

    }
}
项目:zstack    文件:RESTApiFacadeImpl.java   
void init() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    Set<APIEvent> boundEvents = new HashSet<APIEvent>(100);
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.resetFilters(false);
    scanner.addIncludeFilter(new AssignableTypeFilter(APIEvent.class));
    for (String pkg : getBasePkgNames()) {
        for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
            Class<?> clazz = Class.forName(bd.getBeanClassName());
            if (clazz == APIEvent.class) {
                continue;
            }
            APIEvent evt = (APIEvent) clazz.newInstance();
            boundEvents.add(evt);
        }
    }

    for (APIEvent e : boundEvents) {
        bus.subscribeEvent(this, e);
    }
}
项目:jspresso-ce    文件:EntityHelper.java   
/**
 * Gets entity sub contracts.
 *
 * @param entityContract
 *     the entity contract
 * @return the entity sub contracts
 */
@SuppressWarnings("unchecked")
public static Collection<Class<IEntity>> getEntitySubContracts(Class<IEntity> entityContract) {
  Collection<Class<IEntity>> entitySubContracts = new HashSet<>();
  ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false) {
    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
      // Allow to return superclasses
      return beanDefinition.getMetadata().isIndependent();
    }
  };
  provider.addIncludeFilter(new AssignableTypeFilter(entityContract));
  Set<BeanDefinition> components = provider.findCandidateComponents(entityContract.getPackage().getName().replace('.',
      '/'));
  for (BeanDefinition component : components) {
    try {
      Class<IEntity> entitySubContract = (Class<IEntity>) Class.forName(component.getBeanClassName());
      if (entitySubContract != entityContract) {
        entitySubContracts.add(entitySubContract);
      }
    } catch (ClassNotFoundException e) {
      // Ignore
    }
  }
  return entitySubContracts;
}
项目:spring-cloud-bus    文件:BusJacksonAutoConfiguration.java   
private Class<?>[] findSubTypes() {
    List<Class<?>> types = new ArrayList<>();
    if (this.packagesToScan != null) {
        for (String pkg : this.packagesToScan) {
            ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
                    false);
            provider.addIncludeFilter(
                    new AssignableTypeFilter(RemoteApplicationEvent.class));

            Set<BeanDefinition> components = provider.findCandidateComponents(pkg);
            for (BeanDefinition component : components) {
                try {
                    types.add(Class.forName(component.getBeanClassName()));
                }
                catch (ClassNotFoundException e) {
                    throw new IllegalStateException(
                            "Failed to scan classpath for remote event classes", e);
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Found sub types: "+types);
    }
    return types.toArray(new Class<?>[0]);
}
项目:community-edition-old    文件:AJExtensionsCompileTest.java   
@Test
public void testCompileExtendedServices() throws Exception
{
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
    provider.addIncludeFilter(new AssignableTypeFilter(Extensible.class));

    Set<BeanDefinition> components = provider.findCandidateComponents("org/alfresco/*");
    Set<Class<? extends Extensible>> extensibles = new HashSet<>();
    for (BeanDefinition component : components)
    {
        @SuppressWarnings("unchecked")
        Class<? extends Extensible> extensibleClass = (Class<? extends Extensible>) Class.forName(component
                    .getBeanClassName());
        extensibles.add(extensibleClass);

    }
    compile(extensibles);
}
项目:class-guard    文件:ClassPathBeanDefinitionScannerTests.java   
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaults() {
    GenericApplicationContext context = new GenericApplicationContext();
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
    scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
    int beanCount = scanner.scan(BASE_PACKAGE);
    assertEquals(9, beanCount);
    assertFalse(context.containsBean("fooServiceImpl"));
    assertTrue(context.containsBean("serviceInvocationCounter"));
    assertTrue(context.containsBean("stubFooDao"));
    assertTrue(context.containsBean("myNamedComponent"));
    assertTrue(context.containsBean("myNamedDao"));
    assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
项目:class-guard    文件:ClassPathBeanDefinitionScannerTests.java   
@Test
public void testCustomAssignableTypeExcludeFilterAndDefaultsWithoutPostProcessors() {
    GenericApplicationContext context = new GenericApplicationContext();
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
    scanner.setIncludeAnnotationConfig(false);
    scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
    int beanCount = scanner.scan(BASE_PACKAGE);
    assertEquals(5, beanCount);
    assertFalse(context.containsBean("fooServiceImpl"));
    assertTrue(context.containsBean("serviceInvocationCounter"));
    assertTrue(context.containsBean("stubFooDao"));
    assertTrue(context.containsBean("myNamedComponent"));
    assertTrue(context.containsBean("myNamedDao"));
    assertFalse(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertFalse(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertFalse(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
项目:class-guard    文件:ClassPathBeanDefinitionScannerTests.java   
@Test
public void testMultipleCustomExcludeFiltersAndDefaults() {
    GenericApplicationContext context = new GenericApplicationContext();
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, true);
    scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Aspect.class));
    int beanCount = scanner.scan(BASE_PACKAGE);
    assertEquals(8, beanCount);
    assertFalse(context.containsBean("fooServiceImpl"));
    assertFalse(context.containsBean("serviceInvocationCounter"));
    assertTrue(context.containsBean("stubFooDao"));
    assertTrue(context.containsBean("myNamedComponent"));
    assertTrue(context.containsBean("myNamedDao"));
    assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
项目:syncope    文件:SAML2SPClassPathScanImplementationLookup.java   
@Override
public void load() {
    actionsClasses = new HashSet<>();

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AssignableTypeFilter(SAML2IdPActions.class));

    for (BeanDefinition bd : scanner.findCandidateComponents(DEFAULT_BASE_PACKAGE)) {
        try {
            Class<?> clazz = ClassUtils.resolveClassName(
                    bd.getBeanClassName(), ClassUtils.getDefaultClassLoader());
            boolean isAbstractClazz = Modifier.isAbstract(clazz.getModifiers());

            if (SAML2IdPActions.class.isAssignableFrom(clazz) && !isAbstractClazz) {
                actionsClasses.add(clazz.getName());
            }
        } catch (Throwable t) {
            LOG.warn("Could not inspect class {}", bd.getBeanClassName(), t);
        }
    }

    actionsClasses = Collections.unmodifiableSet(actionsClasses);
}
项目:kfs    文件:WebServicesImplTest.java   
public void testWebServices() throws Exception {


    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AssignableTypeFilter(KfsKcSoapService.class));
    Set<BeanDefinition> components = provider.findCandidateComponents(TEST_BASE_PACKAGE);
    for (BeanDefinition component : components) {
        String className = component.getBeanClassName();
        Class<KfsKcSoapService> kfsServiceClass = (Class<KfsKcSoapService>) Class.forName(className);
        try {
            KfsKcSoapService kfsServiceInst = kfsServiceClass.newInstance();
            URL myWsdl = kfsServiceInst.getWsdl();
            assertTrue(isValidfetchXML(myWsdl));
        }
        catch (Exception ex) {
            fail(ex.getMessage());
        }
    }
}
项目:rice    文件:QueryByCriteriaJaxbTest.java   
/**
 * Search the classes in the PREDICATE_BASE_PACKAGE and build a list of all simple (non-composite) Predicate classes
 * @return a list of simple Predicate classes
 * @throws ClassNotFoundException
 */
private ArrayList<Class<?>> discoverSimplePredicateClasses() throws ClassNotFoundException {
    ArrayList<Class<?>> discoveredPredicateClasses = new ArrayList<Class<?>>();

    // This technique was copped from:
    // http://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
    provider.addIncludeFilter(new AssignableTypeFilter(Predicate.class));

    // scan in org.example.package
    Set<BeanDefinition> components = provider.findCandidateComponents(PREDICATE_BASE_PACKAGE);
    for (BeanDefinition component : components)
    {
        Class cls = Class.forName(component.getBeanClassName());
        if (!cls.isMemberClass()                             // filter out inner class predicates from test packages
            && Predicate.class.isAssignableFrom(cls)         // filter out any non-predicate classes
            && !CompositePredicate.class.isAssignableFrom(cls)) // filter out 'and' and 'or' predicates
        {
            discoveredPredicateClasses.add(cls);
            // use class cls found
            LOG.debug("discovered " + cls.toString());
        }
    }
    return discoveredPredicateClasses;
}
项目:muon-java    文件:MuonTransportFactoryBeanRegistrar.java   
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AssignableTypeFilter(MuonTransportFactory.class));
    Properties properties = PropertiesHelper.populateConnectionProperties(environment, MUON_PREFIX);
    scanner
            .findCandidateComponents("io.muoncore.transport")
            .stream()
            .forEach(candidateComponent -> {
                final String beanClassName = candidateComponent.getBeanClassName();

                BeanDefinitionBuilder definition = BeanDefinitionBuilder
                        .genericBeanDefinition(MuonTransportFactoryBean.class);
                definition.addPropertyValue("type", beanClassName);
                definition.addPropertyValue("properties", properties);

                String beanName = BeanDefinitionReaderUtils.generateBeanName(definition.getBeanDefinition(), registry);

                final BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(definition.getBeanDefinition(), beanName);

                BeanDefinitionReaderUtils.registerBeanDefinition(beanDefinitionHolder, registry);
            });
}
项目:opennmszh    文件:Upgrade.java   
/**
 * Gets the upgrade objects.
 *
 * @return the upgrade objects
 * @throws OnmsUpgradeException the OpenNMS upgrade exception
 */
protected List<OnmsUpgrade> getUpgradeObjects() throws OnmsUpgradeException {
    List<OnmsUpgrade> upgrades = new ArrayList<OnmsUpgrade>();
    try {
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
        provider.addIncludeFilter(new AssignableTypeFilter(OnmsUpgrade.class));
        Set<BeanDefinition> components = provider.findCandidateComponents(getClassScope());
        for (BeanDefinition component : components) {
            if (component.isAbstract()) {
                continue;
            }
            Class<?> cls = Class.forName(component.getBeanClassName());
            if (cls.getAnnotation(Ignore.class) != null) {
                continue;
            }
            OnmsUpgrade upgrade = (OnmsUpgrade) cls.newInstance();
            upgrades.add(upgrade);
            log("Found upgrade task %s\n", upgrade.getId());
        }
        Collections.sort(upgrades, new OnmsUpgradeComparator());
    } catch (Exception e) {
        throw new OnmsUpgradeException("  Can't find the upgrade classes because: " + e.getMessage(), e);
    }
    return upgrades;
}
项目:hypersocket-framework    文件:MigrationObjectMapper.java   
private void scanMigrationMixIn() {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AssignableTypeFilter(MigrationMixIn.class));

    final Set<BeanDefinition> classes = scanner.findCandidateComponents("com.hypersocket.migration.mixin.entity");

    try {
        for (BeanDefinition beanDefinition : classes) {
            String className = beanDefinition.getBeanClassName();
            Class aClass = MigrationObjectMapper.class.getClassLoader().loadClass(className);
            Class oldClass = customMixInMap.put(aClass.getSimpleName(), aClass);
            if(oldClass != null) {
                throw new IllegalStateException(String.format("While adding class for key %s, map returned back object, " +
                        "meaning value already exists, " +
                        "for single key we have multiple values, " +
                        "please rename classes for error key.", aClass.getSimpleName()));
            }
        }
    }catch (ClassNotFoundException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
项目:usergrid    文件:Schema.java   
@SuppressWarnings("unchecked")
public void scanEntities() {
    synchronized ( entitiesScanPath ) {
        for ( String path : entitiesScanPath ) {
            ClassPathScanningCandidateComponentProvider provider =
                    new ClassPathScanningCandidateComponentProvider( true );
            provider.addIncludeFilter( new AssignableTypeFilter( TypedEntity.class ) );

            Set<BeanDefinition> components = provider.findCandidateComponents( path );
            for ( BeanDefinition component : components ) {
                try {
                    Class<?> cls = Class.forName( component.getBeanClassName() );
                    if ( Entity.class.isAssignableFrom( cls ) ) {
                        registerEntity( ( Class<? extends Entity> ) cls );
                    }
                }
                catch ( ClassNotFoundException e ) {
                    logger.error( "Unable to get entity class ", e );
                }
            }
            registerEntity( DynamicEntity.class );
        }
    }
}
项目:kuali_rice    文件:QueryByCriteriaJaxbTest.java   
/**
 * Search the classes in the PREDICATE_BASE_PACKAGE and build a list of all simple (non-composite) Predicate classes
 * @return a list of simple Predicate classes
 * @throws ClassNotFoundException
 */
private ArrayList<Class<?>> discoverSimplePredicateClasses() throws ClassNotFoundException {
    ArrayList<Class<?>> discoveredPredicateClasses = new ArrayList<Class<?>>();

    // This technique was copped from:
    // http://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
    provider.addIncludeFilter(new AssignableTypeFilter(Predicate.class));

    // scan in org.example.package
    Set<BeanDefinition> components = provider.findCandidateComponents(PREDICATE_BASE_PACKAGE);
    for (BeanDefinition component : components)
    {
        Class cls = Class.forName(component.getBeanClassName());
        if (!cls.isMemberClass()                             // filter out inner class predicates from test packages
            && Predicate.class.isAssignableFrom(cls)         // filter out any non-predicate classes
            && !CompositePredicate.class.isAssignableFrom(cls)) // filter out 'and' and 'or' predicates
        {
            discoveredPredicateClasses.add(cls);
            // use class cls found
            LOG.debug("discovered " + cls.toString());
        }
    }
    return discoveredPredicateClasses;
}
项目:lams    文件:ComponentScanBeanDefinitionParser.java   
@SuppressWarnings("unchecked")
protected TypeFilter createTypeFilter(Element element, ClassLoader classLoader) {
    String filterType = element.getAttribute(FILTER_TYPE_ATTRIBUTE);
    String expression = element.getAttribute(FILTER_EXPRESSION_ATTRIBUTE);
    try {
        if ("annotation".equals(filterType)) {
            return new AnnotationTypeFilter((Class<Annotation>) classLoader.loadClass(expression));
        }
        else if ("assignable".equals(filterType)) {
            return new AssignableTypeFilter(classLoader.loadClass(expression));
        }
        else if ("aspectj".equals(filterType)) {
            return new AspectJTypeFilter(expression, classLoader);
        }
        else if ("regex".equals(filterType)) {
            return new RegexPatternTypeFilter(Pattern.compile(expression));
        }
        else if ("custom".equals(filterType)) {
            Class<?> filterClass = classLoader.loadClass(expression);
            if (!TypeFilter.class.isAssignableFrom(filterClass)) {
                throw new IllegalArgumentException(
                        "Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression);
            }
            return (TypeFilter) BeanUtils.instantiateClass(filterClass);
        }
        else {
            throw new IllegalArgumentException("Unsupported filter type: " + filterType);
        }
    }
    catch (ClassNotFoundException ex) {
        throw new FatalBeanException("Type filter class not found: " + expression, ex);
    }
}
项目:cqrs-es-kafka    文件:EventHandlerUtils.java   
public static Map<String, EventHandler> buildEventHandlersRegistry(final String basePackage,
                                                                   final ApplicationContext context) {

    final Map<String, EventHandler> registry = new HashMap<>();
    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
    scanner.addIncludeFilter(new AssignableTypeFilter(EventHandler.class));

    EventHandler currentHandler = null;

    for (BeanDefinition bean : scanner.findCandidateComponents(basePackage)) {
        currentHandler = (EventHandler) beanFactory.createBean(ClassUtils.resolveClassName(bean.getBeanClassName(), context.getClassLoader()),
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
        registry.put(currentHandler.getInterest(), currentHandler);
    }

    return registry;
}