List of usage examples for org.springframework.context.annotation ClassPathScanningCandidateComponentProvider findCandidateComponents
public Set<BeanDefinition> findCandidateComponents(String basePackage)
From source file:org.springframework.data.gemfire.config.annotation.support.GemFireComponentClassTypeScanner.java
/** * Scans the {@link Set} of base packages searching for GemFire application components * accepted by the filters of this scanner. * * @return a {@link Set} of GemFire application component {@link Class} types found on the classpath. * @see #newClassPathScanningCandidateComponentProvider(boolean) * @see java.util.Set/* ww w. ja va 2 s . c o m*/ */ public Set<Class<?>> scan() { Set<Class<?>> componentClasses = new CopyOnWriteArraySet<>(); ClassLoader entityClassLoader = getEntityClassLoader(); ClassPathScanningCandidateComponentProvider componentProvider = newClassPathScanningCandidateComponentProvider(); stream(this.spliterator(), true) .flatMap(packageName -> componentProvider.findCandidateComponents(packageName).stream()) .forEach(beanDefinition -> { Optional.ofNullable(beanDefinition.getBeanClassName()).filter(StringUtils::hasText) .ifPresent(beanClassName -> { try { componentClasses.add(ClassUtils.forName(beanClassName, entityClassLoader)); } catch (ClassNotFoundException ignore) { log.warn(String.format("Class for component type [%s] not found", beanDefinition.getBeanClassName())); } }); }); return componentClasses; }
From source file:org.springframework.data.gemfire.function.config.AbstractFunctionExecutionConfigurationSource.java
public Collection<ScannedGenericBeanDefinition> getCandidates(ResourceLoader loader) { ClassPathScanningCandidateComponentProvider scanner = new FunctionExecutionComponentProvider( getIncludeFilters(), functionExecutionAnnotationTypes); scanner.setResourceLoader(loader);//from www. j av a 2 s . c o m for (TypeFilter filter : getExcludeFilters()) { scanner.addExcludeFilter(filter); } Set<ScannedGenericBeanDefinition> result = new HashSet<ScannedGenericBeanDefinition>(); for (String basePackage : getBasePackages()) { if (logger.isDebugEnabled()) { logger.debug("scanning package " + basePackage); } Collection<BeanDefinition> components = scanner.findCandidateComponents(basePackage); for (BeanDefinition definition : components) { result.add((ScannedGenericBeanDefinition) definition); } } return result; }
From source file:org.springframework.data.repository.config.AbstractRepositoryConfigDefinitionParser.java
private Set<String> getRepositoryInterfacesForAutoConfig(S config, ResourceLoader loader, ReaderContext reader) {/* ww w. jav a 2 s .com*/ ClassPathScanningCandidateComponentProvider scanner = new RepositoryComponentProvider( config.getRepositoryBaseInterface()); scanner.setResourceLoader(loader); TypeFilterParser parser = new TypeFilterParser(loader.getClassLoader(), reader); parser.parseFilters(config.getSource(), scanner); Set<BeanDefinition> findCandidateComponents = scanner.findCandidateComponents(config.getBasePackage()); Set<String> interfaceNames = new HashSet<String>(); for (BeanDefinition definition : findCandidateComponents) { interfaceNames.add(definition.getBeanClassName()); } return interfaceNames; }
From source file:org.springframework.data.repository.config.AbstractRepositoryConfigDefinitionParser.java
/** * Tries to detect a custom implementation for a repository bean by classpath scanning. * /*from w w w .j a va 2 s . c o m*/ * @param config * @param parser * @return the {@code AbstractBeanDefinition} of the custom implementation or {@literal null} if none found */ private AbstractBeanDefinition detectCustomImplementation(T config, ParserContext parser) { // Build pattern to lookup implementation class Pattern pattern = Pattern.compile(".*\\." + config.getImplementationClassName()); // Build classpath scanner and lookup bean definition ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider( false); provider.setResourceLoader(parser.getReaderContext().getResourceLoader()); provider.addIncludeFilter(new RegexPatternTypeFilter(pattern)); Set<BeanDefinition> definitions = provider.findCandidateComponents(config.getBasePackage()); if (definitions.size() == 0) { return null; } if (definitions.size() == 1) { return (AbstractBeanDefinition) definitions.iterator().next(); } List<String> implementationClassNames = new ArrayList<String>(); for (BeanDefinition bean : definitions) { implementationClassNames.add(bean.getBeanClassName()); } throw new IllegalStateException(String.format( "Ambiguous custom implementations detected! Found %s but expected a single implementation!", StringUtils.collectionToCommaDelimitedString(implementationClassNames))); }
From source file:org.springframework.data.repository.config.RepositoryBeanDefinitionBuilder.java
/** * Tries to detect a custom implementation for a repository bean by classpath scanning. * // www.j a v a2s.c o m * @param config * @param parser * @return the {@code AbstractBeanDefinition} of the custom implementation or {@literal null} if none found */ private AbstractBeanDefinition detectCustomImplementation(BeanDefinitionRegistry registry, ResourceLoader loader) { // Build pattern to lookup implementation class Pattern pattern = Pattern.compile(".*\\." + configuration.getImplementationClassName()); // Build classpath scanner and lookup bean definition ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider( false); provider.setResourceLoader(loader); provider.addIncludeFilter(new RegexPatternTypeFilter(pattern)); Set<BeanDefinition> definitions = new HashSet<BeanDefinition>(); for (String basePackage : configuration.getBasePackages()) { definitions.addAll(provider.findCandidateComponents(basePackage)); } if (definitions.isEmpty()) { return null; } if (definitions.size() == 1) { return (AbstractBeanDefinition) definitions.iterator().next(); } List<String> implementationClassNames = new ArrayList<String>(); for (BeanDefinition bean : definitions) { implementationClassNames.add(bean.getBeanClassName()); } throw new IllegalStateException(String.format( "Ambiguous custom implementations detected! Found %s but expected a single implementation!", StringUtils.collectionToCommaDelimitedString(implementationClassNames))); }
From source file:org.springframework.retry.backoff.BackOffPolicySerializationTests.java
@Parameters(name = "{index}: {0}") public static List<Object[]> policies() { List<Object[]> result = new ArrayList<Object[]>(); ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true); scanner.addIncludeFilter(new AssignableTypeFilter(BackOffPolicy.class)); scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Test.*"))); scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Mock.*"))); scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Configuration.*"))); Set<BeanDefinition> candidates = scanner.findCandidateComponents("org.springframework.retry"); for (BeanDefinition beanDefinition : candidates) { try {/*from ww w. j a v a 2 s . c om*/ result.add(new Object[] { BeanUtils .instantiate(ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), null)) }); } catch (Exception e) { logger.warn("Cannot create instance of " + beanDefinition.getBeanClassName()); } } return result; }
From source file:org.springframework.retry.policy.RetryContextSerializationTests.java
@Parameters(name = "{index}: {0}") public static List<Object[]> policies() { List<Object[]> result = new ArrayList<Object[]>(); ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true); scanner.addIncludeFilter(new AssignableTypeFilter(RetryPolicy.class)); scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Test.*"))); scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Mock.*"))); Set<BeanDefinition> candidates = scanner.findCandidateComponents("org.springframework.retry.policy"); for (BeanDefinition beanDefinition : candidates) { try {/*from w w w . jav a2 s .co m*/ result.add(new Object[] { BeanUtils .instantiate(ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), null)) }); } catch (Exception e) { logger.warn("Cannot create instance of " + beanDefinition.getBeanClassName(), e); } } ExceptionClassifierRetryPolicy extra = new ExceptionClassifierRetryPolicy(); extra.setExceptionClassifier(new SubclassClassifier<Throwable, RetryPolicy>(new AlwaysRetryPolicy())); result.add(new Object[] { extra }); return result; }
From source file:org.tdar.core.service.ReflectionService.java
/** * Find all classes that implement the identified Class * /*from w ww . ja v a 2 s. c o m*/ * @param cls * @return */ public static Set<BeanDefinition> findClassesThatImplement(Class<?> cls) { ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider( false); scanner.addIncludeFilter(new AssignableTypeFilter(cls)); String basePackage = ORG_TDAR2; Set<BeanDefinition> findCandidateComponents = scanner.findCandidateComponents(basePackage); return findCandidateComponents; }
From source file:org.tdar.core.service.ReflectionService.java
/** * find all Classes that support the identified Annotation * /*from w ww .ja va 2s . co m*/ * @param annots * @return * @throws NoSuchBeanDefinitionException * @throws ClassNotFoundException */ @SafeVarargs public static Class<?>[] scanForAnnotation(Class<? extends Annotation>... annots) throws ClassNotFoundException { List<Class<?>> toReturn = new ArrayList<>(); ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider( false); for (Class<? extends Annotation> annot : annots) { scanner.addIncludeFilter(new AnnotationTypeFilter(annot)); } String basePackage = ORG_TDAR2; for (BeanDefinition bd : scanner.findCandidateComponents(basePackage)) { String beanClassName = bd.getBeanClassName(); Class<?> cls = Class.forName(beanClassName); toReturn.add(cls); } return toReturn.toArray(new Class<?>[0]); }
From source file:org.teiid.spring.autoconfigure.TeiidServer.java
boolean findAndConfigureViews(VDBMetaData vdb, ApplicationContext context, PhysicalNamingStrategy namingStrategy) { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider( false);/* w w w . ja v a2 s . c o m*/ provider.addIncludeFilter(new AnnotationTypeFilter(javax.persistence.Entity.class)); provider.addIncludeFilter(new AnnotationTypeFilter(javax.persistence.Embeddable.class)); provider.addIncludeFilter(new AnnotationTypeFilter(SelectQuery.class)); provider.addIncludeFilter(new AnnotationTypeFilter(UserDefinedFunctions.class)); String basePackage = context.getEnvironment().getProperty(TeiidConstants.ENTITY_SCAN_DIR); if (basePackage == null) { logger.warn("***************************************************************"); logger.warn("\"" + TeiidConstants.ENTITY_SCAN_DIR + "\" is NOT set, scanning entire classpath for @Entity classes."); logger.warn("consider setting this property to avoid time consuming scanning"); logger.warn("***************************************************************"); basePackage = "*"; } // check to add any source models first based on the annotations boolean load = false; Set<BeanDefinition> components = provider.findCandidateComponents(basePackage); for (BeanDefinition c : components) { try { Class<?> clazz = Class.forName(c.getBeanClassName()); ExcelTable excelAnnotation = clazz.getAnnotation(ExcelTable.class); if (excelAnnotation != null) { addExcelModel(vdb, clazz, excelAnnotation); load = true; } } catch (ClassNotFoundException e) { logger.warn("Error loading entity classes"); } } ModelMetaData model = new ModelMetaData(); model.setName(EXPOSED_VIEW); model.setModelType(Model.Type.VIRTUAL); MetadataFactory mf = new MetadataFactory(VDBNAME, VDBVERSION, SystemMetadata.getInstance().getRuntimeTypeMap(), model); if (components.isEmpty()) { if (isRedirectUpdatesEnabled(context)) { // when no @entity classes are defined then this is service based, sniff the // metadata // from Teiid models that are defined and build Hibernate metadata from it. buildVirtualBaseLayer(vdb, context, mf); } else { return false; } } Metadata metadata = getMetadata(components, namingStrategy, mf); UDFProcessor udfProcessor = new UDFProcessor(metadata, vdb); for (BeanDefinition c : components) { try { Class<?> clazz = Class.forName(c.getBeanClassName()); Entity entityAnnotation = clazz.getAnnotation(Entity.class); SelectQuery selectAnnotation = clazz.getAnnotation(SelectQuery.class); TextTable textAnnotation = clazz.getAnnotation(TextTable.class); JsonTable jsonAnnotation = clazz.getAnnotation(JsonTable.class); ExcelTable excelAnnotation = clazz.getAnnotation(ExcelTable.class); UserDefinedFunctions udfAnnotation = clazz.getAnnotation(UserDefinedFunctions.class); if (textAnnotation != null && entityAnnotation != null) { new TextTableView(metadata).buildView(clazz, mf, textAnnotation); } else if (jsonAnnotation != null && entityAnnotation != null) { new JsonTableView(metadata).buildView(clazz, mf, jsonAnnotation); } else if (selectAnnotation != null && entityAnnotation != null) { new SimpleView(metadata).buildView(clazz, mf, selectAnnotation); } else if (excelAnnotation != null && entityAnnotation != null) { new ExcelTableView(metadata).buildView(clazz, mf, excelAnnotation); } else if (udfAnnotation != null) { udfProcessor.buildFunctions(clazz, mf, udfAnnotation); } else if (selectAnnotation == null && entityAnnotation != null) { new EntityBaseView(metadata, vdb, this).buildView(clazz, mf, entityAnnotation); } // check for sequence if (entityAnnotation != null) { udfProcessor.buildSequence(clazz, mf, entityAnnotation); } } catch (ClassNotFoundException e) { logger.warn("Error loading entity classes"); } } udfProcessor.finishProcessing(); // check if the redirection is in play if (isRedirectUpdatesEnabled(context)) { String redirectedDSName = getRedirectedDataSource(context); try { // rename current view model to something else model.setName("internal"); model.setVisible(false); DataSource redirectedDS = (DataSource) ((SBConnectionFactoryProvider) getConnectionFactoryProviders() .get(redirectedDSName)).getBean(); String driverName = getDriverName(redirectedDS); if (driverName == null) { throw new IllegalStateException("Redirection of updates enabled, however datasource" + " configured for redirection is not recognized."); } RedirectionSchemaBuilder mg = new RedirectionSchemaBuilder(context, redirectedDSName); // if none of the annotations defined, create layer with tables from all data // sources if (mf.getSchema().getTables().isEmpty()) { throw new IllegalStateException("Redirection of updates enabled, however there are no " + "@Entity found. There must be atleast one @Entity for this feature to work."); } // now add the modified model that does the redirection ModelMetaData exposedModel = mg.buildRedirectionLayer(mf, EXPOSED_VIEW); vdb.addModel(exposedModel); // we need to create the schema in the redirected data source to store the // ephemeral data, will use // hibernate metadata for schema generation techniques. ModelMetaData redirectedModel = vdb.getModel(redirectedDSName); assert (redirectedModel != null); String dialect = redirectedModel.getPropertyValue(DIALECT); if (dialect == null) { throw new IllegalStateException( "Redirection is enabled, however data source named \"" + redirectedDSName + "\" cannot be used with schema initialization, choose a different data source" + "as there are no schema generation facilities for this data source."); } new RedirectionSchemaInitializer(redirectedDS, redirectedDSName, getDialect(dialect), metadata, this.metadataSources.getServiceRegistry(), mf.getSchema(), context).init(); // reload the redirection model as it has new entries now after schema // generation. try { vdb.addModel(buildModelFromDataSource(redirectedDSName, driverName, context, false)); } catch (AdminException e) { throw new IllegalStateException("Error adding the source, cause: " + e.getMessage()); } load = true; } catch (BeansException e) { throw new IllegalStateException("Redirection is enabled, however data source named \"" + redirectedDSName + "\" is not configured. Please configure a data source."); } } if (!mf.getSchema().getTables().isEmpty()) { load = true; String ddl = DDLStringVisitor.getDDLString(mf.getSchema(), null, null); model.addSourceMetadata("DDL", ddl); vdb.addModel(model); } return load; }