private List<Class<?>> findMangoDaoClasses(String packages) { try { List<Class<?>> daos = new ArrayList<Class<?>>(); ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver); for (String locationPattern : getLocationPattern(packages)) { Resource[] rs = resourcePatternResolver.getResources(locationPattern); for (Resource r : rs) { MetadataReader reader = metadataReaderFactory.getMetadataReader(r); AnnotationMetadata annotationMD = reader.getAnnotationMetadata(); if (annotationMD.hasAnnotation(DB.class.getName())) { ClassMetadata clazzMD = reader.getClassMetadata(); daos.add(Class.forName(clazzMD.getClassName())); } } } return daos; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } }
protected List<String> getClasses(Resource[] resources) { List<String> classNames = new ArrayList<>(); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader metadataReader; try { metadataReader = metadataReaderFactory.getMetadataReader(resource); } catch (IOException e) { throw new RuntimeException("Unable to read metadata resource", e); } AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); if (annotationMetadata.isAnnotated(com.haulmont.chile.core.annotations.MetaClass.class.getName()) || annotationMetadata.isAnnotated(MappedSuperclass.class.getName()) || annotationMetadata.isAnnotated(Entity.class.getName())) { ClassMetadata classMetadata = metadataReader.getClassMetadata(); classNames.add(classMetadata.getClassName()); } } } return classNames; }
@Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata md) { String sourceClass = ""; if (md instanceof ClassMetadata) { sourceClass = ((ClassMetadata) md).getClassName(); } ConditionMessage.Builder message = ConditionMessage.forCondition("ZipkinSender", sourceClass); String property = context.getEnvironment() .getProperty("spring.zipkin.sender.type"); if (StringUtils.isEmpty(property)) { return ConditionOutcome.match(message.because("automatic sender type")); } String senderType = getType(((AnnotationMetadata) md).getClassName()); if (property.equals(senderType)) { return ConditionOutcome.match(message.because(property + " sender type")); } return ConditionOutcome.noMatch(message.because(property + " sender type")); }
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(applicationContext); DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory; String resolvedPath = resolvePackageToScan(); logger.debug("Scanning '{}' for JSON-RPC service interfaces.", resolvedPath); try { for (Resource resource : applicationContext.getResources(resolvedPath)) { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); ClassMetadata classMetadata = metadataReader.getClassMetadata(); AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); String jsonRpcPathAnnotation = JsonRpcService.class.getName(); if (annotationMetadata.isAnnotated(jsonRpcPathAnnotation)) { String className = classMetadata.getClassName(); String path = (String) annotationMetadata.getAnnotationAttributes(jsonRpcPathAnnotation).get("value"); logger.debug("Found JSON-RPC service to proxy [{}] on path '{}'.", className, path); registerJsonProxyBean(defaultListableBeanFactory, className, path); } } } } catch (IOException e) { throw new IllegalStateException(format("Cannot scan package '%s' for classes.", resolvedPath), e); } }
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(applicationContext); DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory; String resolvedPath = resolvePackageToScan(); LOG.debug(format("Scanning '%s' for JSON-RPC service interfaces.", resolvedPath)); try { for (Resource resource : applicationContext.getResources(resolvedPath)) { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); ClassMetadata classMetadata = metadataReader.getClassMetadata(); AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); String jsonRpcPathAnnotation = JsonRpcService.class.getName(); if (annotationMetadata.isAnnotated(jsonRpcPathAnnotation)) { String className = classMetadata.getClassName(); String path = (String) annotationMetadata.getAnnotationAttributes(jsonRpcPathAnnotation).get("value"); boolean useNamedParams = (Boolean) annotationMetadata.getAnnotationAttributes(jsonRpcPathAnnotation).get("useNamedParams"); LOG.debug(format("Found JSON-RPC service to proxy [%s] on path '%s'.", className, path)); registerJsonProxyBean(dlbf, className, path, useNamedParams); } } } } catch (IOException e) { throw new RuntimeException(format("Cannot scan package '%s' for classes.", resolvedPath), e); } }
/** * 获取所有满足条件的Class对应的className * * @param basePackage * 基本的包含class的包, 如: "com.ilivoo,com.xiaosan" * @return */ public String[] findInterestClassNames(String basePackage) { Set<ClassMetadata> classMetadata = findInterestClassMetadata(basePackage); List<String> list = new LinkedList<String>(); for (ClassMetadata metadata : classMetadata) { list.add(metadata.getClassName()); } return list.toArray(new String[0]); }
/** * 获取满足条件的所有的Class对象 * * @param basePackage * 基本的包含class的包, 如: "com.ilivoo,com.xiaosan" * @return */ public Class<?>[] findInterestClasses(String basePackage) { Set<ClassMetadata> classMetadata = findInterestClassMetadata(basePackage); List<Class<?>> list = new LinkedList<Class<?>>(); for (ClassMetadata metadata : classMetadata) { Class<?> clz = ClassUtils.getClassforName(metadata.getClassName(), true); list.add(clz); } return list.toArray(new Class[0]); }
/** * 获取满足条件的所有的Class对于的BeanDeifinition, 一般情况下用于某些BeanDefinition的List, Map, * Array类型的property * * @param basePackage * 基本的包含class的包, 如: "com.ilivoo,com.xiaosan" * @param registry * BeanDefinition的注册器, 一般情况下都是通过ParserContext.getRegistry()获取 * @return */ public BeanDefinition[] findInterestBeanDefinition(String basePackage, BeanDefinitionRegistry registry) { Set<ClassMetadata> classMetadatas = findInterestClassMetadata(basePackage); List<BeanDefinition> list = new LinkedList<BeanDefinition>(); for (ClassMetadata metadata : classMetadatas) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(metadata.getClassName()); BeanDefinition definition = builder.getBeanDefinition(); list.add(definition); } return list.toArray(new BeanDefinition[0]); }
/** * 获取满足条件的所有的ClassMetadata * * @param basePackage * 基本的包含class的包, 如: "com.ilivoo,com.xiaosan" * @return */ private Set<ClassMetadata> findInterestClassMetadata(String basePackage) { List<Resource> allResource = findInterestResources(basePackage); Set<ClassMetadata> interests = new LinkedHashSet<ClassMetadata>(); for (Resource resource : allResource) { log.trace("扫描资源: " + resource); if (resource.isReadable()) { try { MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource); if (this.isCandidateComponent(metadataReader)) { interests.add(metadataReader.getClassMetadata()); } else { log.trace("资源不匹配TypeFilter: " + resource); } } catch (Throwable ex) { throw new BeanDefinitionStoreException("无法读取资源类: " + resource, ex); } } else { log.trace("忽略不可读的资源 : " + resource); } } return interests; }
@Override protected boolean match(ClassMetadata metadata) { Assert.notNull(metadata, "获取的metadata为空"); String className = metadata.getClassName(); String[] names = className.split("\\."); String simpleName = names[names.length-1]; if(isPrefix&&simpleName.startsWith(pattern)){ return true; } if(simpleName.endsWith(pattern)){ return true; } return false; }
private static String getClassOrMethodName(AnnotatedTypeMetadata metadata) { if (metadata instanceof ClassMetadata) { ClassMetadata classMetadata = (ClassMetadata) metadata; return classMetadata.getClassName(); } MethodMetadata methodMetadata = (MethodMetadata) metadata; return methodMetadata.getDeclaringClassName() + "#" + methodMetadata.getMethodName(); }
@Override public ClassMetadata getClassMetadataFor(Class<?> clazz) { try { MetadataReader reader = new SimpleMetadataReaderFactory().getMetadataReader(clazz.getName()); return reader.getAnnotationMetadata(); } catch (IOException ex) { throw new IllegalStateException(ex); } }
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()); }
@Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { final ClassMetadata classMetadata = metadataReader.getClassMetadata(); try { final Class<?> clazz = Class.forName(classMetadata.getClassName()); final ServiceImplementation implementationAnnotation = AnnotationUtils.findAnnotation(clazz, ServiceImplementation.class); final Method[] methods = clazz.getMethods(); for (Method method : methods) { if (AnnotationUtils.getAnnotation(method, Call.class) != null && !Modifier.isNative(method.getModifiers())) { LOGGER.error( "Method '{}' in '{}' is annotated with @{} but not declared as native: code inside method will be ignored.", method.getName(), clazz.getName(), Call.class.getName()); } } final String[] interfaceNames = classMetadata.getInterfaceNames(); boolean hasMatch = false; for (String interfaceName : interfaceNames) { final Service annotation = Class.forName(interfaceName).getAnnotation(Service.class); if (annotation != null) { if (implementationAnnotation == null) { LOGGER.warn("Service '{}' is not annotated with @{}, and will not be exposed as REST service", classMetadata.getClassName(), ServiceImplementation.class.getName()); } hasMatch = true; break; } } return hasMatch; } catch (Throwable e) { // NOSONAR if (!LOGGER.isDebugEnabled()) { LOGGER.error("Unable to filter class {}.", classMetadata.getClassName()); } else { LOGGER.debug("Unable to filter class {}.", classMetadata.getClassName(), e); } } return false; }
/** * 获取指定包下的静态资源对象 * @param packageName 包名 * @return */ private String[] getResources(String packageName) { try { // 搜索资源 String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolveBasePackage(packageName) + "/" + DEFAULT_RESOURCE_PATTERN; Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath); // 提取资源 Set<String> result = new HashSet<String>(); String name = basesource.anno.Resource.class.getName(); for (Resource resource : resources) { if (!resource.isReadable()) { continue; } // 判断是否静态资源 MetadataReader metaReader = this.metadataReaderFactory.getMetadataReader(resource); AnnotationMetadata annoMeta = metaReader.getAnnotationMetadata(); if (!annoMeta.hasAnnotation(name)) { continue; } ClassMetadata clzMeta = metaReader.getClassMetadata(); result.add(clzMeta.getClassName()); } return result.toArray(new String[result.size()]); } catch (IOException e) { String message = "无法读取资源信息"; logger.error(message, e); throw new RuntimeException(message, e); } }
@Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { final ClassMetadata classMetadata = metadataReader.getClassMetadata(); try { final Class<?> clazz = Class.forName(classMetadata.getClassName()); return AnnotationUtils.findAnnotation(clazz, Action.class) != null; } catch (Throwable e) { // NOSONAR if (!LOGGER.isDebugEnabled()) { LOGGER.error("Unable to filter class {}.", classMetadata.getClassName()); } else { LOGGER.debug("Unable to filter class {}.", classMetadata.getClassName(), e); } } return false; }
@Override protected boolean match(ClassMetadata metadata) { boolean isPattern = isPatternPackage(metadata.getClassName()); return isPattern; }
@Override public ClassMetadata getClassMetadata() { return this.classMetadata; }
@Override protected boolean match(ClassMetadata metadata) { return this.pattern.matcher(metadata.getClassName()).matches(); }
public ClassMetadata getClassMetadata() { return this.classMetadata; }
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { // This method optimizes avoiding unnecessary creation of ClassReaders // as well as visiting over those readers. if (matchSelf(metadataReader)) { return true; } ClassMetadata metadata = metadataReader.getClassMetadata(); if (matchClassName(metadata.getClassName())) { return true; } if (!this.considerInherited) { return false; } if (metadata.hasSuperClass()) { // Optimization to avoid creating ClassReader for super class. Boolean superClassMatch = matchSuperClass(metadata.getSuperClassName()); if (superClassMatch != null) { if (superClassMatch.booleanValue()) { return true; } } else { // Need to read super class to determine a match... if (match(metadata.getSuperClassName(), metadataReaderFactory)) { return true; } } } if (!this.considerInterfaces) { return false; } for (String ifc : metadata.getInterfaceNames()) { // Optimization to avoid creating ClassReader for super class Boolean interfaceMatch = matchInterface(ifc); if (interfaceMatch != null) { if (interfaceMatch.booleanValue()) { return true; } } else { // Need to read interface to determine a match... if (match(ifc, metadataReaderFactory)) { return true; } } } return false; }
/** * Read basic class metadata for the underlying class. */ ClassMetadata getClassMetadata();
/** * Determine a match based on the given ClassMetadata object. * @param metadata the ClassMetadata object * @return whether this filter matches on the specified type */ protected abstract boolean match(ClassMetadata metadata);