/** * 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()); }
/** * 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; }
@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); }
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; }
@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); } } }
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; }
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); }
@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()); }
@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)); }
@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)); }
@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)); }
/** * 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()); }
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; }
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; }
@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); }
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; }
@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); } } }
/** * 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; }
@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()])); }
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; }
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); } } } }
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())); } } }
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); } }
/** * 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; }
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]); }
@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)); }
@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)); }
@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); }
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()); } } }
@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); }); }
/** * 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; }
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); } }
@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 ); } } }
@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); } }