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

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

Introduction

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

Prototype

public RegexPatternTypeFilter(Pattern pattern) 

Source Link

Usage

From source file:biz.c24.io.spring.config.C24ModelBeanDefinitionParser.java

/**
 * Classpath scans the given base package for subclasses of {@link biz.c24.io.api.data.Element} whose names end on
 * {@code DocumentRootElement}.// w  w w . j  a va2 s  .c  om
 * 
 * @param basePackage
 * @param context
 * @param source
 * @return
 */
private AbstractBeanDefinition getC24ModelFromPackage(String basePackage, ParserContext context,
        Object source) {

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new TypeFilter() {

        private final TypeFilter nameFilter = new RegexPatternTypeFilter(
                Pattern.compile(".*DocumentRootElement"));
        private final TypeFilter typeFilter = new AssignableTypeFilter(biz.c24.io.api.data.Element.class);

        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            return nameFilter.match(metadataReader, metadataReaderFactory)
                    && typeFilter.match(metadataReader, metadataReaderFactory);
        }
    });

    Set<BeanDefinition> result = provider.findCandidateComponents(basePackage);
    if (result.size() != 1) {
        context.getReaderContext().error("Found none or multiple classes ending on 'DocumentRootElement'!",
                source);
    }

    String elementClassName = result.iterator().next().getBeanClassName();
    return getC24ModelFromElement(elementClassName, context, source);
}

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  ava  2  s . c  o m*/
            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: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://from w  w  w . ja v a2  s.c om
            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. j  av a2 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 {// w  ww. j a  v a  2s.c om
        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:org.synyx.hades.dao.config.DaoConfigDefinitionParser.java

/**
 * Tries to detect a custom implementation for a DAO bean by classpath
 * scanning./*from www  . ja  va  2 s.c o  m*/
 * 
 * @param context
 * @param parser
 * @return the {@code BeanDefinition} of the custom implementation or null
 *         if none found
 */
private AbstractBeanDefinition detectCustomImplementation(final DaoContext context,
        final ParserContext parser) {

    // Build pattern to lookup implementation class
    Pattern pattern = Pattern.compile(".*" + context.getImplementationClassName());

    // Build classpath scanner and lookup bean definition
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.setResourceLoader(parser.getReaderContext().getResourceLoader());
    provider.addIncludeFilter(new RegexPatternTypeFilter(pattern));
    Set<BeanDefinition> definitions = provider.findCandidateComponents(context.getDaoBasePackageName());

    return (0 == definitions.size() ? null : (AbstractBeanDefinition) definitions.iterator().next());
}

From source file:org.springframework.data.repository.config.AbstractRepositoryConfigDefinitionParser.java

/**
 * Tries to detect a custom implementation for a repository bean by classpath scanning.
 * /*from  w w  w  .j  a  va2 s.  c  o  m*/
 * @param config
 * @param parser
 * @return the {@code AbstractBeanDefinition} of the custom implementation or {@literal null} if none found
 */
private AbstractBeanDefinition detectCustomImplementation(T config, ParserContext parser) {

    // Build pattern to lookup implementation class
    Pattern pattern = Pattern.compile(".*\\." + config.getImplementationClassName());

    // Build classpath scanner and lookup bean definition
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.setResourceLoader(parser.getReaderContext().getResourceLoader());
    provider.addIncludeFilter(new RegexPatternTypeFilter(pattern));
    Set<BeanDefinition> definitions = provider.findCandidateComponents(config.getBasePackage());

    if (definitions.size() == 0) {
        return null;
    }

    if (definitions.size() == 1) {
        return (AbstractBeanDefinition) definitions.iterator().next();
    }

    List<String> implementationClassNames = new ArrayList<String>();
    for (BeanDefinition bean : definitions) {
        implementationClassNames.add(bean.getBeanClassName());
    }

    throw new IllegalStateException(String.format(
            "Ambiguous custom implementations detected! Found %s but expected a single implementation!",
            StringUtils.collectionToCommaDelimitedString(implementationClassNames)));
}

From source file:org.springframework.data.repository.config.RepositoryBeanDefinitionBuilder.java

/**
 * Tries to detect a custom implementation for a repository bean by classpath scanning.
 * //ww  w .j  a  v  a 2 s.co m
 * @param config
 * @param parser
 * @return the {@code AbstractBeanDefinition} of the custom implementation or {@literal null} if none found
 */
private AbstractBeanDefinition detectCustomImplementation(BeanDefinitionRegistry registry,
        ResourceLoader loader) {

    // Build pattern to lookup implementation class
    Pattern pattern = Pattern.compile(".*\\." + configuration.getImplementationClassName());

    // Build classpath scanner and lookup bean definition
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.setResourceLoader(loader);
    provider.addIncludeFilter(new RegexPatternTypeFilter(pattern));

    Set<BeanDefinition> definitions = new HashSet<BeanDefinition>();

    for (String basePackage : configuration.getBasePackages()) {
        definitions.addAll(provider.findCandidateComponents(basePackage));
    }

    if (definitions.isEmpty()) {
        return null;
    }

    if (definitions.size() == 1) {
        return (AbstractBeanDefinition) definitions.iterator().next();
    }

    List<String> implementationClassNames = new ArrayList<String>();
    for (BeanDefinition bean : definitions) {
        implementationClassNames.add(bean.getBeanClassName());
    }

    throw new IllegalStateException(String.format(
            "Ambiguous custom implementations detected! Found %s but expected a single implementation!",
            StringUtils.collectionToCommaDelimitedString(implementationClassNames)));
}

From source file:org.springframework.retry.backoff.BackOffPolicySerializationTests.java

@Parameters(name = "{index}: {0}")
public static List<Object[]> policies() {
    List<Object[]> result = new ArrayList<Object[]>();
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(BackOffPolicy.class));
    scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Test.*")));
    scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Mock.*")));
    scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Configuration.*")));
    Set<BeanDefinition> candidates = scanner.findCandidateComponents("org.springframework.retry");
    for (BeanDefinition beanDefinition : candidates) {
        try {// w  w w. j a  v  a 2 s  . c o  m
            result.add(new Object[] { BeanUtils
                    .instantiate(ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), null)) });
        } catch (Exception e) {
            logger.warn("Cannot create instance of " + beanDefinition.getBeanClassName());
        }
    }
    return result;
}

From source file:org.springframework.retry.policy.RetryContextSerializationTests.java

@Parameters(name = "{index}: {0}")
public static List<Object[]> policies() {
    List<Object[]> result = new ArrayList<Object[]>();
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(RetryPolicy.class));
    scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Test.*")));
    scanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*Mock.*")));
    Set<BeanDefinition> candidates = scanner.findCandidateComponents("org.springframework.retry.policy");
    for (BeanDefinition beanDefinition : candidates) {
        try {//from w w w .j  a v a 2 s.co  m
            result.add(new Object[] { BeanUtils
                    .instantiate(ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), null)) });
        } catch (Exception e) {
            logger.warn("Cannot create instance of " + beanDefinition.getBeanClassName(), e);
        }
    }
    ExceptionClassifierRetryPolicy extra = new ExceptionClassifierRetryPolicy();
    extra.setExceptionClassifier(new SubclassClassifier<Throwable, RetryPolicy>(new AlwaysRetryPolicy()));
    result.add(new Object[] { extra });
    return result;
}