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

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

Introduction

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

Prototype

public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters) 

Source Link

Document

Create a ClassPathScanningCandidateComponentProvider with a StandardEnvironment .

Usage

From source file:com.foilen.smalltools.tools.Hibernate50Tools.java

/**
 * Generate the SQL file. This is based on the code in {@link LocalSessionFactoryBuilder#scanPackages(String...)}
 *
 * @param dialect//from   ww  w.j  a v  a 2s  .  c  o m
 *            the dialect (e.g: org.hibernate.dialect.MySQL5InnoDBDialect )
 * @param outputSqlFile
 *            where to put the generated SQL file
 * @param useUnderscore
 *            true: to have tables names like "employe_manager" ; false: to have tables names like "employeManager"
 * @param packagesToScan
 *            the packages where your entities are
 */
public static void generateSqlSchema(Class<? extends Dialect> dialect, String outputSqlFile,
        boolean useUnderscore, String... packagesToScan) {

    BootstrapServiceRegistry bootstrapServiceRegistry = new BootstrapServiceRegistryBuilder().build();

    MetadataSources metadataSources = new MetadataSources(bootstrapServiceRegistry);

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(Embeddable.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(MappedSuperclass.class));
    for (String pkg : packagesToScan) {
        for (BeanDefinition beanDefinition : scanner.findCandidateComponents(pkg)) {
            metadataSources.addAnnotatedClassName(beanDefinition.getBeanClassName());
        }
    }

    StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder(
            bootstrapServiceRegistry);
    standardServiceRegistryBuilder.applySetting(AvailableSettings.DIALECT, dialect.getName());
    StandardServiceRegistryImpl ssr = (StandardServiceRegistryImpl) standardServiceRegistryBuilder.build();
    MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(ssr);

    if (useUnderscore) {
        metadataBuilder.applyImplicitNamingStrategy(new SpringImplicitNamingStrategy());
        metadataBuilder.applyPhysicalNamingStrategy(new SpringPhysicalNamingStrategy());
    }

    MetadataImpl metadata = (MetadataImpl) metadataBuilder.build();

    // Exportation
    SchemaExport schemaExport = new SchemaExport(metadata);
    schemaExport.setOutputFile(outputSqlFile);
    schemaExport.setDelimiter(";");
    schemaExport.setFormat(true);
    schemaExport.execute(true, false, false, true);
}

From source file:com.newtranx.util.cassandra.spring.MapperScannerConfigurer.java

@SuppressWarnings("unused") // compiler bug?
@Override//from  ww  w. java  2 s  .co  m
public void postProcessBeanFactory(ConfigurableListableBeanFactory context) throws BeansException {
    synchronized (lock) {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
                false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(Table.class));
        for (BeanDefinition bd : scanner.findCandidateComponents(basePackage)) {
            Class<?> entityCls;
            try {
                entityCls = Class.forName(bd.getBeanClassName());
            } catch (ClassNotFoundException e) {
                throw new AssertionError(e);
            }
            log.info("Creating proxy mapper for entity: " + entityCls.getName());
            CassandraMapper annotation = entityCls.getAnnotation(CassandraMapper.class);
            Mapper<?> bean = createProxy(Mapper.class, new MyInterceptor(entityCls, annotation.singleton()));
            String beanName;
            if (annotation == null)
                beanName = StringUtils.uncapitalize(entityCls.getSimpleName()) + "Mapper";
            else
                beanName = annotation.value();
            context.registerSingleton(beanName, bean);
            log.info("Bean registed, name=" + beanName + ", bean=" + bean.toString());
        }
    }
}

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 {/* ww  w .  j  a v a  2 s  .co 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.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  w w .j av  a  2s .co 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.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  .  j  av  a 2 s.  co  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:com.qubit.solution.fenixedu.bennu.webservices.servlet.BennuWebservicesInitializer.java

@Atomic(mode = TxMode.READ)
private void synchorizeServices() {
    for (Class clazz : BennuWebService.getAvailableWebServices()) {
        checkServerConfigurationAndCreateIfNeeded(clazz.getName());
    }/*from w  ww .j  a  va 2 s.  co  m*/

    // Since clients are initialised by the WsServlet we need to look them up via classpath scanning
    // using spring componentprovider since we do not have OMNIS lookup available
    // 21 April 2015 - Paulo Abrantes

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new AssignableTypeFilter(BennuWebServiceClient.class));

    Set<BeanDefinition> components = provider
            .findCandidateComponents(BennuWebServiceClient.class.getPackage().getName().replace('.', '/'));
    for (BeanDefinition component : components) {
        try {
            Class cls = Class.forName(component.getBeanClassName());
            checkClientConfigurationAndCreateIfNeeded(cls.getName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        // use class cls found
    }

    deleteConfigurations(Bennu.getInstance().getWebserviceConfigurationsSet().stream()
            .filter(configuration -> !configuration.isImplementationClassAvailable())
            .collect(Collectors.toList()));

}

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);/*from   w ww. ja va  2 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:org.openmrs.module.CDAGenerator.api.impl.CDAGeneratorServiceImpl.java

@Override
public List<BaseCdaSectionHandler> getAllCdaSectionHandlers() {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            true);/*w ww  .j  a v a  2s .  c  o m*/

    provider.addIncludeFilter(new AssignableTypeFilter(BaseCdaSectionHandler.class));

    List<BaseCdaSectionHandler> sectionHandlers = new ArrayList<BaseCdaSectionHandler>();

    // scan in org.openmrs.module.CDAGenerator.Sectionhandlers package
    Set<BeanDefinition> components = provider
            .findCandidateComponents("org.openmrs.module.CDAGenerator.SectionHandlers");

    for (BeanDefinition component : components) {
        try {

            Class cls = Class.forName(component.getBeanClassName());

            BaseCdaSectionHandler p = (BaseCdaSectionHandler) cls.newInstance();
            if (p.templateid != null) {
                sectionHandlers.add(p);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return sectionHandlers;
}

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);/*www .  jav  a 2s .c  o  m*/
    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  a  2  s  . com
        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;
}