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:com.couchbase.spring.config.AbstractCouchbaseConfiguration.java

/**
 * Scans the mapping base package for classes annotated with {@link Document}.
 *//*from   w  w w  .ja v  a2 s. c o  m*/
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(),
                    AbstractCouchbaseConfiguration.class.getClassLoader()));
        }
    }

    return initialEntitySet;
}

From source file:com.github.gdrouet.scannerbenchmark.JmhBenchmark.java

/**
 * <p>/*w w w .ja v  a2s  .  c  om*/
 * Looking for type annotated with an annotation with Spring.
 * </p>
 */
@Benchmark
public void scanAnnotatedTypeWithSpring() {
    final ClassPathScanningCandidateComponentProvider s = new ClassPathScanningCandidateComponentProvider(
            false);
    s.addIncludeFilter(new AnnotationTypeFilter(ANNOTATION));
    final Set<BeanDefinition> r = s.findCandidateComponents(PACKAGE);
    LOGGER.info("{} classes annotated with {} retrieved with Spring", r.size(), ANNOTATION.getName());
}

From source file:org.datamongo.jira.datamongo1064.mapper.EmbeddedObjectTypeInformationMapper.java

/**
 * Scans the mapping base package for classes annotated with {@link Embeddable}.
 * /* ww w  .j  a v  a2 s.  c  om*/
 * @see #getMappingBasePackage()
 * @return
 * @throws ClassNotFoundException
 */
protected Map<Class<?>, String> getInitialEntitySet() throws ClassNotFoundException {

    String[] basePackage = this.basePackage;
    Map<Class<?>, String> initialEntitySet = new HashMap<Class<?>, String>();

    if (basePackage != null) {
        for (String packageBase : basePackage) {
            if (StringUtils.hasText(packageBase)) {
                ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(
                        false);
                componentProvider.addIncludeFilter(new AnnotationTypeFilter(Embeddable.class));

                for (BeanDefinition candidate : componentProvider.findCandidateComponents(packageBase)) {
                    Class<?> forName = ClassUtils.forName(candidate.getBeanClassName(),
                            AbstractMongoConfiguration.class.getClassLoader());
                    String alias = forName.getAnnotation(TypeAlias.class) != null
                            ? forName.getAnnotation(TypeAlias.class).value()
                            : forName.getName();
                    initialEntitySet.put(forName, alias);
                }
            }
        }
    }

    return initialEntitySet;
}

From source file:com.googlecode.spring.appengine.objectify.OfyServiceBuilder.java

protected List<Class<?>> scanBasePackages() {
    List<Class<?>> classes = new ArrayList<Class<?>>();
    for (String basePackage : basePackages) {
        if (this.logger.isInfoEnabled()) {
            this.logger.info("Scanning package [" + basePackage + "]");
        }/*from  w  w  w  .  j  a v a2  s. com*/
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
                false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
        Set<BeanDefinition> candidates = scanner.findCandidateComponents(basePackage);
        for (BeanDefinition candidate : candidates) {
            Class<?> clazz = ClassUtils.resolveClassName(candidate.getBeanClassName(),
                    ClassUtils.getDefaultClassLoader());
            classes.add(clazz);
        }
    }
    return classes;
}

From source file:utils.HibernateSessionFactory.java

private static void buildSessionFactory() {

    try {/*from   w  ww .j a v a  2 s. c o  m*/
        if (sessionFactory == null) {
            //Play.current().getFile("conf/hibernate.cfg.xml")
            configuration = new AnnotationConfiguration().configure(configFile);

            /*ArrayList<Class> classes = new ArrayList<Class>();
                    
            LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
            sessionFactoryBean.setDataSource(dataSource());
            //sessionFactoryBean.setAnnotatedClasses(new Class[]{Team.class});//new row!!!
            //sessionFactoryBean.setPackagesToScan("models.db");
            sessionFactoryBean.setHibernateProperties(hibProperties());
            */
            //org.springframework.orm.hibernate4.LocalSessionFactoryBean
            // the following will detect all classes that are annotated as @Entity
            ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
                    false);

            scanner.addIncludeFilter(new AnnotationTypeFilter(Embeddable.class));
            scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));

            // only register classes within "com.fooPackage" package
            for (BeanDefinition bd : scanner.findCandidateComponents("models.db")) {
                String name = bd.getBeanClassName();
                try {
                    Class.forName(name).newInstance();
                    Logger.debug("Adding entity : " + name);
                    configuration.addAnnotatedClass(Class.forName(name));
                } catch (Exception E) {
                    // TODO: handle exception - couldn't load class in question
                    E.printStackTrace();
                }
            } // for

            //sessionFactory = sessionFactoryBean.getObject();

            //configuration.setInterceptor(new HibernatePostLoadInterceptor());
            //configuration.setListener("post-load",new ACenterAPostLoadEventListener());

            //configuration.configure(configFile);

            sessionFactory = configuration.buildSessionFactory();

            /*
             SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) hibernateEntityManagerFactory.getSessionFactory();
            sessionFactoryImpl.getEventListeners().setPreInsertEventListeners(new <span class="skimlinks-unlinked">org.hibernate.event.PreInsertEventListener</span>[] { this.preInsertEventListener });
            sessionFactoryImpl.getEventListeners().setPreUpdateEventListeners(new <span class="skimlinks-unlinked">org.hibernate.event.PreUpdateEventListener</span>[] { this.preUpdateEventListener });
            sessionFactoryImpl.getEventListeners().setPreDeleteEventListeners(new <span class="skimlinks-unlinked">org.hibernate.event.PreDeleteEventListener</span>[] { this.preDeleteEventListener });
                    
                    
            SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) hibernateEntityManagerFactory.getSessionFactory();
            EventListenerRegistry registry = sessionFactoryImpl.getServiceRegistry().getService(<span class="skimlinks-unlinked">EventListenerRegistry.class</span>);
            registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(listener);
            registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(listener);
            }
             */

            //sessionFactory.getE
            //org.hibernate.SessionFactoryObserver

            /*HistoryListener historyListener = new HistoryListener();
            configuration.setL  ("pre-insert", historyListener);
            configuration.setListener("pre-update", historyListener);
            configuration.setListener("pre-delete", historyListener);*/

            /*
                            EntityCallbackHandler callbackHandler = new EntityCallbackHandler();
                            callbackHandler.add(reflectionManager.toXClass(EntityWithJPACallbacks.class), reflectionManager);
                            EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
            // for @PrePersist:
                            registry.setListeners(EventType.PERSIST, new EJB3PersistEventListener(callbackHandler));
            // for @PreUpdate
                            registry.setListeners(EventType.FLUSH_ENTITY, new EJB3FlushEntityEventListener(callbackHandler));
                            */

            // only register classes within "com.fooPackage" package
            //ACenterA TODO: SESSION FACTORY CREATED..
            PluginManager.notifyEvent(PluginEvent.HIBERNATE_SESSION_FACTORY_CREATED, getSession());

            /*
            /* Internal ACenterA Inc. Use
            ClassPathScanningCandidateComponentProvider scannerTree =
                new ClassPathScanningCandidateComponentProvider(false);
                    
                    
            scannerTree.addIncludeFilter(new AnnotationTypeFilter(models.tree.TreeItem.class));
                    
                    
            getSession();
            for (BeanDefinition bd : scannerTree.findCandidateComponents("models.tree")) {
            String classId = bd.getBeanClassName();
            try {
                Logger.debug("WILL INSERT INTO ELEMENTS_TYPE : " + classId);
                Class.forName(classId).newInstance();
                ElementsType type = new ElementsType();
                    
                type.setClassId(classId);
                    
                type.setName(classId);
                    
                ElementsType t = ElementsTypeImpl.getOrCreateElementsType(type);
                Logger.debug("INSERTED OF : " + t);
                //configuration.addAnnotatedClass();
            } catch (Exception E) {
                // TODO: handle exception - couldn't load class in question
                E.printStackTrace();
            }
            } // for
            */

            closeSession();

        }
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("%%%% Error Creating SessionFactory %%%%");
        e.printStackTrace();
    }

}

From source file:org.mybatis.spring.mapper.MapperScanner.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 ww  .j  a  v  a  2  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.comstar.mars.env.EnvClassPathMapperScanner.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  a  v  a  2s .  c  om
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.sourceallies.beanoh.BeanohTestCase.java

/**
 * Reconcile the beans marked with org.springframework.stereotype.Component
 * in the classpath with the beans loaded in the Spring context.
 * /*from  w  ww.j a v a 2  s. c  o 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:org.jsconf.core.ConfigurationFactory.java

public ConfigurationFactory withScanPackage(String forPackage) {
    ClassPathScanningCandidate candidateComponentProvider = new ClassPathScanningCandidate(false);
    candidateComponentProvider.addIncludeFilter(new AnnotationTypeFilter(ConfigurationProperties.class));
    Set<Class<?>> candidate = candidateComponentProvider.findCandidateClass(forPackage);
    for (Class<?> cl : candidate) {
        withBean(cl);/* w  w w.  j av  a 2  s . c o m*/
    }
    return this;
}

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  a va2 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() {
            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");
        }
    });

}