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

The following are top voted examples for showing how to use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: muon-java   File: MuonRepositoryRegistrar.java   View source code 7 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    Set<String> basePackages = getBasePackages(importingClassMetadata);
    ClassPathScanningCandidateComponentProvider scanner = getScanner();
    scanner.addIncludeFilter(new AnnotationTypeFilter(MuonRepository.class));
    for (String basePackage : basePackages) {
        Set<BeanDefinition> candidateComponents = scanner
                .findCandidateComponents(basePackage);
        for (BeanDefinition candidateComponent : candidateComponents) {
            if (candidateComponent instanceof AnnotatedBeanDefinition) {

                AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
                AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
                Assert.isTrue(annotationMetadata.isInterface(),
                        "@FeignClient can only be specified on an interface");

                BeanDefinitionHolder holder = createBeanDefinition(annotationMetadata);
                BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
            }
        }
    }

}
 
Example 2
Project: tipi-engine   File: AnnotationActivityRegistrar.java   View source code 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {

    // on recherche toutes les classes concrètes du package à la recherche de celles qui sont annotées 'TipiTopProcess'
    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false) {
        @Override
        protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
            return beanDefinition.getMetadata().isConcrete();
        }
    };
    scanner.addIncludeFilter(new AnnotationTypeFilter(TipiTopProcess.class));

    if (excludeFilters != null) {
        for (TypeFilter filter : excludeFilters) {
            scanner.addExcludeFilter(filter);
        }
    }

    Set<BeanDefinition> beans = scanner.findCandidateComponents(aPackage);
    LOGGER.info("Registering " + beans.size() + " Tipi activities");
    for (BeanDefinition bean : beans) {
        Class<?> clazz = Class.forName(bean.getBeanClassName());
        registerClass(clazz);
    }
}
 
Example 3
Project: tipi-engine   File: HibernateMetaDataHelper.java   View source code 6 votes vote down vote up
/**
 * Retourne les classes d'une package
 *
 * @param packageName
 * @return
 * @throws Exception
 */
public static List<Class> getClasses(String packageName) {
    final List<Class> list = new ArrayList<>();

    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(Object.class));
    final Set<BeanDefinition> bds = scanner.findCandidateComponents(packageName);
    try {
        for (BeanDefinition bd : bds) {
            final Class<?> tc = Class.forName(bd.getBeanClassName());
            if (tc.getAnnotation(Entity.class) != null) {
                list.add(tc);
            }
        }
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    return list;
}
 
Example 4
Project: alfresco-repository   File: AJExtensionsCompileTest.java   View source code 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 5
Project: spring-data-documentdb   File: DocumentDbConfigurationSupport.java   View source code 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<Class<?>>();

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

        for (final BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {

            initialEntitySet
                    .add(ClassUtils.forName(candidate.getBeanClassName(),
                            DocumentDbConfigurationSupport.class.getClassLoader()));
        }
    }

    return initialEntitySet;
}
 
Example 6
Project: taboola-cronyx   File: ConfigUtil.java   View source code 6 votes vote down vote up
public static <T> List<Pair<Class, T>> cronyxQuartzConverterPairs(Class<T> tClass) {

        List<Pair<Class, T>> results = new ArrayList<>();

        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AssignableTypeFilter(tClass));

        Set<BeanDefinition> components = provider.findCandidateComponents(PACKAGE);
        for (BeanDefinition component : components) {
            try {
                Class cls = Class.forName(component.getBeanClassName());
                Class<?> typeArgument = GenericTypeResolver.resolveTypeArgument(cls, tClass);
                results.add(new ImmutablePair<>(typeArgument, (T) cls.newInstance()));

            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                throw new CronyxException("Could not instantiate cronyxToQuartzConverters", e);
            }
        }
        return results;
    }
 
Example 7
Project: springboot-analysis   File: ConsumerRegistrar.java   View source code 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AnnotationTypeFilter(Consumer.class));
    provider.addIncludeFilter(new AssignableTypeFilter(IConsumer.class));
    Set<BeanDefinition> beanDefinitionSet = provider.findCandidateComponents("spring.study.componentprovider.bean");

    for(BeanDefinition beanDefinition : beanDefinitionSet) {
        String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry);
        if(!registry.containsBeanDefinition(beanName)) {
            registry.registerBeanDefinition(beanName, beanDefinition);
            registry.registerBeanDefinition("11", beanDefinition);
        }
    }

}
 
Example 8
Project: cqrs-es-kafka   File: CommandHandlerUtils.java   View source code 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 9
Project: lodsve-framework   File: MongoBeanDefinitionRegistrar.java   View source code 6 votes vote down vote up
private static Set<String> getInititalEntityClasses(String[] domainPackages) {
    if (ArrayUtils.isEmpty(domainPackages)) {
        return null;
    }

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

    Set<String> classes = new ManagedSet<>();
    for (String domainPackage : domainPackages) {
        if (StringUtils.isBlank(domainPackage)) {
            continue;
        }
        for (BeanDefinition candidate : componentProvider.findCandidateComponents(domainPackage)) {
            classes.add(candidate.getBeanClassName());
        }
    }

    return classes;
}
 
Example 10
Project: schemagen-graphql   File: GraphQLSpringSchemaBuilder.java   View source code 6 votes vote down vote up
public static List<IGraphQLTypeMapper> getDefaultTypeMappers() {
    ImmutableList.Builder<IGraphQLTypeMapper> builder = ImmutableList.builder();

    ClassPathScanningCandidateComponentProvider scanner =
            new ClassPathScanningCandidateComponentProvider(true);

    scanner.addIncludeFilter(new AnnotationTypeFilter(GraphQLTypeMapper.class));

    for (BeanDefinition bd : scanner.findCandidateComponents(IGraphQLTypeMapper.class.getPackage().getName())) {
        try {
            Class<?> cls = ClassUtils.resolveClassName(bd.getBeanClassName(),
                    ClassUtils.getDefaultClassLoader());

            builder.add((IGraphQLTypeMapper) cls.newInstance());
        } catch (Exception e) {
            LOGGER.error("Unexpected exception.", e);
        }
    }
    return builder.build();
}
 
Example 11
Project: feign-error-decoder   File: CachedSpringClassHierarchySupplier.java   View source code 6 votes vote down vote up
public CachedSpringClassHierarchySupplier(Class<?> baseClass, String basePackage) {
  if (!baseClassSubClassesCache.containsKey(baseClass)) {
    ClassPathScanningCandidateComponentProvider provider =
        new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AssignableTypeFilter(baseClass));

    Set<Class<?>> subClasses = new HashSet<>();
    for (BeanDefinition beanDefinition : provider.findCandidateComponents(basePackage)) {
      try {
        subClasses.add(Class.forName(beanDefinition.getBeanClassName()));
      } catch (ClassNotFoundException e) {
        throw new IllegalStateException(
            String.format("Could not load child class '%s'.", beanDefinition.getBeanClassName()),
            e);
      }
    }
    baseClassSubClassesCache.put(baseClass, subClasses);
  }
  subClasses = baseClassSubClassesCache.get(baseClass);
}
 
Example 12
Project: feign-error-decoder   File: SpringClassHierarchySupplier.java   View source code 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 13
Project: spring-data-jest   File: ElasticsearchJestAutoConfiguration.java   View source code 6 votes vote down vote up
/**
 * List all official ES plugins available on ClassPath.
 * @return List of plugins class
 */
@SuppressWarnings("unchecked")
private static Collection<Class<? extends Plugin>> scanPlugins() {
	ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(false);
	componentProvider.addIncludeFilter(new AssignableTypeFilter(Plugin.class));

	return componentProvider.findCandidateComponents("org.elasticsearch.plugin").stream()
			.map(BeanDefinition::getBeanClassName)
			.map(name -> {
				try {
					return (Class<? extends Plugin>) Class.forName(name);
				} catch (ClassNotFoundException e) {
					logger.warn("Cannot load class on plugin detection", e);
					return null;
				}
			})
			.collect(Collectors.toSet());
}
 
Example 14
Project: graviteeio-access-management   File: AbstractRepositoryConfiguration.java   View source code 6 votes vote down vote up
protected Set<Class<?>> getInitialEntitySet() throws ClassNotFoundException {

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

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

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

        return initialEntitySet;
    }
 
Example 15
Project: acme-solution   File: CommandHandlerUtils.java   View source code 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().getName(), currentHandler);
    }

    return registry;
}
 
Example 16
Project: acme-solution   File: EventHandlerUtils.java   View source code 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 17
Project: distGatling   File: JerseyConfig.java   View source code 6 votes vote down vote up
/**
* Scans for {@link javax.ws.rs.Path} annotated classes in the given packages and registers them with Jersey.
* @param controllerPackages Jersery controller base package names
*/
  protected void registerControllers(String[] controllerPackages) {
      ClassPathScanningCandidateComponentProvider scanner =
      		new ClassPathScanningCandidateComponentProvider(false);
  		scanner.addIncludeFilter(new AnnotationTypeFilter(javax.ws.rs.Path.class));

  	for(String controllerPackage : controllerPackages) {
  		logger.info("Scanning for Jersey controllers in '{}' package.", controllerPackage);
  		
       for (BeanDefinition bd : scanner.findCandidateComponents(controllerPackage)) {
       	logger.info("Registering Jersey endpoint class:  {}", bd.getBeanClassName());
       	Class<?> controllerClazz = getJerseyControllerClass(bd.getBeanClassName());
       	if(controllerClazz != null)
       		register(controllerClazz);
       }
  	}
  }
 
Example 18
Project: distGatling   File: JerseyConfig.java   View source code 6 votes vote down vote up
/**
* Scans for {@link javax.ws.rs.Path} annotated classes in the given packages and registers them with Jersey.
* @param controllerPackages Jersery controller base package names
*/
  protected void registerControllers(String[] controllerPackages) {
      ClassPathScanningCandidateComponentProvider scanner =
      		new ClassPathScanningCandidateComponentProvider(false);
  		scanner.addIncludeFilter(new AnnotationTypeFilter(javax.ws.rs.Path.class));

  	for(String controllerPackage : controllerPackages) {
  		logger.info("Scanning for Jersey controllers in '{}' package.", controllerPackage);
  		
       for (BeanDefinition bd : scanner.findCandidateComponents(controllerPackage)) {
       	logger.info("Registering Jersey endpoint class:  {}", bd.getBeanClassName());
       	Class<?> controllerClazz = getJerseyControllerClass(bd.getBeanClassName());
       	if(controllerClazz != null)
       		register(controllerClazz);
       }
  	}
  }
 
Example 19
Project: distGatling   File: JerseyConfig.java   View source code 6 votes vote down vote up
/**
* Scans for {@link javax.ws.rs.Path} annotated classes in the given packages and registers them with Jersey.
* @param controllerPackages Jersery controller base package names
*/
  protected void registerControllers(String[] controllerPackages) {
      ClassPathScanningCandidateComponentProvider scanner =
      		new ClassPathScanningCandidateComponentProvider(false);
  		scanner.addIncludeFilter(new AnnotationTypeFilter(javax.ws.rs.Path.class));

  	for(String controllerPackage : controllerPackages) {
  		logger.info("Scanning for Jersey controllers in '{}' package.", controllerPackage);
  		
       for (BeanDefinition bd : scanner.findCandidateComponents(controllerPackage)) {
       	logger.info("Registering Jersey endpoint class:  {}", bd.getBeanClassName());
       	Class<?> controllerClazz = getJerseyControllerClass(bd.getBeanClassName());
       	if(controllerClazz != null)
       		register(controllerClazz);
       }
  	}
  }
 
Example 20
Project: line-bot-sdk-java   File: ReplyEventTest.java   View source code 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 21
Project: restful-api-cxf-spring-java   File: ConfigUtils.java   View source code 6 votes vote down vote up
public List<Class> findClass( Class annotation ) {
	ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
	scanner.addIncludeFilter(new AnnotationTypeFilter(annotation));
	
	List<Class> classList = new ArrayList<Class>();
	
	for (BeanDefinition bd : scanner.findCandidateComponents(BASE_PACKAGE)) {

		try {
			classList.add(Class.forName(bd.getBeanClassName()));
		} catch (ClassNotFoundException e) {

			LOG.error("problème de déploiement du service associé au bean : " + bd.getBeanClassName());
		}
	}
	
	return classList;
}
 
Example 22
Project: restful-api-cxf-spring-java   File: ConfigTestUtils.java   View source code 6 votes vote down vote up
public List<Class> findClasses( Class annotation ) {
	ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
	scanner.addIncludeFilter(new AnnotationTypeFilter(annotation));
	
	List<Class> classList = new ArrayList<Class>();
	
	for (BeanDefinition bd : scanner.findCandidateComponents(BASE_PACKAGE)) {

		try {
			classList.add(Class.forName(bd.getBeanClassName()));
		} catch (ClassNotFoundException e) {

			LOG.error("problème de déploiement du service associé au bean : " + bd.getBeanClassName());
		}
	}
	
	return classList;
}
 
Example 23
Project: spring-graphql-common   File: GraphQLSchemaDiscoverer.java   View source code 6 votes vote down vote up
public static Set<Class<?>> findSchemaClasses(final String basePackage) throws ClassNotFoundException {
    
    Set<Class<?>> initialEntitySet = new HashSet<Class<?>>();

    if (StringUtils.hasText(basePackage)) {
        ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(
                false);
        componentProvider.addIncludeFilter(new AnnotationTypeFilter(GRAPH_QL_SCHEMA_ANNOTATION));

        for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {
            initialEntitySet.add(ClassUtils.forName(candidate.getBeanClassName(),
                    GraphQLSchemaDiscoverer.class.getClassLoader()));
        }
    }
    return initialEntitySet;
}
 
Example 24
Project: warpdb   File: ClassUtils.java   View source code 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 25
Project: spring-boot-concourse   File: MongoDataAutoConfiguration.java   View source code 6 votes vote down vote up
private Set<Class<?>> getInitialEntitySet(BeanFactory beanFactory)
		throws ClassNotFoundException {
	Set<Class<?>> entitySet = new HashSet<Class<?>>();
	ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
			false);
	scanner.setEnvironment(this.environment);
	scanner.setResourceLoader(this.resourceLoader);
	scanner.addIncludeFilter(new AnnotationTypeFilter(Document.class));
	scanner.addIncludeFilter(new AnnotationTypeFilter(Persistent.class));
	for (String basePackage : getMappingBasePackages(beanFactory)) {
		if (StringUtils.hasText(basePackage)) {
			for (BeanDefinition candidate : scanner
					.findCandidateComponents(basePackage)) {
				entitySet.add(ClassUtils.forName(candidate.getBeanClassName(),
						this.classLoader));
			}
		}
	}
	return entitySet;
}
 
Example 26
Project: putput   File: JerseyConfig.java   View source code 6 votes vote down vote up
@PostConstruct
public void registerResources() {
  ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
  provider.addIncludeFilter(new AssignableTypeFilter(BaseResource.class));

  for (BeanDefinition component : provider.findCandidateComponents("org/putput")) {
    try {
      Class<?> resourceClass = Class.forName(component.getBeanClassName());
      org.slf4j.LoggerFactory.getLogger(JerseyConfig.class).info("registering " + resourceClass.getName());
      register(resourceClass);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }

}
 
Example 27
Project: kc-rice   File: QueryByCriteriaJaxbTest.java   View source code 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 28
Project: owsi-core-parent   File: ReflectionUtils.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> Set<Class<? extends T>> findClasses(String rootPackage, Class<T> clazz, TypeFilter filter) {
	ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
	scanner.addIncludeFilter(filter);
	
	Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(rootPackage);
	Set<Class<? extends T>> classes = new LinkedHashSet<Class<? extends T>>();
	
	for (BeanDefinition beanDefinition : beanDefinitions) {
		try {
			classes.add((Class<? extends T>) Class.forName(beanDefinition.getBeanClassName()));
		} catch (ClassNotFoundException e) {
			LOGGER.warn("Class not found: " + beanDefinition.getBeanClassName());
		}
	}
	
	return classes;
}
 
Example 29
Project: moserp   File: RestConfiguration.java   View source code 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 30
Project: contestparser   File: MongoDataAutoConfiguration.java   View source code 6 votes vote down vote up
private Set<Class<?>> getInitialEntitySet(BeanFactory beanFactory)
		throws ClassNotFoundException {
	Set<Class<?>> entitySet = new HashSet<Class<?>>();
	ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
			false);
	scanner.setEnvironment(this.environment);
	scanner.setResourceLoader(this.resourceLoader);
	scanner.addIncludeFilter(new AnnotationTypeFilter(Document.class));
	scanner.addIncludeFilter(new AnnotationTypeFilter(Persistent.class));
	for (String basePackage : getMappingBasePackages(beanFactory)) {
		if (StringUtils.hasText(basePackage)) {
			for (BeanDefinition candidate : scanner
					.findCandidateComponents(basePackage)) {
				entitySet.add(ClassUtils.forName(candidate.getBeanClassName(),
						this.classLoader));
			}
		}
	}
	return entitySet;
}
 
Example 31
Project: pungwecms   File: ModuleManagementService.java   View source code 6 votes vote down vote up
/**
 * Scans the classpath for classes with the <b>@Module</b> annotation
 *
 * @see Module @Module
 */
public void scan() {
	List<String> defaultEnabledModules = applicationContext.getBean("defaultEnabledModules", List.class);
	// Important to remove all missing modules first, so scanning the classpath is quicker
	removeMissingModules();
	// If we have enabled modules then we should not attempt to enable those in the config file...
	final boolean enabledModules = !getModuleConfigService().listEnabledModules().isEmpty();
	ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
	scanner.addIncludeFilter(new AnnotationTypeFilter(Module.class));
	Set<BeanDefinition> modules = scanner.findCandidateComponents("*");
	modules.forEach(b -> {
		try {
			Class c = Class.forName(b.getBeanClassName());
			getModuleConfigService().registerModule(c, c.getProtectionDomain().getCodeSource().getLocation());
		} catch (ClassNotFoundException e) {
			LOG.error("Could not load a module found on the class path, due to it's class not being found. This should never happen and usually means something is wrong with the environment", e);
		}
	});

	if (!enabledModules && defaultEnabledModules != null && !defaultEnabledModules.isEmpty()) {
		enable(defaultEnabledModules);
	}
}
 
Example 32
Project: onetwo   File: AnnotationMetadataHelper.java   View source code 6 votes vote down vote up
public Stream<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());
}
 
Example 33
Project: brooklyn-tosca   File: TypeScanner.java   View source code 6 votes vote down vote up
public static Set<Class<?>> scanTypes(String basePackage, Class<?> targetType) throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    if (resourceLoader!=null) {
        scanner.setResourceLoader(resourceLoader);
    }

    AssignableTypeFilter filter = new AssignableTypeFilter(targetType);
    scanner.addIncludeFilter(filter);
    Set<BeanDefinition> beanSet = scanner.findCandidateComponents(basePackage);

    Set<Class<?>> classSet = new HashSet<Class<?>>();
    for (BeanDefinition beanDef : beanSet) {
        // log.debug("found candidate bean = {}", beanDef.getBeanClassName());

        Class<?> clazz;

        clazz = Class.forName(beanDef.getBeanClassName(), true, Thread.currentThread().getContextClassLoader());
        classSet.add(clazz);
    }

    return classSet;
}
 
Example 34
Project: zstack   File: InventoryIndexManagerImpl.java   View source code 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 35
Project: zstack   File: ConfigurationManagerImpl.java   View source code 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 36
Project: zstack   File: ConfigurationManagerImpl.java   View source code 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 37
Project: zstack   File: Deployer.java   View source code 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 38
Project: zstack   File: InventoryFacadeImpl.java   View source code 6 votes vote down vote up
@Override
public boolean start() {
    try {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
        scanner.addIncludeFilter(new AnnotationTypeFilter(Inventory.class));
        scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
        scanner.addExcludeFilter(new AnnotationTypeFilter(org.springframework.stereotype.Component.class));
        for (String pkg : getBasePkgNames()) {
            for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
                Class<?> inventoryClass = Class.forName(bd.getBeanClassName());
                Inventory invat = inventoryClass.getAnnotation(Inventory.class);
                Info info = new Info();
                info.inventory = invat;
                info.inventoryClass = inventoryClass;
                inventoryMapping.put(invat.mappingVOClass(), info);
            }
        }
    } catch (Exception e) {
        throw new CloudRuntimeException(e);
    }
    return true;
}
 
Example 39
Project: zstack   File: RESTApiFacadeImpl.java   View source code 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 40
Project: iVIS   File: DocumentationUtil.java   View source code 6 votes vote down vote up
public static Set<Class<? extends Object>> getAllClassesFromPackage(String packageName) {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));
    Set<BeanDefinition> classes = provider.findCandidateComponents(packageName);
    Set<Class<?>> allClasses = classes.stream()
            .map(bean -> {
                try {
                    return Class.forName(bean.getBeanClassName());
                } catch (ClassNotFoundException e) {
                    LoggerFactory.getLogger(DocumentationUtil.class).error(e.getMessage(), e.getCause());
                }
                return null;
            })
            .collect(Collectors.toSet());
    return allClasses;
}