Example usage for org.springframework.core.type.filter AnnotationTypeFilter AnnotationTypeFilter

List of usage examples for org.springframework.core.type.filter AnnotationTypeFilter AnnotationTypeFilter

Introduction

In this page you can find the example usage for org.springframework.core.type.filter AnnotationTypeFilter AnnotationTypeFilter.

Prototype

public AnnotationTypeFilter(Class<? extends Annotation> annotationType) 

Source Link

Document

Create a new AnnotationTypeFilter for the given annotation type.

Usage

From source file:org.devefx.httpmapper.spring.mapper.ClassPathMapperScanner.java

/**
 * Configures parent scanner to search for the right interfaces. It can search
 * for all interfaces or just for those that extends a markerInterface or/and
 * those annotated with the annotationClass
 *//*from w ww . java 2 s . c o m*/
public void registerFilters() {
    boolean acceptAllInterfaces = true;

    // if specified, use the given annotation and / or marker interface
    if (this.annotationClass != null) {
        addIncludeFilter(new AnnotationTypeFilter(this.annotationClass));
        acceptAllInterfaces = false;
    }

    // override AssignableTypeFilter to ignore matches on the actual marker interface
    if (this.markerInterface != null) {
        addIncludeFilter(new AssignableTypeFilter(this.markerInterface) {
            @Override
            protected boolean matchClassName(String className) {
                return false;
            }
        });
        acceptAllInterfaces = false;
    }

    if (acceptAllInterfaces) {
        // default include filter that accepts all classes
        addIncludeFilter(new TypeFilter() {
            @Override
            public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                    throws IOException {
                return true;
            }
        });
    }

    // exclude package-info.java
    addExcludeFilter(new TypeFilter() {
        @Override
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            String className = metadataReader.getClassMetadata().getClassName();
            return className.endsWith("package-info");
        }
    });
}

From source file:com.walmart.gatling.JerseyConfig.java

/**
 * 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
 *///from w  ww  .ja va2  s .c o m
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);
        }
    }
}

From source file:com.gzj.tulip.jade.context.spring.JadeComponentProvider.java

/**
 * 
 */
public JadeComponentProvider() {
    includeFilters.add(new AnnotationTypeFilter(DAO.class));
}

From source file:com.dm.estore.config.WebAppInitializer.java

private void registerListener(ServletContext servletContext) {
    AnnotationConfigWebApplicationContext rootContext = createContext(ApplicationModule.class);

    // find all classes marked as @Configuration in classpath
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);//from   w w  w .  ja va  2 s  .c  o m
    scanner.addIncludeFilter(new AnnotationTypeFilter(Configuration.class));
    //TypeFilter tf = new AssignableTypeFilter(CLASS_YOU_WANT.class);
    //s.addIncludeFilter(tf);
    //s.scan("package.you.want1", "package.you.want2");       
    //String[] beans = bdr.getBeanDefinitionNames();
    for (BeanDefinition bd : scanner.findCandidateComponents("com.dm.estore")) {
        final String beanClassName = bd.getBeanClassName();
        final String simpleName = ClassUtils.getShortCanonicalName(beanClassName);
        if (!excludeFromAutoSearch.contains(beanClassName)
                && !simpleName.toLowerCase().startsWith(TEST_RESOURCES_PREFIX)) {
            LOG.warn("Load configuration from: " + bd.getBeanClassName());
            try {
                Class<?> clazz = WebAppInitializer.class.getClassLoader().loadClass(bd.getBeanClassName());
                rootContext.register(clazz);
            } catch (ClassNotFoundException ex) {
                LOG.error("Unable to load class: " + bd.getBeanClassName(), ex);
            }
        }
    }
    rootContext.refresh();

    servletContext.addListener(new ContextLoaderListener(rootContext));
}

From source file:org.zalando.stups.spring.cloud.netflix.feign.OAuth2FeignClientsRegsitrar.java

@Override
public void registerBeanDefinitions(final AnnotationMetadata importingClassMetadata,
        final BeanDefinitionRegistry registry) {

    Set<String> basePackages = getBasePackages(importingClassMetadata);

    ClassPathScanningCandidateComponentProvider scanner = getScanner();
    scanner.addIncludeFilter(new AnnotationTypeFilter(FeignClient.class));
    scanner.setResourceLoader(this.resourceLoader);

    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();
                Assert.isTrue(annotationMetadata.isInterface(),
                        "@FeignClient can only be specified on an interface");

                BeanDefinitionHolder holder = createBeanDefinition(annotationMetadata);
                BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
            }/*  w w  w .  ja v a  2 s .  c  o m*/
        }
    }
}

From source file:com.googlecode.icegem.serialization.spring.AutoSerializableRegistrarBean.java

private void registerClasses(ClassLoader classLoader) throws ClassNotFoundException {

    List<Class<?>> toRegister = new ArrayList<Class<?>>();

    for (String pack : scanPackages) {
        logger.debug("Scan {}.* for @AutoSerializable classes", pack);
        ClassPathScanningCandidateComponentProvider ppp = new ClassPathScanningCandidateComponentProvider(
                false);/*w  w w.  j  a  v a2 s .c o m*/
        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);
            toRegister.add(clazz);
        }
    }

    toRegister.addAll(registeredClasses);
    logger.info("All classes that will be registered in GemFire: " + toRegister);

    try {
        HierarchyRegistry.registerAll(classLoader, toRegister);
    } catch (InvalidClassException e) {
        final String msg = "Some class from list " + toRegister + " is nor serializable. Cause: "
                + e.getMessage();
        throw new IllegalArgumentException(msg, e);
    } catch (CannotCompileException e) {
        final String msg = "Can't compile DataSerializer classes for some classes from list " + toRegister
                + ". Cause: " + e.getMessage();
        throw new IllegalArgumentException(msg, e);
    }
}

From source file:ch.sdi.core.util.ClassUtil.java

/**
* Lists all types in the given package (recursive) which are annotated by the given annotation.
* <p>//from   w ww  .j a va  2 s  . co m
* All types which match the criteria are returned, no further checks (interface, abstract, embedded, etc.
* are performed.
* <p>
*
* @param aAnnotation
*        the desired annotation type
* @param aRoot
*        the package name where to start the search. Must not be empty. And not start
*        with 'org.springframework' (cannot parse springs library itself).
* @return a list of found types
*/
public static Collection<? extends Class<?>> findCandidatesByAnnotation(Class<? extends Annotation> aAnnotation,
        String aRoot) {
    if (!StringUtils.hasText(aRoot)) {
        throw new IllegalArgumentException("aRoot must not be empty (cannot parse spring library classes)");

    } // if StringUtils.hasText( aRoot )

    if (aRoot.startsWith("org.springframework")) {
        throw new IllegalArgumentException("cannot parse spring library classes");

    } // if StringUtils.hasText( aRoot )

    List<Class<?>> result = new ArrayList<Class<?>>();

    MyClassScanner scanner = new MyClassScanner();

    scanner.addIncludeFilter(new AnnotationTypeFilter(aAnnotation));
    Set<BeanDefinition> canditates = scanner.findCandidateComponents(aRoot);
    for (BeanDefinition beanDefinition : canditates) {
        try {
            String classname = beanDefinition.getBeanClassName();
            Class<?> clazz = Class.forName(classname);
            result.add(clazz);
        } catch (ClassNotFoundException t) {
            myLog.error("Springs type scanner returns a class name whose class cannot be evaluated!!!", t);
        }
    }

    return result;
}

From source file:com.github.ljtfreitas.restify.spring.configure.RestifyConfigurationRegistrar.java

@SuppressWarnings("unchecked")
private Set<TypeFilter> filters(RestifyExcludeFilter[] filters) {
    Set<TypeFilter> typeFilters = new LinkedHashSet<>();

    Arrays.stream(filters).forEach(f -> {
        Arrays.stream(f.classes()).forEach(classType -> {
            switch (f.type()) {
            case ANNOTATION: {
                typeFilters.add(new AnnotationTypeFilter((Class<? extends Annotation>) classType));
                break;
            }//from  w w  w  .  j  a  va 2  s  .c  om
            case ASSIGNABLE_TYPE: {
                typeFilters.add(new AssignableTypeFilter(classType));
                break;
            }
            case CUSTOM: {
                typeFilters.add(Tryable.of(() -> (TypeFilter) classType.newInstance(),
                        () -> new IllegalArgumentException(
                                "Cannot construct your custom TypeFilter of type [" + classType + "]")));
            }
            default: {
                throw new IllegalArgumentException("Illegal @Filter use. "
                        + "Your configure [classes] attribute with filter type [" + f.type() + "]");
            }
            }
        });

        Arrays.stream(f.pattern()).forEach(pattern -> {
            switch (f.type()) {
            case REGEX: {
                typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(pattern)));
            }
            case ASPECTJ: {
                typeFilters.add(new AspectJTypeFilter(pattern, resourceLoader.getClassLoader()));
            }
            default: {
                throw new IllegalArgumentException("Illegal @Filter use. "
                        + "Your configure [pattern] attribute with filter type [" + f.type() + "]");
            }
            }
        });
    });

    return typeFilters;
}

From source file:com.hortonworks.registries.common.util.ReflectionHelper.java

public static Collection<Class<?>> getAnnotatedClasses(String basePackage,
        Class<? extends Annotation> annotation) {
    Collection<Class<?>> classes = new ArrayList<>();
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);/*from   w  w w .  j  a  v  a 2  s  . com*/
    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;
}

From source file:it.geosolutions.geobatch.annotations.ActionServicePostProcessor.java

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

    if (bean.getClass().equals(AliasRegistry.class)) {
        AliasRegistry aliasRegistry = (AliasRegistry) bean;
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
                true);/*w  w  w .  j a v a2s .c  om*/
        scanner.addIncludeFilter(new AnnotationTypeFilter(Action.class));
        for (BeanDefinition bd : scanner.findCandidateComponents("it.geosolutions")) {
            try {
                Class actionClass = Class.forName(bd.getBeanClassName());
                Action annotation = (Action) actionClass.getAnnotation(Action.class);
                if (annotation != null) {
                    Class<? extends ActionConfiguration> configurationClass = annotation.configurationClass();

                    String alias = configurationClass.getSimpleName();
                    if (annotation.configurationAlias() != null && !annotation.configurationAlias().isEmpty()) {
                        alias = annotation.configurationAlias();
                    }
                    aliasRegistry.putAlias(alias, configurationClass);

                    if (annotation.aliases() != null) {
                        for (Class a : annotation.aliases()) {
                            if (NullType.class == a)
                                continue;
                            aliasRegistry.putAlias(a.getSimpleName(), a);
                        }
                    }

                    if (annotation.implicitCollections() != null) {
                        for (String ic : annotation.implicitCollections()) {
                            if (ic == null || ic.isEmpty())
                                continue;
                            aliasRegistry.putImplicitCollection(ic, configurationClass);
                        }
                    }

                    GenericActionService asr = new GenericActionService(
                            annotation.configurationClass().getSimpleName(), actionClass);
                    asr.setApplicationContext(applicationContext);
                    actionList.add(asr);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    return bean;
}