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

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

Introduction

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

Prototype

public AssignableTypeFilter(Class<?> targetType) 

Source Link

Document

Create a new AssignableTypeFilter for the given type.

Usage

From source file:framework.generic.mybatis.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
 */// w  w  w  .j  av  a2  s . com
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() {
            public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                    throws IOException {
                return true;
            }
        });
    }

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

}

From source file:com.qubit.solution.fenixedu.integration.cgd.ui.cgdConfiguration.CgdIntegrationConfigurationController.java

@RequestMapping(value = "/update/{oid}/strategies", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
public @org.springframework.web.bind.annotation.ResponseBody List<String> requestAvailableStrategies(
        @PathVariable("oid") CgdIntegrationConfiguration cgdIntegrationConfiguration, Model model) {

    List<String> results = new ArrayList<String>();
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);/* www .j  a v  a  2s. co m*/
    provider.addIncludeFilter(new AssignableTypeFilter(IMemberIDAdapter.class));
    for (BeanDefinition definition : provider
            .findCandidateComponents("/com/qubit/solution/fenixedu/integration/cgd/services/memberid")) {
        results.add(definition.getBeanClassName());
    }

    return results;
}

From source file:org.codehaus.grepo.core.config.GenericRepositoryScanBeanDefinitionParser.java

/**
 * @param element The element./* ww  w .ja v  a 2 s . c  om*/
 * @param scanner The scanner.
 * @param readerContext The reader context.
 */
protected void parseTypeFilters(Element element, GenericRepositoryBeanDefinitionScanner scanner,
        XmlReaderContext readerContext) {

    // Parse exclude and include filter elements.
    ClassLoader classLoader = scanner.getResourceLoader().getClassLoader();
    NodeList nodeList = element.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            String localName = node.getLocalName();
            try {
                if (INCLUDE_FILTER_ELEMENT.equals(localName)) {
                    // Note: that we use the composite type filter for include-filter,
                    // because we always want repositories of appropriate interface type...
                    CompositeTypeFilter typeFilter = new CompositeTypeFilter();
                    typeFilter.addTypeFilter(new AssignableTypeFilter(requiredGenericRepositoryType));
                    typeFilter.addTypeFilter(createTypeFilter((Element) node, classLoader));
                    scanner.addIncludeFilter(typeFilter);
                } else if (EXCLUDE_FILTER_ELEMENT.equals(localName)) {
                    TypeFilter typeFilter = createTypeFilter((Element) node, classLoader);
                    scanner.addExcludeFilter(typeFilter);
                }
            } catch (Exception ex) {
                readerContext.error(ex.getMessage(), readerContext.extractSource(element), ex.getCause());
            }
        }
    }
}

From source file:org.spring.guice.annotation.GuiceModuleRegistrar.java

private List<TypeFilter> typeFiltersFor(AnnotationAttributes filterAttributes) {

    List<TypeFilter> typeFilters = new ArrayList<TypeFilter>();
    FilterType filterType = filterAttributes.getEnum("type");

    for (Class<?> filterClass : filterAttributes.getClassArray("value")) {
        switch (filterType) {
        case ANNOTATION:
            Assert.isAssignable(Annotation.class, filterClass,
                    "An error occured when processing a @ComponentScan " + "ANNOTATION type filter: ");
            @SuppressWarnings("unchecked")
            Class<Annotation> annoClass = (Class<Annotation>) filterClass;
            typeFilters.add(new AnnotationTypeFilter(annoClass));
            break;
        case ASSIGNABLE_TYPE:
            typeFilters.add(new AssignableTypeFilter(filterClass));
            break;
        case CUSTOM:
            Assert.isAssignable(TypeFilter.class, filterClass,
                    "An error occured when processing a @ComponentScan " + "CUSTOM type filter: ");
            typeFilters.add(BeanUtils.instantiateClass(filterClass, TypeFilter.class));
            break;
        default://  w w  w .jav  a2 s  .  c o  m
            throw new IllegalArgumentException("Unknown filter type " + filterType);
        }
    }

    for (String expression : getPatterns(filterAttributes)) {

        String rawName = filterType.toString();

        if ("REGEX".equals(rawName)) {
            typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression)));
        } else if ("ASPECTJ".equals(rawName)) {
            typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader.getClassLoader()));
        } else {
            throw new IllegalArgumentException("Unknown filter type " + filterType);
        }
    }

    return typeFilters;
}

From source file:org.codehaus.grepo.core.config.GenericRepositoryScanBeanDefinitionParser.java

/**
 * @param element The element./*from   w ww  .  ja v  a 2  s .  c o m*/
 * @param classLoader The class loader.
 * @return Returns the type filter.
 */
@SuppressWarnings("unchecked")
protected TypeFilter createTypeFilter(Element element, ClassLoader classLoader) {
    String filterType = element.getAttribute(FILTER_TYPE_ATTRIBUTE);
    String expression = element.getAttribute(FILTER_EXPRESSION_ATTRIBUTE);
    try {
        if ("annotation".equals(filterType)) {
            return new AnnotationTypeFilter((Class<Annotation>) classLoader.loadClass(expression));
        } else if ("assignable".equals(filterType)) {
            return new AssignableTypeFilter(classLoader.loadClass(expression));
        } else if ("aspectj".equals(filterType)) {
            return new AspectJTypeFilter(expression, classLoader);
        } else if ("regex".equals(filterType)) {
            return new RegexPatternTypeFilter(Pattern.compile(expression));
        } else if ("custom".equals(filterType)) {
            Class filterClass = classLoader.loadClass(expression);
            if (!TypeFilter.class.isAssignableFrom(filterClass)) {
                throw new IllegalArgumentException(
                        "Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression);
            }
            return (TypeFilter) BeanUtils.instantiateClass(filterClass);
        } else {
            throw new IllegalArgumentException("Unsupported filter type: " + filterType);
        }
    } catch (ClassNotFoundException ex) {
        throw new FatalBeanException("Type filter class not found: " + expression, ex);
    }
}

From source file:info.sargis.eventbus.config.EventBusHandlerBeanDefinitionParser.java

@SuppressWarnings("unchecked")
protected TypeFilter createTypeFilter(Element element, ClassLoader classLoader) {
    String filterType = element.getAttribute(FILTER_TYPE_ATTRIBUTE);
    String expression = element.getAttribute(FILTER_EXPRESSION_ATTRIBUTE);
    try {/*from  w  ww . j  a  v  a  2 s .c o  m*/
        if ("annotation".equals(filterType)) {
            return new AnnotationTypeFilter((Class<Annotation>) classLoader.loadClass(expression));
        } else if ("assignable".equals(filterType)) {
            return new AssignableTypeFilter(classLoader.loadClass(expression));
        } else if ("regex".equals(filterType)) {
            return new RegexPatternTypeFilter(Pattern.compile(expression));
        } else if ("custom".equals(filterType)) {
            Class filterClass = classLoader.loadClass(expression);
            if (!TypeFilter.class.isAssignableFrom(filterClass)) {
                throw new IllegalArgumentException(
                        "Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression);
            }
            return (TypeFilter) BeanUtils.instantiateClass(filterClass);
        } else {
            throw new IllegalArgumentException("Unsupported filter type: " + filterType);
        }
    } catch (ClassNotFoundException ex) {
        throw new FatalBeanException("Type filter class not found: " + expression, ex);
    }
}

From source file:com.agileapes.couteau.maven.mojo.AbstractPluginExecutor.java

/**
 * This method will return a set of all project classes
 *
 * @return the classes/*from  www .j a  v a 2 s.c o  m*/
 */
protected Set<Class> getClasses() {
    final ClassPathScanningClassProvider scanner = new ClassPathScanningClassProvider(true);
    scanner.setClassLoader(getProjectClassLoader());
    scanner.addIncludeFilter(new AssignableTypeFilter(Object.class));
    final Set<Class> candidateClasses = new LinkedHashSet<Class>();
    with(getScanPackages()).each(new Processor<String>() {
        @Override
        public void process(String input) {
            candidateClasses.addAll(scanner.findCandidateClasses(input));
        }
    });
    return candidateClasses;
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.stylesheet.StylesheetValidationTest.java

private Stream<Class<? extends S2SFormGenerator>> getGeneratorsToTest() {
    final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);//from w  ww  .java 2  s.  c  om

    final TypeFilter testableFilter = (metadataReader,
            metadataReaderFactory) -> new AnnotationTypeFilter(FormGenerator.class).match(metadataReader,
                    metadataReaderFactory)
                    && new AssignableTypeFilter(S2SFormGenerator.class).match(metadataReader,
                            metadataReaderFactory)
                    && !metadataReader.getClassMetadata().isAbstract()
                    && !BROKEN_GENERATORS.contains(metadataReader.getClassMetadata().getClassName());

    provider.addIncludeFilter(testableFilter);
    provider.addExcludeFilter(new AssignableTypeFilter(DynamicNamespace.class));
    provider.setResourceLoader(new PathMatchingResourcePatternResolver(this.getClass().getClassLoader()));
    final Set<BeanDefinition> generators = provider
            .findCandidateComponents("org.kuali.coeus.s2sgen.impl.generate.support");
    return generators.stream().map(generator -> {
        try {
            @SuppressWarnings("unchecked")
            final Class<? extends S2SFormGenerator> clazz = (Class<? extends S2SFormGenerator>) Class
                    .forName(generator.getBeanClassName());
            return clazz;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    });
}

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

@Test
public void failIfNewTypeOfMaterialIsNotAddedInTheAboveTest() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);/*  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:cross.applicationContext.ReflectionApplicationContextGenerator.java

/**
 *
 * @param clazz/*from w w w  .  j  a va2 s. c o  m*/
 * @param packages
 * @return
 */
public static Set<BeanDefinition> getImplementationsOf(Class<?> clazz, String... packages) {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new AssignableTypeFilter(clazz));
    Set<BeanDefinition> beanDefinitions = new LinkedHashSet<>();
    for (String pkg : packages) {
        String pkgDeclaration = "";
        if (pkg.contains(".")) {
            pkgDeclaration = pkg.replaceAll("\\.", "/");
        }
        Set<BeanDefinition> components = provider.findCandidateComponents(pkgDeclaration);
        beanDefinitions.addAll(components);
    }
    return beanDefinitions;
}