Example usage for org.springframework.context.annotation ClassPathScanningCandidateComponentProvider addIncludeFilter

List of usage examples for org.springframework.context.annotation ClassPathScanningCandidateComponentProvider addIncludeFilter

Introduction

In this page you can find the example usage for org.springframework.context.annotation ClassPathScanningCandidateComponentProvider addIncludeFilter.

Prototype

public void addIncludeFilter(TypeFilter includeFilter) 

Source Link

Document

Add an include type filter to the end of the inclusion list.

Usage

From source file:com.sourceallies.beanoh.BeanohTestCase.java

/**
 * Reconcile the beans marked with org.springframework.stereotype.Component
 * in the classpath with the beans loaded in the Spring context.
 * /*ww  w  .  j  a  v  a  2 s.  co  m*/
 * Ignore classes with the method ignoreClassNames and ignore packages with
 * the method ignorePackages.
 * 
 * @param basePackage
 *            the base package in which classes annotated with
 *            org.springframework.stereotype.Component will be located
 */
public void assertComponentsInContext(String basePackage) {
    loadContext();
    final Set<String> scannedComponents = new HashSet<String>();
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Component.class));

    collectComponentsInClasspath(basePackage, scannedComponents, scanner);
    removeComponentsInPackages(scannedComponents);
    removeIgnoredClasses(scannedComponents);

    iterateBeanDefinitions(new BeanDefinitionAction() {
        @Override
        public void execute(String name, BeanDefinition definition) {
            scannedComponents.remove(definition.getBeanClassName());
        }
    });

    if (scannedComponents.size() > 0) {
        throw new MissingComponentException(
                "There are beans marked with '@Component' in the classpath that are not configured by Spring. "
                        + "Either configure these beans or ignore them with the 'ignoreClassNames' or 'ignorePackages' method.\n"
                        + "Components not in Spring:" + missingList(scannedComponents));
    }
}

From source file:com.joyveb.dbpimpl.cass.prepare.config.java.AbstractCassandraConfiguration.java

/**
 * Scans the mapping base package for classes annotated with {@link Table}.
 * //  w w  w.  ja va2 s  .  c  o  m
 * @see #getMappingBasePackage()
 * @return
 * @throws ClassNotFoundException
 */
protected Set<Class<?>> getInitialEntitySet() {

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

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

        for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {
            initialEntitySet.add(loadClass(candidate.getBeanClassName()));
        }
    }

    return initialEntitySet;
}

From source file:com.googlecode.icegem.cacheutils.common.PeerCacheService.java

/**
 * @param classLoader/*from ww  w.  ja  v  a  2 s .c  o  m*/
 * @throws Exception
 */
private void registerClasses(ClassLoader classLoader) throws Exception {
    List<Class<?>> classesFromPackages = new ArrayList<Class<?>>();

    for (String pack : scanPackages) {
        log.info("Scan package " + pack + " for classes marked by @AutoSerializable");

        ClassPathScanningCandidateComponentProvider ppp = new ClassPathScanningCandidateComponentProvider(
                false);

        ppp.addIncludeFilter(new AnnotationTypeFilter(AutoSerializable.class));

        Set<BeanDefinition> candidateComponents = ppp.findCandidateComponents(pack);

        for (BeanDefinition beanDefinition : candidateComponents) {
            String className = beanDefinition.getBeanClassName();

            final Class<?> clazz = Class.forName(className);

            classesFromPackages.add(clazz);
        }
    }

    try {
        HierarchyRegistry.registerAll(classLoader, classesFromPackages);
    } catch (InvalidClassException e) {
        final String msg = "Some class from list " + classesFromPackages + " is nor serializable. Cause: "
                + e.getMessage();

        log.error(msg);

        throw new RuntimeException(msg, e);
    } catch (CannotCompileException e) {
        final String msg = "Can't compile DataSerializer classes for some classes from list "
                + classesFromPackages + ". Cause: " + e.getMessage();

        log.error(msg);

        throw new RuntimeException(msg, e);
    }
}

From source file:com.thoughtworks.go.server.service.MagicalMaterialAndMaterialConfigConversionTest.java

@Test
public void failIfNewTypeOfMaterialIsNotAddedInTheAboveTest() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);/*from  w ww.j  a va2 s.c om*/
    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);
}

From source file:com.github.bjoern2.yolotyrion.spring.xml.RepositorySingleBeanDefinitionParser.java

protected ClassPathScanningCandidateComponentProvider generateScanner(Class<?> interfaze) {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false) {/*from   w  w  w .  ja  v  a2s.com*/
        @Override
        protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
            return true;
        }
    };
    provider.addIncludeFilter(new AssignableTypeFilter(interfaze));
    return provider;
}

From source file:org.openmrs.module.webservices.rest.web.DelegatingCrudResourceTest.java

/**
 * This test looks at all subclasses of DelegatingCrudResource, and test all {@link RepHandler}
 * methods to make sure they are all capable of running without exceptions. It also checks that
 */// w  w  w.ja va  2  s .co m
@SuppressWarnings("rawtypes")
@Test
@Ignore
public void testAllReprsentationDescriptions() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            true);
    //only match subclasses of BaseDelegatingResource
    provider.addIncludeFilter(new AssignableTypeFilter(BaseDelegatingResource.class));

    // scan in org.openmrs.module.webservices.rest.web.resource package 
    Set<BeanDefinition> components = provider
            .findCandidateComponents("org.openmrs.module.webservices.rest.web.resource");
    if (CollectionUtils.isEmpty(components))
        Assert.fail("Faile to load any resource classes");

    for (BeanDefinition component : components) {
        Class resourceClass = Class.forName(component.getBeanClassName());
        for (Method method : ReflectionUtils.getAllDeclaredMethods(resourceClass)) {
            ParameterizedType parameterizedType = (ParameterizedType) resourceClass.getGenericSuperclass();
            Class openmrsClass = (Class) parameterizedType.getActualTypeArguments()[0];
            //User Resource is special in that the Actual parameterized Type isn't a standard domain object, so we also
            //need to look up fields and methods from the org.openmrs.User class 
            boolean isUserResource = resourceClass.equals(UserResource1_8.class);
            List<Object> refDescriptions = new ArrayList<Object>();

            if (method.getName().equals("getRepresentationDescription")
                    && method.getDeclaringClass().equals(resourceClass)) {
                //get all the rep definitions for all representations
                refDescriptions
                        .add(method.invoke(resourceClass.newInstance(), new Object[] { Representation.REF }));
                refDescriptions.add(
                        method.invoke(resourceClass.newInstance(), new Object[] { Representation.DEFAULT }));
                refDescriptions
                        .add(method.invoke(resourceClass.newInstance(), new Object[] { Representation.FULL }));
            }

            for (Object value : refDescriptions) {
                if (value != null) {
                    DelegatingResourceDescription des = (DelegatingResourceDescription) value;
                    for (String key : des.getProperties().keySet()) {
                        if (!key.equals("uri") && !key.equals("display") && !key.equals("auditInfo")) {
                            boolean hasFieldOrPropertySetter = (ReflectionUtils.findField(openmrsClass,
                                    key) != null);
                            if (!hasFieldOrPropertySetter) {
                                hasFieldOrPropertySetter = hasSetterMethod(key, resourceClass);
                                if (!hasFieldOrPropertySetter && isUserResource)
                                    hasFieldOrPropertySetter = (ReflectionUtils.findField(User.class,
                                            key) != null);
                            }
                            if (!hasFieldOrPropertySetter)
                                hasFieldOrPropertySetter = hasSetterMethod(key, resourceClass);

                            //TODO replace this hacky way that we are using to check if there is a get method for a 
                            //collection that has no actual getter e.g activeIdentifers and activeAttributes for Patient
                            if (!hasFieldOrPropertySetter) {
                                hasFieldOrPropertySetter = (ReflectionUtils.findMethod(openmrsClass,
                                        "get" + StringUtils.capitalize(key)) != null);
                                if (!hasFieldOrPropertySetter && isUserResource)
                                    hasFieldOrPropertySetter = (ReflectionUtils.findMethod(User.class,
                                            "get" + StringUtils.capitalize(key)) != null);
                            }

                            if (!hasFieldOrPropertySetter)
                                hasFieldOrPropertySetter = isallowedMissingProperty(resourceClass, key);

                            Assert.assertTrue(
                                    "No property found for '" + key + "' for " + openmrsClass
                                            + " nor setter method on resource " + resourceClass,
                                    hasFieldOrPropertySetter);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.agilemicroservices.autoconfigure.orm.RepositoryConfigurationDelegate.java

/**
 * Scans {@code repository.support} packages for implementations of {@link RepositoryFactorySupport}. Finding more
 * than a single type is considered a multi-store configuration scenario which will trigger stricter repository
 * scanning.//from   www .  ja v  a 2 s. c  o  m
 *
 * @return
 */
private boolean multipleStoresDetected() {

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);
    scanner.setEnvironment(environment);
    scanner.setResourceLoader(resourceLoader);
    scanner.addIncludeFilter(new LenientAssignableTypeFilter(RepositoryFactorySupport.class));

    if (scanner.findCandidateComponents(MODULE_DETECTION_PACKAGE).size() > 1) {

        LOGGER.debug(MULTIPLE_MODULES);
        return true;
    }

    return false;
}

From source file:hwolf.spring.boot.servlet.ClassPathScanner.java

@SuppressWarnings("unchecked")
private ClassPathScanningCandidateComponentProvider buildClassPathScanner() {

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);//from  w w w  .  j  a  v a 2 s .c om
    for (Class<?> type : types) {
        if (type.isAnnotation()) {
            if (debug) {
                LOGGER.debug("Search for classes annotated with " + type);
            }
            scanner.addIncludeFilter(new AnnotationTypeFilter((Class<Annotation>) type));
        } else {
            if (debug) {
                LOGGER.debug("Search for classes assignable to " + type);
            }
            scanner.addIncludeFilter(new AssignableTypeFilter(type));
        }
    }
    return scanner;
}

From source file:com.searchbox.framework.web.ApplicationConversionService.java

@Override
public void afterPropertiesSet() throws Exception {

    LOGGER.info("Scanning for SearchComponents");
    Map<Class<?>, String> conditionUrl = new HashMap<Class<?>, String>();
    ClassPathScanningCandidateComponentProvider scanner;

    // Getting all the SearchElements
    scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(SearchCondition.class));
    for (BeanDefinition bean : scanner.findCandidateComponents("com.searchbox")) {
        try {//  w ww .  j  a v  a 2s.  c o m
            Class<?> clazz = Class.forName(bean.getBeanClassName());
            String urlParam = clazz.getAnnotation(SearchCondition.class).urlParam();
            conditionUrl.put(clazz, urlParam);
        } catch (Exception e) {
            LOGGER.error("Could not introspect SearchElement: " + bean, e);
        }
    }

    // Getting all converters for SearchConditions
    scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(SearchConverter.class));
    for (BeanDefinition bean : scanner.findCandidateComponents("com.searchbox")) {
        try {
            Class<?> clazz = Class.forName(bean.getBeanClassName());
            for (Type i : clazz.getGenericInterfaces()) {
                ParameterizedType pi = (ParameterizedType) i;
                for (Type piarg : pi.getActualTypeArguments()) {
                    if (AbstractSearchCondition.class.isAssignableFrom(((Class<?>) piarg))) {
                        Class<?> conditionClass = ((Class<?>) piarg);
                        searchConditions.put(conditionUrl.get(conditionClass), ((Class<?>) piarg));
                        this.addConverter((Converter<?, ?>) clazz.newInstance());
                        LOGGER.info("Registered Converter " + clazz.getSimpleName() + " for "
                                + ((Class<?>) piarg).getSimpleName() + " with prefix: "
                                + conditionUrl.get(conditionClass));
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("Could not create Converter for: " + bean.getBeanClassName(), e);
        }
    }

    this.addConverter(new Converter<String, SearchboxEntity>() {
        @Override
        public SearchboxEntity convert(String slug) {
            return searchboxRepository.findBySlug(slug);
        }
    });

    this.addConverter(new Converter<SearchboxEntity, String>() {
        @Override
        public String convert(SearchboxEntity searchbox) {
            return searchbox.getSlug();
        }
    });

    this.addConverter(new Converter<Long, SearchboxEntity>() {
        @Override
        public SearchboxEntity convert(java.lang.Long id) {
            return searchboxRepository.findOne(id);
        }
    });

    this.addConverter(new Converter<SearchboxEntity, Long>() {
        @Override
        public Long convert(SearchboxEntity searchbox) {
            return searchbox.getId();
        }
    });

    this.addConverter(new Converter<String, PresetEntity>() {
        @Override
        public PresetEntity convert(String slug) {
            return presetRepository.findPresetDefinitionBySlug(slug);
        }
    });

    this.addConverter(new Converter<Long, PresetEntity>() {
        @Override
        public PresetEntity convert(java.lang.Long id) {
            return presetRepository.findOne(id);
        }
    });

    this.addConverter(new Converter<PresetEntity, String>() {
        @Override
        public String convert(PresetEntity presetDefinition) {
            return new StringBuilder().append(presetDefinition.getSlug()).toString();
        }
    });

    this.addConverter(new Converter<Class<?>, String>() {
        @Override
        public String convert(Class<?> source) {
            return source.getName();
        }
    });

    this.addConverter(new Converter<String, Class<?>>() {

        @Override
        public Class<?> convert(String source) {
            try {
                // TODO Such a bad hack...
                if (source.contains("class")) {
                    source = source.replace("class", "").trim();
                }
                return context.getClassLoader().loadClass(source);
                // Class.forName(source);
            } catch (ClassNotFoundException e) {
                LOGGER.error("Could not convert \"" + source + "\" to class.", e);
            }
            return null;
        }

    });
}

From source file:com.logsniffer.config.BeanConfigFactoryManager.java

@SuppressWarnings("unchecked")
@PostConstruct/*w w w .j a v  a2 s.  c  om*/
private void initJsonMapper() {
    final SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyDeserializer(final DeserializationConfig config,
                final BeanDescription beanDesc, final JsonDeserializer<?> deserializer) {
            if (ConfiguredBean.class.isAssignableFrom(beanDesc.getBeanClass())) {
                return new ConfiguredBeanDeserializer(deserializer);
            }
            return deserializer;
        }
    });
    jsonMapper.registerModule(module);
    if (postConstructors != null) {
        for (final BeanPostConstructor<?> bpc : postConstructors) {
            mappedPostConstrucors.put(bpc.getClass(), bpc);
        }
    }

    // Register sub beans
    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);
    final AssignableTypeFilter filter4configBenas = new AssignableTypeFilter(ConfiguredBean.class);
    scanner.addIncludeFilter(filter4configBenas);

    for (final BeanDefinition bd : scanner.findCandidateComponents("com.logsniffer")) {
        try {
            final Class<? extends ConfiguredBean> clazz = (Class<? extends ConfiguredBean>) Class
                    .forName(bd.getBeanClassName());
            final JsonTypeName jsonNameAnnotation = clazz.getAnnotation(JsonTypeName.class);
            final List<String> names = new ArrayList<String>();
            configBeanNames.put(clazz, names);
            if (jsonNameAnnotation != null) {
                names.add(jsonNameAnnotation.value());
                if (jsonNameAnnotation.deprecated() != null) {
                    for (final String dep : jsonNameAnnotation.deprecated()) {
                        names.add(dep);
                    }
                }
            }
            names.add(clazz.getSimpleName());
            logger.debug("Registered JSON type {} for following names: {}", clazz, names);
        } catch (final ClassNotFoundException e) {
            logger.warn("Failed to register JSON type name for " + bd.getBeanClassName(), e);
        }
    }
}