Java Code Examples for org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider

The following examples show how to use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider. 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: RestDoc   Source File: SpringControllerResolver.java    License: Apache License 2.0 7 votes vote down vote up
@Override
public List<Class> getClasses() {
    List<String> packages = _packages;

    var scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));

    var classes = new ArrayList<Class>();
    if (packages == null) packages = Arrays.asList("cn", "com");
    for (var packageName : packages) {
        var beans = scanner.findCandidateComponents(packageName);
        for (var bean : beans) {
            try {
                var className = bean.getBeanClassName();
                Class clazz = Class.forName(className);

                classes.add(clazz);
            } catch (ClassNotFoundException e) {
                _logger.warn("not found class:" + bean.getBeanClassName(), e);
            }
        }
    }
    return classes;
}
 
Example 2
Source Project: sdn-rx   Source File: Neo4jConfigurationSupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Scans the given base package for entities, i.e. Neo4j specific types annotated with {@link Node}.
 *
 * @param basePackage must not be {@literal null}.
 * @return found entities in the package to scan.
 * @throws ClassNotFoundException if the given class cannot be loaded by the class loader.
 */
protected final Set<Class<?>> scanForEntities(String basePackage) throws ClassNotFoundException {

	if (!StringUtils.hasText(basePackage)) {
		return Collections.emptySet();
	}

	Set<Class<?>> initialEntitySet = new HashSet<Class<?>>();

	ClassPathScanningCandidateComponentProvider componentProvider =
		new ClassPathScanningCandidateComponentProvider(false);
	componentProvider.addIncludeFilter(new AnnotationTypeFilter(Node.class));

	ClassLoader classLoader = Neo4jConfigurationSupport.class.getClassLoader();
	for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {
		initialEntitySet.add(ClassUtils.forName(candidate.getBeanClassName(), classLoader));
	}

	return initialEntitySet;
}
 
Example 3
Source Project: gemini   Source File: ErrorService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AssignableTypeFilter(GeminiException.class));
    Set<BeanDefinition> components = provider.findCandidateComponents("it.at7.gemini");
    for (BeanDefinition component : components) {
        Class<?> gemException = Class.forName(component.getBeanClassName());
        Class<?>[] innerClasses = gemException.getDeclaredClasses();
        for (Class<?> innerClass : innerClasses) {
            String simpleName = innerClass.getSimpleName();
            if (simpleName.equals("Code")) {
                Enum[] enumConstants = (Enum[]) innerClass.getEnumConstants();
                register(enumConstants);
            }
        }
    }
}
 
Example 4
Source Project: springdoc-openapi   Source File: OpenAPIBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets api def class.
 *
 * @param scanner the scanner
 * @param packagesToScan the packages to scan
 * @return the api def class
 */
private OpenAPIDefinition getApiDefClass(ClassPathScanningCandidateComponentProvider scanner,
		List<String> packagesToScan) {
	for (String pack : packagesToScan) {
		for (BeanDefinition bd : scanner.findCandidateComponents(pack)) {
			// first one found is ok
			try {
				return AnnotationUtils.findAnnotation(Class.forName(bd.getBeanClassName()),
						OpenAPIDefinition.class);
			}
			catch (ClassNotFoundException e) {
				LOGGER.error("Class Not Found in classpath : {}", e.getMessage());
			}
		}
	}
	return null;
}
 
Example 5
Source Project: springdoc-openapi   Source File: OpenAPIBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets security schemes classes.
 *
 * @param scanner the scanner
 * @param packagesToScan the packages to scan
 * @return the security schemes classes
 */
private Set<io.swagger.v3.oas.annotations.security.SecurityScheme> getSecuritySchemesClasses(
		ClassPathScanningCandidateComponentProvider scanner, List<String> packagesToScan) {
	Set<io.swagger.v3.oas.annotations.security.SecurityScheme> apiSecurityScheme = new HashSet<>();
	for (String pack : packagesToScan) {
		for (BeanDefinition bd : scanner.findCandidateComponents(pack)) {
			try {
				apiSecurityScheme.add(AnnotationUtils.findAnnotation(Class.forName(bd.getBeanClassName()),
						io.swagger.v3.oas.annotations.security.SecurityScheme.class));
			}
			catch (ClassNotFoundException e) {
				LOGGER.error("Class Not Found in classpath : {}", e.getMessage());
			}
		}
	}
	return apiSecurityScheme;
}
 
Example 6
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
	ClassPathScanningCandidateComponentProvider scanner = new ScanningComponent(Boolean.FALSE, this.environment);
	scanner.setResourceLoader(this.resourceLoader);

	AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(Network.class);
	scanner.addIncludeFilter(annotationTypeFilter);

	String packageName = ClassUtils.getPackageName(importingClassMetadata.getClassName());
	Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(packageName);
	candidateComponents.forEach(beanDefinition -> {
		AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition;
		AnnotationMetadata annotationMetadata = annotatedBeanDefinition.getMetadata();
		BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(NetworkFactory.class);
		String className = annotationMetadata.getClassName();
		definition.addPropertyValue(NetworkFactoryConstants.PROPERTY_VALUE.getValue(), className);
		definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

		AbstractBeanDefinition abstractBeanDefinition = definition.getBeanDefinition();
		BeanDefinitionHolder holder = new BeanDefinitionHolder(abstractBeanDefinition, className);
		BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);

	});

}
 
Example 7
Source Project: BootNettyRpc   Source File: NettyRpcRegistrar.java    License: Apache License 2.0 6 votes vote down vote up
protected ClassPathScanningCandidateComponentProvider getScanner() {

        return new ClassPathScanningCandidateComponentProvider( false, this.environment ) {

            @Override
            protected boolean isCandidateComponent(
                    AnnotatedBeanDefinition beanDefinition) {
                if (beanDefinition.getMetadata().isIndependent()) {

                    if (beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().getInterfaceNames().length == 1
                            && Annotation.class.getName().equals( beanDefinition.getMetadata().getInterfaceNames()[0] )) {
                        try {
                            Class<?> target = ClassUtils.forName( beanDefinition.getMetadata().getClassName(), NettyRpcRegistrar.this.classLoader );
                            return !target.isAnnotation();
                        } catch (Exception ex) {
                            this.logger.error( "Could not load target class: " + beanDefinition.getMetadata().getClassName(), ex );

                        }
                    }
                    return true;
                }
                return false;

            }
        };
    }
 
Example 8
Source Project: ESarch   Source File: CommandController.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
private void initializeCommandApi() {
    logger.info("Initialising the command API list.");

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    BASE_COMMAND_CLASS.forEach(superCmdClazz -> provider.addIncludeFilter(new AssignableTypeFilter(superCmdClazz)));

    List<String> commandClassNames = provider.findCandidateComponents(CORE_API_PACKAGE)
                                             .stream()
                                             .map(BeanDefinition::getBeanClassName)
                                             .collect(Collectors.toList());

    simpleToFullClassName = commandClassNames.stream().collect(Collectors.toMap(
            this::simpleCommandClassName, commandClassName -> commandClassName
    ));

    commandApi = commandClassNames.stream().collect(Collectors.toMap(
            this::simpleCommandClassName, this::commandJsonSchema
    ));

    logger.info("{} commands available.", commandApi.size());
}
 
Example 9
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
    GenericBeanDefinition beanPostProcessorDefinition = new GenericBeanDefinition();
    beanPostProcessorDefinition.setInstanceSupplier(()->this);
    beanPostProcessorDefinition.setBeanClass(BeanPostProcessor.class);
    registry.registerBeanDefinition("NettyRpcClientBeanPostProcessor",beanPostProcessorDefinition);

    ClassPathScanningCandidateComponentProvider scanner = getScanner();
    scanner.setResourceLoader(resourceLoader);
    scanner.addIncludeFilter(new AnnotationTypeFilter(NettyRpcClient.class));
    Map<String, Object> enableNettyRpcClientsAttributes = metadata.getAnnotationAttributes(enableNettyRpcClientsCanonicalName);

    for (String basePackage : getBasePackages(metadata,enableNettyRpcClientsAttributes)) {
        for (BeanDefinition candidateComponent : scanner.findCandidateComponents(basePackage)) {
            if (!(candidateComponent instanceof AnnotatedBeanDefinition)) {
                continue;
            }

            AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
            if(!beanDefinition.getMetadata().isInterface()) {
                throw new IllegalArgumentException("@NettyRpcClient can only be specified on an interface");
            }
            registerNettyRpcClient(beanDefinition,registry);
        }
    }
}
 
Example 10
Source Project: mercury   Source File: SimpleClassScanner.java    License: Apache License 2.0 6 votes vote down vote up
public List<Class<?>> getAnnotatedClasses(String scanPath, Class<? extends Annotation> type) {
    if (!scanPath.contains(".")) {
        throw new IllegalArgumentException(EX_START + scanPath + EX_END);
    }
    List<Class<?>> result = new ArrayList<>();
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AnnotationTypeFilter(type));
    for (BeanDefinition beanDef : provider.findCandidateComponents(scanPath)) {
        try {
            result.add(Class.forName(beanDef.getBeanClassName()));
        } catch (ClassNotFoundException e) {
            // ok to ignore
        }
    }
    return result;
}
 
Example 11
@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);
}
 
Example 12
Source Project: syndesis   Source File: ExternalSource.java    License: Apache License 2.0 6 votes vote down vote up
static Class<? extends ExecutionFactory<?, ?>> findTranslatorInPackage(String translatorName,
        ClassPathScanningCandidateComponentProvider provider, String packageName) {
    Set<BeanDefinition> components = provider.findCandidateComponents(packageName);
    for (BeanDefinition c : components) {
        try {
            @SuppressWarnings("unchecked")
            Class<? extends ExecutionFactory<?, ?>> clazz = (Class<? extends ExecutionFactory<?, ?>>) Class
            .forName(c.getBeanClassName());
            String name = clazz.getAnnotation(Translator.class).name();
            if (name.equals(translatorName)) {
                return clazz;
            }
        } catch (ClassNotFoundException | SecurityException | IllegalArgumentException e) {
            throw new IllegalStateException("Error loading translators", e);
        }
    }
    return null;
}
 
Example 13
Source Project: teiid-spring-boot   Source File: ExternalSource.java    License: Apache License 2.0 6 votes vote down vote up
static Class<? extends ExecutionFactory<?, ?>> findTranslatorInPackage(String translatorName,
        ClassPathScanningCandidateComponentProvider provider, String packageName) {
    Set<BeanDefinition> components = provider.findCandidateComponents(packageName);
    for (BeanDefinition c : components) {
        try {
            @SuppressWarnings("unchecked")
            Class<? extends ExecutionFactory<?, ?>> clazz = (Class<? extends ExecutionFactory<?, ?>>) Class
            .forName(c.getBeanClassName());
            String name = clazz.getAnnotation(Translator.class).name();
            if (name.equals(translatorName)) {
                return clazz;
            }
        } catch (ClassNotFoundException | SecurityException | IllegalArgumentException e) {
            throw new IllegalStateException("Error loading translators", e);
        }
    }
    return null;
}
 
Example 14
Source Project: spring-data-cosmosdb   Source File: CosmosConfigurationSupport.java    License: MIT License 6 votes vote down vote up
protected Set<Class<?>> scanForEntities(String basePackage) throws ClassNotFoundException {
    if (!StringUtils.hasText(basePackage)) {
        return Collections.emptySet();
    }

    final Set<Class<?>> initialEntitySet = new HashSet<>();

    if (StringUtils.hasText(basePackage)) {
        final ClassPathScanningCandidateComponentProvider componentProvider =
                new ClassPathScanningCandidateComponentProvider(false);

        componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class));

        for (final BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {
            final String className = candidate.getBeanClassName();
            Assert.notNull(className, "Bean class name is null.");

            initialEntitySet
                    .add(ClassUtils.forName(className, CosmosConfigurationSupport.class.getClassLoader()));
        }
    }

    return initialEntitySet;
}
 
Example 15
Source Project: usergrid   Source File: Schema.java    License: Apache License 2.0 6 votes vote down vote up
@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 );
        }
    }
}
 
Example 16
Source Project: line-bot-sdk-java   Source File: ReplyEventTest.java    License: Apache License 2.0 6 votes vote down vote up
private static List<Class<?>> getAllEventClass() {
    ClassPathScanningCandidateComponentProvider scanningProvider =
            new ClassPathScanningCandidateComponentProvider(false);
    scanningProvider
            .addIncludeFilter((metadataReader, metadataReaderFactory) -> true);

    return scanningProvider.findCandidateComponents(Event.class.getPackage().getName())
                           .stream()
                           .map(BeanDefinition::getBeanClassName)
                           .map(className -> {
                               try {
                                   return (Class<?>) Class.forName(className);
                               } catch (ClassNotFoundException e) {
                                   throw new RuntimeException(e);
                               }
                           })
                           .filter(Event.class::isAssignableFrom)
                           .collect(toList());
}
 
Example 17
Source Project: warpdb   Source File: ClassUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Scan @Entity classes in base packages.
 * 
 * @param basePackages
 *            base package names.
 * @return List of entity class.
 */
public static List<Class<?>> scanEntities(String... basePackages) {
	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
	provider.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
	List<Class<?>> classes = new ArrayList<>();
	for (String basePackage : basePackages) {
		Set<BeanDefinition> beans = provider.findCandidateComponents(basePackage);
		for (BeanDefinition bean : beans) {
			try {
				classes.add(Class.forName(bean.getBeanClassName()));
			} catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
		}
	}
	return classes;
}
 
Example 18
Source Project: cqrs-es-kafka   Source File: CommandHandlerUtils.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 19
Source Project: cqrs-es-kafka   Source File: EventHandlerUtils.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 20
Source Project: moserp   Source File: RestConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@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()]));
}
 
Example 21
Source Project: onetwo   Source File: AnnotationMetadataHelper.java    License: Apache License 2.0 6 votes vote down vote up
public List<BeanDefinition> scanBeanDefinitions(Class<? extends Annotation> annoClass, String...extraPackagesToScans){
	ClassPathScanningCandidateComponentProvider scanner = createAnnotationScanner(classLoader, annoClass);
	if(resourceLoader!=null){
		scanner.setResourceLoader(resourceLoader);
	}
	/*Set<String> basePackages = getBasePackages();
	for (String basePackage : basePackages) {
		Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(basePackage);
		for (BeanDefinition candidateComponent : candidateComponents) {
			consumer.accept(candidateComponent);
		}
	}*/
	Set<String> basePackages = getBasePackages();
	if(!LangUtils.isEmpty(extraPackagesToScans)){
		basePackages.addAll(Arrays.asList(extraPackagesToScans));
	}
	return basePackages.stream()
						.flatMap(pack->scanner.findCandidateComponents(pack).stream())
						.collect(Collectors.toList());
}
 
Example 22
private static List<DTOContainer<?>> findAllDTOs() throws ClassNotFoundException {
    final List<DTOContainer<?>> fondJsonCreatorClasses = new ArrayList<>();

    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            true);
    scanner.addIncludeFilter((metadataReader, metadataReaderFactory) -> true);

    final Stream<String> classNamesStream = scanner.findCandidateComponents("org.phoenicis").stream()
            .map(BeanDefinition::getBeanClassName);
    final Iterable<String> classNames = classNamesStream::iterator;

    for (String className : classNames) {
        final Class<?> clazz = Class.forName(className);
        if (isJsonClass(clazz)) {
            fondJsonCreatorClasses.add(new DTOContainer<>(clazz));
        }
    }

    return fondJsonCreatorClasses;
}
 
Example 23
private static List<TranslatableContainer<?>> findAllTranslatables() throws ClassNotFoundException {
    final List<TranslatableContainer<?>> foundClasses = new ArrayList<>();

    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            true);
    scanner.addIncludeFilter((metadataReader, metadataReaderFactory) -> true);

    final Stream<String> classNamesStream = scanner.findCandidateComponents("org.phoenicis").stream()
            .map(BeanDefinition::getBeanClassName);
    final Iterable<String> classNames = classNamesStream::iterator;

    for (String className : classNames) {
        final Class<?> clazz = Class.forName(className);
        if (isTranslatable(clazz)) {
            foundClasses.add(new TranslatableContainer<>(clazz));
        }
    }

    return foundClasses;
}
 
Example 24
Source Project: zstack   Source File: InventoryIndexManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void populateTriggerVOs() throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AnnotationTypeFilter(TriggerIndex.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    for (String pkg : getBasePkgNames()) {
        for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
            Class<?> triggerVO = Class.forName(bd.getBeanClassName());
            if (!triggerVO.isAnnotationPresent(Entity.class)) {
                throw new IllegalArgumentException(String.format("Class[%s] is annotated by @TriggerIndex, but not annotated by @Entity",
                        triggerVO.getName()));
            }
            triggerVOs.add(triggerVO);
            popluateTriggerVONamesCascade(triggerVO);
        }
    }
}
 
Example 25
Source Project: zstack   Source File: ConfigurationManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
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);
            }
        }
    }
}
 
Example 26
Source Project: zstack   Source File: ConfigurationManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void generateInventoryPythonClass(StringBuilder sb, List<String> basePkgs) {
    List<String> inventoryPython = new ArrayList<>();
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(PythonClassInventory.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Component.class));
    for (String pkg : basePkgs) {
        for (BeanDefinition bd : scanner.findCandidateComponents(pkg).stream().sorted((bd1, bd2) -> {
            return bd1.getBeanClassName().compareTo(bd2.getBeanClassName());
        }).collect(Collectors.toList())) {
            try {
                Class<?> clazz = Class.forName(bd.getBeanClassName());
                if (isPythonClassGenerated(clazz)) {
                    /* This class was generated as other's parent class */
                    continue;
                }
                inventoryPython.add(classToInventoryPythonClass(clazz));
            } catch (Exception e) {
                logger.warn(String.format("Unable to generate python class for %s", bd.getBeanClassName()), e);
            }
        }
    }

    for (String invstr : inventoryPython) {
        sb.append(invstr);
    }
}
 
Example 27
Source Project: zstack   Source File: RESTApiFacadeImpl.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 28
@Test
public void failIfNewTypeOfMaterialIsNotAddedInTheAboveTest() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AssignableTypeFilter(MaterialConfig.class));
    Set<BeanDefinition> candidateComponents = provider.findCandidateComponents("com/thoughtworks");
    List<Class> reflectionsSubTypesOf = candidateComponents.stream().map(beanDefinition -> beanDefinition.getBeanClassName()).map(s -> {
        try {
            return Class.forName(s);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }).collect(Collectors.toList());

    reflectionsSubTypesOf.removeIf(this::isNotAConcrete_NonTest_MaterialConfigImplementation);

    List<Class> allExpectedMaterialConfigImplementations = allMaterialConfigsWhichAreDataPointsInThisTest();

    assertThatAllMaterialConfigsInCodeAreTestedHere(reflectionsSubTypesOf, allExpectedMaterialConfigImplementations);
}
 
Example 29
Source Project: ranger   Source File: RangerRESTAPIFilter.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private List<Class> findClasses(String packageName)
		throws ClassNotFoundException {
	List<Class> classes = new ArrayList<Class>();

	ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
			true);

	// scanner.addIncludeFilter(new
	// AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));

	for (BeanDefinition bd : scanner.findCandidateComponents(packageName)) {
		classes.add(Class.forName(bd.getBeanClassName()));
	}

	return classes;
}
 
Example 30
/**
 * Scans the mapping base package for classes annotated with {@link Table}.
 * 
 * @see #getMappingBasePackage()
 * @return
 * @throws ClassNotFoundException
 */
protected Set<Class<?>> getInitialEntitySet() throws ClassNotFoundException {

	String basePackage = getMappingBasePackage();
	Set<Class<?>> initialEntitySet = new HashSet<>();

	if (hasText(basePackage)) {
		ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(false);
		componentProvider.addIncludeFilter(new AnnotationTypeFilter(Table.class));
		componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class));

		for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {
			initialEntitySet.add(ClassUtils.forName(candidate.getBeanClassName(), AbstractCrateConfiguration.class.getClassLoader()));
		}
	}

	return initialEntitySet;
}