Java Code Examples for org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#addIncludeFilter()

The following examples show how to use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#addIncludeFilter() . 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: PluginResolver.java    From ecs-sync with Apache License 2.0 6 votes vote down vote up
public PluginResolver() {
    try {
        ClassPathScanningCandidateComponentProvider pluginScanner = new ClassPathScanningCandidateComponentProvider(false);
        pluginScanner.addIncludeFilter(new AnnotationTypeFilter(StorageConfig.class));
        pluginScanner.addIncludeFilter(new AnnotationTypeFilter(FilterConfig.class));

        final List<Class> pluginClasses = new ArrayList<>();
        pluginClasses.addAll(Arrays.asList(SyncConfig.class, HostInfo.class, JobControl.class, JobList.class, SyncProgress.class));
        for (BeanDefinition beanDef : pluginScanner.findCandidateComponents("com.emc.ecs.sync")) {
            pluginClasses.add(Class.forName(beanDef.getBeanClassName()));
        }

        context = JAXBContext.newInstance(pluginClasses.toArray(new Class[0]));
    } catch (ClassNotFoundException | JAXBException e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
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 4
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 5
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 6
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 7
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 8
Source File: Deployer.java    From zstack with Apache License 2.0 6 votes vote down vote up
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()));
        }

    }
}
 
Example 9
Source File: SpringClassHierarchySupplier.java    From feign-error-decoder with MIT License 6 votes vote down vote up
@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());
}
 
Example 10
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 11
Source File: RestResourceConfig.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@Autowired
public RestResourceConfig(final ApplicationContext applicationContext) {
    property("contextConfig", applicationContext);
    scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.resetFilters(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Path.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(Provider.class));
    register(RequestContextFilter.class);
    register(MultiPartFeature.class);
    register(ObjectMapperProvider.class);
    register(JacksonFeature.class);
    registerResources("com.clicktravel.cheddar.rest.exception.mapper", "com.clicktravel.cheddar.server.http.filter",
            "com.clicktravel.cheddar.server.rest.resource.status", "com.clicktravel.services",
            "com.clicktravel.cheddar.rest.body.writer");
    property(ServerProperties.LOCATION_HEADER_RELATIVE_URI_RESOLUTION_DISABLED, true);
    property(ServerProperties.WADL_FEATURE_DISABLE, true);
}
 
Example 12
Source File: ReflectionHelper.java    From streamline with Apache License 2.0 5 votes vote down vote up
public static Collection<Class<?>> getAnnotatedClasses(String basePackage, Class<? extends Annotation> annotation) {
    Collection<Class<?>> classes = new ArrayList<>();
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AnnotationTypeFilter(annotation));
    for (BeanDefinition beanDef : provider.findCandidateComponents(basePackage)) {
        try {
            classes.add(Class.forName(beanDef.getBeanClassName()));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    return classes;
}
 
Example 13
Source File: OpenAPIGenerator.java    From spring-openapi with MIT License 5 votes vote down vote up
private Map<String, PathItem> createPathExtensions() {
ClassPathScanningCandidateComponentProvider scanner = createClassPathScanningCandidateComponentProvider();
scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));

      List<Class<?>> controllerClasses = new ArrayList<>();
      List<String> packagesWithoutRegex = removeRegexFormatFromPackages(controllerBasePackages);
      for (String controllerPackage : packagesWithoutRegex) {
          logger.debug("Scanning controller package=[{}]", controllerPackage);
          for (BeanDefinition beanDefinition : scanner.findCandidateComponents(controllerPackage)) {
              logger.debug("Scanning controller class=[{}]", beanDefinition.getBeanClassName());
              controllerClasses.add(getClass(beanDefinition));
          }
      }
      return operationsTransformer.transformOperations(controllerClasses);
  }
 
Example 14
Source File: CmisRegistrar.java    From spring-content with Apache License 2.0 5 votes vote down vote up
void cmisDocumentScan(String... basePackages) {
	ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
	scanner.addIncludeFilter(new AnnotationTypeFilter(CmisDocument.class));

	for (String basePackage : basePackages) {
		for (BeanDefinition bd : scanner.findCandidateComponents(basePackage)) {

			cmisDocumentBeanDefinition = bd;

			CmisEntityRepositoryComponentProvider cmisRepoScanner = new CmisEntityRepositoryComponentProvider(bd.getBeanClassName(), classLoader);
			scanner.setResourceLoader(resourceLoader);
			scanner.setEnvironment(environment);
			for (int i =0; i < basePackages.length && cmisDocumentRepositoryBeanDefinition == null; i++) {
				cmisDocumentRepositoryBeanDefinition = cmisRepoScanner.findCandidateComponents(basePackages[i])
						.stream()
						.findFirst()
						.get();
			}

			CmisEntityStorageComponentProvider cmisStoreScanner = new CmisEntityStorageComponentProvider(bd.getBeanClassName(), classLoader);
			scanner.setResourceLoader(resourceLoader);
			scanner.setEnvironment(environment);
			for (int i =0; i < basePackages.length && cmisDocumentStoreBeanDefinition == null; i++) {
				cmisDocumentStoreBeanDefinition = cmisStoreScanner.findCandidateComponents(basePackages[i])
					.stream()
					.findFirst()
					.get();
			}
		}
	}
}
 
Example 15
Source File: ExternalSource.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public static Class<? extends ExecutionFactory<?, ?>> translatorClass(String translatorName, String basePackage) {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AnnotationTypeFilter(Translator.class));
    Class<? extends ExecutionFactory<?, ?>> clazz = findTranslatorInPackage(translatorName, provider,
            "org.teiid.translator");
    if (clazz == null) {
        clazz = findTranslatorInPackage(translatorName, provider,basePackage);
    }
    return clazz;
}
 
Example 16
Source File: AnnotationsScanner.java    From mdw with Apache License 2.0 5 votes vote down vote up
/**
 * TODO: Only handles @Activity annotations at the moment.
 * @Monitor would also be a good candidate.
 */
private ClassPathScanningCandidateComponentProvider createScannerComponentProvider() {
    ClassPathScanningCandidateComponentProvider provider
            = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AnnotationTypeFilter(Activity.class));
    return provider;
}
 
Example 17
Source File: ConfigurationManagerImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void handle(APIGenerateSqlVOViewMsg msg) {
    try {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
        scanner.addIncludeFilter(new AnnotationTypeFilter(EO.class));
        scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
        scanner.addExcludeFilter(new AnnotationTypeFilter(Component.class));
        StringBuilder sb = new StringBuilder();
        for (String pkg : msg.getBasePackageNames()) {
            for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
                Class<?> entityClazz = Class.forName(bd.getBeanClassName());
                generateVOViewSql(sb, entityClazz);
            }
        }

        String exportPath = PathUtil.join(System.getProperty("user.home"), "zstack-mysql-view");
        FileUtils.deleteDirectory(new File(exportPath));
        File folder = new File(exportPath);
        folder.mkdirs();
        File outfile = new File(PathUtil.join(exportPath, "view.sql"));
        FileUtils.writeStringToFile(outfile, sb.toString());

        APIGenerateSqlVOViewEvent evt = new APIGenerateSqlVOViewEvent(msg.getId());
        bus.publish(evt);
    } catch (Exception e) {
        throw new CloudRuntimeException(e);
    }
}
 
Example 18
Source File: ObjectMapperSubtypeConfigurer.java    From kork with Apache License 2.0 5 votes vote down vote up
private NamedType[] findSubtypes(Class<?> clazz, String pkg) {
  ClassPathScanningCandidateComponentProvider provider =
      new ClassPathScanningCandidateComponentProvider(false);
  provider.addIncludeFilter(new AssignableTypeFilter(clazz));

  return provider.findCandidateComponents(pkg).stream()
      .map(
          bean -> {
            Class<?> cls =
                ClassUtils.resolveClassName(
                    bean.getBeanClassName(), ClassUtils.getDefaultClassLoader());

            JsonTypeName nameAnnotation = cls.getAnnotation(JsonTypeName.class);
            if (nameAnnotation == null || "".equals(nameAnnotation.value())) {
              String message =
                  "Subtype " + cls.getSimpleName() + " does not have a JsonTypeName annotation";
              if (strictSerialization) {
                throw new InvalidSubtypeConfigurationException(message);
              }
              log.warn(message);
              return null;
            }

            return new NamedType(cls, nameAnnotation.value());
          })
      .filter(Objects::nonNull)
      .toArray(NamedType[]::new);
}
 
Example 19
Source File: SpringRestConfiguration.java    From galeb with Apache License 2.0 4 votes vote down vote up
private Set<BeanDefinition> allBeansDomain() {
    final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));
    return provider.findCandidateComponents("io.galeb.core.entity");
}
 
Example 20
Source File: Java110ListenerDiscoveryRegistrar.java    From MicroCommunity with Apache License 2.0 4 votes vote down vote up
/**
 * 注册侦听
 * @param metadata
 * @param registry
 */
public void registerListener(AnnotationMetadata metadata,
                             BeanDefinitionRegistry registry) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    ClassPathScanningCandidateComponentProvider scanner = getScanner();
    scanner.setResourceLoader(this.resourceLoader);
    Set<String> basePackages;
    Map<String, Object> attrs = metadata
            .getAnnotationAttributes(Java110ListenerDiscovery.class.getName());

    Object listenerPublishClassObj =  attrs.get("listenerPublishClass");

    Assert.notNull(listenerPublishClassObj,"Java110ListenerDiscovery 没有配置 listenerPublishClass 属性");

    Class<?> listenerPublishClass = (Class<?>) listenerPublishClassObj;

    AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
            Java110Listener.class);

    scanner.addIncludeFilter(annotationTypeFilter);
    basePackages = getBasePackages(metadata);

    for (String basePackage : basePackages) {
        Set<BeanDefinition> candidateComponents = scanner
                .findCandidateComponents(basePackage);
        for (BeanDefinition candidateComponent : candidateComponents) {
            if (candidateComponent instanceof AnnotatedBeanDefinition) {
                // verify annotated class is an interface
                AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
                AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();


                Map<String, Object> attributes = annotationMetadata
                        .getAnnotationAttributes(
                                Java110Listener.class.getCanonicalName());

                String beanName = getListenerName(attributes,beanDefinition);

                /*BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(beanDefinition, beanName);
                BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);*/
                Method method = listenerPublishClass.getMethod("addListener",String.class);
                method.invoke(null,beanName);
            }
        }
    }
}