Java Code Examples for org.springframework.core.io.support.ResourcePatternResolver#CLASSPATH_ALL_URL_PREFIX

The following examples show how to use org.springframework.core.io.support.ResourcePatternResolver#CLASSPATH_ALL_URL_PREFIX . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SpringResourcesScanner.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public List<ResourceAdapter<?>> scan() {
	String locationPattern = null;
	if (StringUtils.isBlank(baseDir)) {
		locationPattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX;
	} else {
		locationPattern = FileUtils.convertDir(baseDir);
	}
	
	String sqldirPath = locationPattern+"/**/*"+postfix;
	Resource[] sqlfileArray;
	try {
		sqlfileArray = resourcePatternResolver.getResources(sqldirPath);
	} catch (IOException e) {
		throw new BaseException("scan resource error, dir: " + baseDir + ", postfix: " + postfix, e);
	}
	return Stream.of(sqlfileArray)
					.map(f->new SpringResourceAdapterImpl(f, postfix))
					.collect(Collectors.toList());
}
 
Example 2
Source File: CustomTagAnnotations.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Finds all the classes which have a BeanTag or BeanTags annotation
 *
 * @param basePackage the package to start in
 * @return classes which have BeanTag or BeanTags annotation
 * @throws IOException
 * @throws ClassNotFoundException
 */
protected static List<Class<?>> findTagClasses(String basePackage) throws IOException, ClassNotFoundException {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

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

    String resolvedBasePackage = ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(
            basePackage));
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            resolvedBasePackage + "/" + "**/*.class";

    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (metadataReader != null && isBeanTag(metadataReader)) {
                classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            }
        }
    }

    return classes;
}
 
Example 3
Source File: CsvReportEntitiesMapping.java    From aw-reporting with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the beans classes that are annotated with {@code CsvReport} and extends the
 * {@code Report} base class.
 *
 * @param basePackage the package to be scanned.
 * @return the list of classes that match the requirements to be a report bean.
 */
private List<Class<? extends Report>> findReportBeans(String basePackage) throws IOException,
    ClassNotFoundException {
  ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
  MetadataReaderFactory metadataReaderFactory =
      new CachingMetadataReaderFactory(resourcePatternResolver);
  String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
      + resolveBasePackage(basePackage) + "/" + "**/*.class";
  Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);

  List<Class<? extends Report>> candidates = new ArrayList<Class<? extends Report>>();
  for (Resource resource : resources) {
    addCandidateIfApplicable(resource, metadataReaderFactory, candidates);
  }

  return candidates;
}
 
Example 4
Source File: ContextSingletonBeanFactoryLocator.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an instance which uses the the specified selector, as the name of the
 * definition file(s). In the case of a name with a Spring "classpath*:" prefix,
 * or with no prefix, which is treated the same, the current thread's context class
 * loader's {@code getResources} method will be called with this value to get
 * all resources having that name. These resources will then be combined to form a
 * definition. In the case where the name uses a Spring "classpath:" prefix, or
 * a standard URL prefix, then only one resource file will be loaded as the
 * definition.
 * @param selector the location of the resource(s) which will be read and
 * combined to form the definition for the BeanFactoryLocator instance.
 * Any such files must form a valid ApplicationContext definition.
 * @return the corresponding BeanFactoryLocator instance
 * @throws BeansException in case of factory loading failure
 */
public static BeanFactoryLocator getInstance(String selector) throws BeansException {
	String resourceLocation = selector;
	if (resourceLocation == null) {
		resourceLocation = DEFAULT_RESOURCE_LOCATION;
	}

	// For backwards compatibility, we prepend "classpath*:" to the selector name if there
	// is no other prefix (i.e. "classpath*:", "classpath:", or some URL prefix).
	if (!ResourcePatternUtils.isUrl(resourceLocation)) {
		resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation;
	}

	synchronized (instances) {
		if (logger.isTraceEnabled()) {
			logger.trace("ContextSingletonBeanFactoryLocator.getInstance(): instances.hashCode=" +
					instances.hashCode() + ", instances=" + instances);
		}
		BeanFactoryLocator bfl = instances.get(resourceLocation);
		if (bfl == null) {
			bfl = new ContextSingletonBeanFactoryLocator(resourceLocation);
			instances.put(resourceLocation, bfl);
		}
		return bfl;
	}
}
 
Example 5
Source File: SingletonBeanFactoryLocator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an instance which uses the specified selector, as the name of the
 * definition file(s). In the case of a name with a Spring 'classpath*:' prefix,
 * or with no prefix, which is treated the same, the current thread context
 * ClassLoader's {@code getResources} method will be called with this value
 * to get all resources having that name. These resources will then be combined to
 * form a definition. In the case where the name uses a Spring 'classpath:' prefix,
 * or a standard URL prefix, then only one resource file will be loaded as the
 * definition.
 * @param selector the name of the resource(s) which will be read and
 * combined to form the definition for the BeanFactoryLocator instance.
 * Any such files must form a valid BeanFactory definition.
 * @return the corresponding BeanFactoryLocator instance
 * @throws BeansException in case of factory loading failure
 */
public static BeanFactoryLocator getInstance(String selector) throws BeansException {
	String resourceLocation = selector;
	if (resourceLocation == null) {
		resourceLocation = DEFAULT_RESOURCE_LOCATION;
	}

	// For backwards compatibility, we prepend 'classpath*:' to the selector name if there
	// is no other prefix (i.e. classpath*:, classpath:, or some URL prefix.
	if (!ResourcePatternUtils.isUrl(resourceLocation)) {
		resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation;
	}

	synchronized (instances) {
		if (logger.isTraceEnabled()) {
			logger.trace("SingletonBeanFactoryLocator.getInstance(): instances.hashCode=" +
					instances.hashCode() + ", instances=" + instances);
		}
		BeanFactoryLocator bfl = instances.get(resourceLocation);
		if (bfl == null) {
			bfl = new SingletonBeanFactoryLocator(resourceLocation);
			instances.put(resourceLocation, bfl);
		}
		return bfl;
	}
}
 
Example 6
Source File: SingletonBeanFactoryLocator.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an instance which uses the the specified selector, as the name of the
 * definition file(s). In the case of a name with a Spring 'classpath*:' prefix,
 * or with no prefix, which is treated the same, the current thread context
 * ClassLoader's {@code getResources} method will be called with this value
 * to get all resources having that name. These resources will then be combined to
 * form a definition. In the case where the name uses a Spring 'classpath:' prefix,
 * or a standard URL prefix, then only one resource file will be loaded as the
 * definition.
 * @param selector the name of the resource(s) which will be read and
 * combined to form the definition for the BeanFactoryLocator instance.
 * Any such files must form a valid BeanFactory definition.
 * @return the corresponding BeanFactoryLocator instance
 * @throws BeansException in case of factory loading failure
 */
public static BeanFactoryLocator getInstance(String selector) throws BeansException {
	String resourceLocation = selector;
	if (resourceLocation == null) {
		resourceLocation = DEFAULT_RESOURCE_LOCATION;
	}

	// For backwards compatibility, we prepend 'classpath*:' to the selector name if there
	// is no other prefix (i.e. classpath*:, classpath:, or some URL prefix.
	if (!ResourcePatternUtils.isUrl(resourceLocation)) {
		resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation;
	}

	synchronized (instances) {
		if (logger.isTraceEnabled()) {
			logger.trace("SingletonBeanFactoryLocator.getInstance(): instances.hashCode=" +
					instances.hashCode() + ", instances=" + instances);
		}
		BeanFactoryLocator bfl = instances.get(resourceLocation);
		if (bfl == null) {
			bfl = new SingletonBeanFactoryLocator(resourceLocation);
			instances.put(resourceLocation, bfl);
		}
		return bfl;
	}
}
 
Example 7
Source File: DataSourceAutoConfiguration.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Let typeAliasesPackage alias bean support wildcards.
 * 
 * @return
 */
private Class<?>[] getTypeAliases(PathMatchingResourcePatternResolver resolver) throws Exception {
	List<Class<?>> typeAliases = new ArrayList<>();

	// Define metadataReader
	MetadataReaderFactory metadataReaderFty = new CachingMetadataReaderFactory(resolver);

	for (String pkg : typeAliasesPackage.split(",")) {
		// Get location
		String location = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg)
				+ "**/*.class";
		// Get resources.
		Resource[] resources = resolver.getResources(location);
		if (resources != null) {
			for (Resource resource : resources) {
				if (resource.isReadable()) {
					MetadataReader metadataReader = metadataReaderFty.getMetadataReader(resource);
					typeAliases.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
				}
			}
		}
	}

	return typeAliases.toArray(new Class<?>[] {});
}
 
Example 8
Source File: AbstractDataBaseBean.java    From spring-boot-starter-dao with Apache License 2.0 6 votes vote down vote up
protected final AbstractBeanDefinition createSqlSessionFactoryBean(String dataSourceName, String mapperPackage,
		String typeAliasesPackage, Dialect dialect, Configuration configuration) {
	configuration.setDatabaseId(dataSourceName);
	BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(SqlSessionFactoryBean.class);
	bdb.addPropertyValue("configuration", configuration);
	bdb.addPropertyValue("failFast", true);
	bdb.addPropertyValue("typeAliases", this.saenTypeAliases(typeAliasesPackage));
	bdb.addPropertyReference("dataSource", dataSourceName);
	bdb.addPropertyValue("plugins", new Interceptor[] { new CustomPageInterceptor(dialect) });
	if (!StringUtils.isEmpty(mapperPackage)) {
		try {
			mapperPackage = new StandardEnvironment().resolveRequiredPlaceholders(mapperPackage);
			String mapperPackages = ClassUtils.convertClassNameToResourcePath(mapperPackage);
			String mapperPackagePath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPackages + "/*.xml";
			Resource[] resources = new PathMatchingResourcePatternResolver().getResources(mapperPackagePath);
			bdb.addPropertyValue("mapperLocations", resources);
		} catch (Exception e) {
			log.error("初始化失败", e);
			throw new RuntimeException( String.format("SqlSessionFactory 初始化失败  mapperPackage=%s", mapperPackage + ""));
		}
	}
	return bdb.getBeanDefinition();
}
 
Example 9
Source File: WicketDependencyVersionChecker.java    From wicket-spring-boot with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void detectWicketDependencyVersionMissmatch() throws IOException {
	String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +  DEFAULT_RESOURCE_PATTERN;
	Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
	
	List<MavenDependency> wicketMavenDependencies = collectWicketMavenDependencies( resources);
	String wicketCoreVersion = findWicketCoreVersion( wicketMavenDependencies );
	
	boolean versionMissmatchFound = false;
	List<MavenDependency> mismatchVersionDependencies = new ArrayList<>();
	for ( MavenDependency mavenDependency : wicketMavenDependencies ) {
		if(mavenDependency.groupId.equals( WICKET_CORE_GROUPID ) || mavenDependency.groupId.equals( WICKETSTUFF_GROUPID ) ) {
			if(!mavenDependency.version.equals( wicketCoreVersion )) {
				log.error( "########## INVALID WICKET VERSION DETECTED - CORE: {} - DEPENDENCY: {}", wicketCoreVersion,  mavenDependency);
				versionMissmatchFound = true;
				mismatchVersionDependencies.add( mavenDependency );
			}
		}
	}
	
	if(versionMissmatchFound && props.isThrowExceptionOnDependencyVersionMismatch()) {
		throw new WicketDependencyMismatchDetectedException( wicketCoreVersion, mismatchVersionDependencies );
	}
	
}
 
Example 10
Source File: ClassScanner.java    From kaif with Apache License 2.0 6 votes vote down vote up
public static List<Class> searchAnnotatedClasses(String basePackage, Class<?> annotation)
    throws IOException, ClassNotFoundException {
  ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
  MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(
      resourcePatternResolver);

  List<Class> candidates = new ArrayList<>();
  String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
      resolveBasePackage(basePackage) + "/" + "**/*.class";
  Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
  for (Resource resource : resources) {
    if (resource.isReadable()) {
      MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
      if (isCandidate(metadataReader, annotation)) {
        candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
      }
    }
  }
  return candidates;
}
 
Example 11
Source File: FreemarkerSqlTemplates.java    From spring-data-jpa-extra with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    Set<String> names = new HashSet<>();
    Set<EntityType<?>> entities = em.getMetamodel().getEntities();
    for (EntityType<?> entity : entities) {
        names.add(entity.getName());
    }

    String suffixPattern = "/**/*" + suffix;

    if (!names.isEmpty()) {
        String pattern;
        if (StringUtils.isNotBlank(templateBasePackage)) {
            pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    ClassUtils.convertClassNameToResourcePath(templateBasePackage) + suffixPattern;

            loadPatternResource(names, pattern);
        }
        if (StringUtils.isNotBlank(templateLocation)) {
            pattern = templateLocation.contains(suffix) ? templateLocation : templateLocation + suffixPattern;
            try {
                loadPatternResource(names, pattern);
            } catch (FileNotFoundException e) {
                if ("classpath:/sqls".equals(templateLocation)) {
                    //warn: default value
                    logger.warn("templateLocation[" + templateLocation + "] not exist!");
                    logger.warn(e.getMessage());
                } else {
                    //throw: custom value.
                    throw e;
                }
            }
        }
    }
}
 
Example 12
Source File: TopicConsumerSpringProvider.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
private void scanAndRegisterAnnotationTopics(String[] scanBasePackages){
   	String RESOURCE_PATTERN = "/**/*.class";
   	
   	ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
   	for (String scanBasePackage : scanBasePackages) {
   		logger.info(">>begin scan package [{}] with Annotation[ConsumerHandler] MessageHanlder ",scanBasePackage);
   		try {
               String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(scanBasePackage)
                       + RESOURCE_PATTERN;
               org.springframework.core.io.Resource[] resources = resourcePatternResolver.getResources(pattern);
               MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
               for (org.springframework.core.io.Resource resource : resources) {
                   if (resource.isReadable()) {
                       MetadataReader reader = readerFactory.getMetadataReader(resource);
                       String className = reader.getClassMetadata().getClassName();
                       Class<?> clazz = Class.forName(className);
                       if(clazz.isAnnotationPresent(ConsumerHandler.class)){
                       	ConsumerHandler annotation = clazz.getAnnotation(ConsumerHandler.class);
                       	MessageHandler hander = (MessageHandler) context.getBean(clazz);
                       	if(!topicHandlers.containsKey(annotation.topic())){                        		
                       		topicHandlers.put(annotation.topic(), hander);
                       		logger.info("register new MessageHandler:{}-{}",annotation.topic(),clazz.getName());
                       	}
                       }
                   }
               }
               logger.info("<<scan package["+scanBasePackage+"] finished!");
           } catch (Exception e) {
           	if(e instanceof org.springframework.beans.factory.NoSuchBeanDefinitionException){
           		throw (org.springframework.beans.factory.NoSuchBeanDefinitionException)e;
           	}
           	logger.error("<<scan package["+scanBasePackage+"] error", e);
           }
	}
   	
}
 
Example 13
Source File: SchemaLoader.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Resource getSchema(String schemaName) throws IOException {
  if (schemaName.contains("/")) {
    schemaName = schemaName.substring(schemaName.lastIndexOf('/'));
  }

  ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
  String searchPattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/**/" + schemaName;
  Resource[] resources = resourcePatternResolver.getResources(searchPattern);

  if (resources.length == 0) {
    throw new RuntimeException("Could not find schema [" + schemaName + "]");
  }

  return resources[0];
}
 
Example 14
Source File: ResourceXmlParser.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private String[] getResources(String packageName) {
    try {
        // 搜索资源
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(packageName)) + "/" + DEFAULT_RESOURCE_PATTERN;
        Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
        // 提取资源
        Set<String> names = new HashSet<String>();
        String name = ResourceConfiguration.class.getName();
        for (Resource resource : resources) {
            if (!resource.isReadable()) {
                continue;
            }
            // 判断是否静态资源
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
            if (!annotationMetadata.hasAnnotation(name)) {
                continue;
            }
            ClassMetadata classMetadata = metadataReader.getClassMetadata();
            names.add(classMetadata.getClassName());
        }
        return names.toArray(new String[0]);
    } catch (IOException exception) {
        String message = "无法获取资源";
        logger.error(message, exception);
        throw new StorageException(message, exception);
    }
}
 
Example 15
Source File: PackagesSqlSessionFactoryBean.java    From spring-boot-api-project-seed with Apache License 2.0 5 votes vote down vote up
@Override
public void setTypeAliasesPackage(String typeAliasesPackage) {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
    typeAliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            ClassUtils.convertClassNameToResourcePath(typeAliasesPackage) + "/" + DEFAULT_RESOURCE_PATTERN;

    //将加载多个绝对匹配的所有Resource
    //将首先通过ClassLoader.getResource("META-INF")加载非模式路径部分
    //然后进行遍历模式匹配
    try {
        List<String> result = new ArrayList<>();
        Resource[] resources = resolver.getResources(typeAliasesPackage);
        if (resources.length > 0) {
            MetadataReader metadataReader = null;
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
                }
            }
        }
        if (!result.isEmpty()) {
            super.setTypeAliasesPackage(StringUtils.join(result.toArray(), ","));
        } else {
            String msg = String.format("参数typeAliasesPackage:%s,未找到任何包", typeAliasesPackage);
            logger.warn(msg);
        }
    } catch (IOException | ClassNotFoundException e) {
        logger.info(e.getMessage());
    }
}
 
Example 16
Source File: EnumDictHandlerRegister.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("all")
public static void register(String[] packages) {
    if (typeHandlerRegistry == null) {
        log.error("请在spring容器初始化后再调用此方法!");
        return;
    }
    for (String basePackage : packages) {
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                ClassUtils.convertClassNameToResourcePath(basePackage) + "/**/*.class";
        try {
            Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
            for (Resource resource : resources) {
                try {
                    MetadataReader reader = metadataReaderFactory.getMetadataReader(resource);
                    Class enumType = Class.forName(reader.getClassMetadata().getClassName());
                    if (enumType.isEnum() && EnumDict.class.isAssignableFrom(enumType)) {
                        log.debug("register enum dict:{}", enumType);
                        DefaultDictDefineRepository.registerDefine(DefaultDictDefineRepository.parseEnumDict(enumType));
                        //注册枚举类型
                        typeHandlerRegistry.register(enumType, new EnumDictHandler(enumType));

                        //注册枚举数组类型
                        typeHandlerRegistry.register(Array.newInstance(enumType, 0).getClass(), new EnumDictArrayHandler(enumType));
                    }
                } catch (Exception | Error ignore) {

                }
            }
        } catch (IOException e) {
            log.warn("register enum dict error", e);
        }
    }
}
 
Example 17
Source File: AppPropertiesLocator.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected Set<Class> findConfigInterfaces() {
    if (interfacesCache == null) {
        synchronized (this) {
            if (interfacesCache == null) {
                log.trace("Locating config interfaces");
                Set<String> cache = new HashSet<>();
                for (String rootPackage : metadata.getRootPackages()) {
                    String packagePrefix = rootPackage.replace(".", "/") + "/**/*.class";
                    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + packagePrefix;
                    Resource[] resources;
                    try {
                        resources = resourcePatternResolver.getResources(packageSearchPath);
                        for (Resource resource : resources) {
                            if (resource.isReadable()) {
                                MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                                ClassMetadata classMetadata = metadataReader.getClassMetadata();
                                if (classMetadata.isInterface()) {
                                    for (String intf : classMetadata.getInterfaceNames()) {
                                        if (Config.class.getName().equals(intf)) {
                                            cache.add(classMetadata.getClassName());
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("Error searching for Config interfaces", e);
                    }
                }
                log.trace("Found config interfaces: {}", cache);
                interfacesCache = cache;
            }
        }
    }
    return interfacesCache.stream()
            .map(ReflectionHelper::getClass)
            .collect(Collectors.toSet());
}
 
Example 18
Source File: ClassPathScanningCandidateComponentProvider.java    From thinking-in-spring-boot-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Scan the class path for candidate components.
 * @param basePackage the package to check for annotated classes
 * @return a corresponding Set of autodetected bean definitions
 */
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
    Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();
    try {
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                resolveBasePackage(basePackage) + "/" + this.resourcePattern;
        Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
        boolean traceEnabled = logger.isTraceEnabled();
        boolean debugEnabled = logger.isDebugEnabled();
        for (int i = 0; i < resources.length; i++) {
            Resource resource = resources[i];
            if (traceEnabled) {
                logger.trace("Scanning " + resource);
            }
            if (resource.isReadable()) {
                MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
                if (isCandidateComponent(metadataReader)) {
                    ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
                    sbd.setResource(resource);
                    sbd.setSource(resource);
                    if (isCandidateComponent(sbd)) {
                        if (debugEnabled) {
                            logger.debug("Identified candidate component class: " + resource);
                        }
                        candidates.add(sbd);
                    }
                    else {
                        if (debugEnabled) {
                            logger.debug("Ignored because not a concrete top-level class: " + resource);
                        }
                    }
                }
                else {
                    if (traceEnabled) {
                        logger.trace("Ignored because not matching any filter: " + resource);
                    }
                }
            }
            else {
                if (traceEnabled) {
                    logger.trace("Ignored because not readable: " + resource);
                }
            }
        }
    }
    catch (IOException ex) {
        throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
    }
    return candidates;
}
 
Example 19
Source File: DefaultPersistenceUnitManager.java    From java-technology-stack with MIT License 4 votes vote down vote up
private void scanPackage(SpringPersistenceUnitInfo scannedUnit, String pkg) {
	if (this.componentsIndex != null) {
		Set<String> candidates = new HashSet<>();
		for (AnnotationTypeFilter filter : entityTypeFilters) {
			candidates.addAll(this.componentsIndex.getCandidateTypes(pkg, filter.getAnnotationType().getName()));
		}
		candidates.forEach(scannedUnit::addManagedClassName);
		Set<String> managedPackages = this.componentsIndex.getCandidateTypes(pkg, "package-info");
		managedPackages.forEach(scannedUnit::addManagedPackage);
		return;
	}

	try {
		String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
				ClassUtils.convertClassNameToResourcePath(pkg) + CLASS_RESOURCE_PATTERN;
		Resource[] resources = this.resourcePatternResolver.getResources(pattern);
		MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
		for (Resource resource : resources) {
			if (resource.isReadable()) {
				MetadataReader reader = readerFactory.getMetadataReader(resource);
				String className = reader.getClassMetadata().getClassName();
				if (matchesFilter(reader, readerFactory)) {
					scannedUnit.addManagedClassName(className);
					if (scannedUnit.getPersistenceUnitRootUrl() == null) {
						URL url = resource.getURL();
						if (ResourceUtils.isJarURL(url)) {
							scannedUnit.setPersistenceUnitRootUrl(ResourceUtils.extractJarFileURL(url));
						}
					}
				}
				else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
					scannedUnit.addManagedPackage(
							className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
				}
			}
		}
	}
	catch (IOException ex) {
		throw new PersistenceException("Failed to scan classpath for unlisted entity classes", ex);
	}
}
 
Example 20
Source File: DefaultPersistenceUnitManager.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private void scanPackage(SpringPersistenceUnitInfo scannedUnit, String pkg) {
	if (this.componentsIndex != null) {
		Set<String> candidates = new HashSet<>();
		for (AnnotationTypeFilter filter : entityTypeFilters) {
			candidates.addAll(this.componentsIndex.getCandidateTypes(pkg, filter.getAnnotationType().getName()));
		}
		candidates.forEach(scannedUnit::addManagedClassName);
		Set<String> managedPackages = this.componentsIndex.getCandidateTypes(pkg, "package-info");
		managedPackages.forEach(scannedUnit::addManagedPackage);
		return;
	}

	try {
		String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
				ClassUtils.convertClassNameToResourcePath(pkg) + CLASS_RESOURCE_PATTERN;
		Resource[] resources = this.resourcePatternResolver.getResources(pattern);
		MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
		for (Resource resource : resources) {
			if (resource.isReadable()) {
				MetadataReader reader = readerFactory.getMetadataReader(resource);
				String className = reader.getClassMetadata().getClassName();
				if (matchesFilter(reader, readerFactory)) {
					scannedUnit.addManagedClassName(className);
					if (scannedUnit.getPersistenceUnitRootUrl() == null) {
						URL url = resource.getURL();
						if (ResourceUtils.isJarURL(url)) {
							scannedUnit.setPersistenceUnitRootUrl(ResourceUtils.extractJarFileURL(url));
						}
					}
				}
				else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
					scannedUnit.addManagedPackage(
							className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
				}
			}
		}
	}
	catch (IOException ex) {
		throw new PersistenceException("Failed to scan classpath for unlisted entity classes", ex);
	}
}