org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider Java Examples

The following examples show how to use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider. 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 File: Neo4jConfigurationSupport.java    From sdn-rx with Apache License 2.0 7 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 #2
Source File: SpringControllerResolver.java    From RestDoc with 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 #3
Source File: ConfigurationManagerImpl.java    From zstack with 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 #4
Source File: RangerRESTAPIFilter.java    From ranger with 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 #5
Source File: MagicalMaterialAndMaterialConfigConversionTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: QueryByCriteriaJaxbTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: WebServicesImplTest.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
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());
        }
    }
}
 
Example #8
Source File: OpenAPIBuilder.java    From springdoc-openapi with 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 #9
Source File: CommandController.java    From ESarch with 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 #10
Source File: NettyRpcRegistrar.java    From BootNettyRpc with 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 #11
Source File: OpenAPIBuilder.java    From springdoc-openapi with 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 #12
Source File: NetworkAssemble.java    From network-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: ErrorService.java    From gemini with 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 #14
Source File: AJExtensionsCompileTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #15
Source File: RESTApiFacadeImpl.java    From zstack with 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 #16
Source File: ExternalSource.java    From syndesis with 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 #17
Source File: ConfigurationManagerImpl.java    From zstack with 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 #18
Source File: ValidIfExactlyOneNonNullCheckerTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllAnnotatedClasses() throws NoSuchFieldException, ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(ValidIfExactlyOneNonNull.class));
    for (BeanDefinition def : scanner.findCandidateComponents("com.sequenceiq.redbeams")) {
        String annotatedClassName = def.getBeanClassName();
        Class<?> annotatedClass = Class.forName(annotatedClassName);
        ValidIfExactlyOneNonNull classAnnotation = annotatedClass.getAnnotation(ValidIfExactlyOneNonNull.class);
        String[] fields = classAnnotation.fields();
        if (fields.length == 0) {
            fail("ValidIfExactlyOneNonNull annotation on class " + annotatedClassName + " has no fields");
        }
        for (String fieldName : classAnnotation.fields()) {
            annotatedClass.getDeclaredField(fieldName);
            // if this does not throw an exception, great
        }
    }
}
 
Example #19
Source File: ExternalSource.java    From teiid-spring-boot with 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 #20
Source File: CosmosConfigurationSupport.java    From spring-data-cosmosdb with 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 #21
Source File: InventoryIndexManagerImpl.java    From zstack with 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 #22
Source File: TranslatableContractTest.java    From phoenicis with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #23
Source File: DTOContractTest.java    From phoenicis with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #24
Source File: AnnotationMetadataHelper.java    From onetwo with 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 #25
Source File: RestConfiguration.java    From moserp with 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 #26
Source File: EventHandlerUtils.java    From cqrs-es-kafka with 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 #27
Source File: Schema.java    From usergrid with 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 #28
Source File: ReplyEventTest.java    From line-bot-sdk-java with 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 #29
Source File: CommandHandlerUtils.java    From cqrs-es-kafka with 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 #30
Source File: ClassUtils.java    From warpdb with 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;
}