org.springframework.core.type.classreading.MetadataReader Java Examples

The following examples show how to use org.springframework.core.type.classreading.MetadataReader. 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: AutoJsonRpcClientProxyCreator.java    From jsonrpc4j with MIT License 6 votes vote down vote up
@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);
	}
}
 
Example #2
Source File: BootstrapImportSelector.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
OrderedAnnotatedElement(MetadataReaderFactory metadataReaderFactory, String name)
		throws IOException {
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(name);
	AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
	Map<String, Object> attributes = metadata
			.getAnnotationAttributes(Order.class.getName());
	this.name = name;
	if (attributes != null && attributes.containsKey("value")) {
		this.value = (Integer) attributes.get("value");
		this.order = new Order() {
			@Override
			public Class<? extends Annotation> annotationType() {
				return Order.class;
			}

			@Override
			public int value() {
				return OrderedAnnotatedElement.this.value;
			}
		};
	}
}
 
Example #3
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 #4
Source File: ClassScaner.java    From oim-fx with MIT License 6 votes vote down vote up
public Set<Class<?>> doScan(String basePackage) {
	Set<Class<?>> classes = new HashSet<Class<?>>();
	try {
		String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + org.springframework.util.ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage)) + "/**/*.class";
		Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);

		for (int i = 0; i < resources.length; i++) {
			Resource resource = resources[i];
			if (resource.isReadable()) {
				MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
				if ((includeFilters.size() == 0 && excludeFilters.size() == 0) || matches(metadataReader)) {
					try {
						classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}

				}
			}
		}
	} catch (IOException ex) {
		throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
	}
	return classes;
}
 
Example #5
Source File: MangoDaoAutoCreator.java    From mango-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #6
Source File: AnnotationTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testNonAnnotatedClassDoesntMatch() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	String classUnderTest = "org.springframework.core.type.AnnotationTypeFilterTests$SomeNonCandidateClass";
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);

	AnnotationTypeFilter filter = new AnnotationTypeFilter(Component.class);
	assertFalse(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
 
Example #7
Source File: AnnotationTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testDirectAnnotationMatch() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	String classUnderTest = "org.springframework.core.type.AnnotationTypeFilterTests$SomeComponent";
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);

	AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class);
	assertTrue(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
 
Example #8
Source File: ClassPathJaxb2TypeScanner.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected boolean isJaxb2Class(MetadataReader reader, MetadataReaderFactory factory) throws IOException {
	for (TypeFilter filter : JAXB2_TYPE_FILTERS) {
		if (filter.match(reader, factory) && !reader.getClassMetadata().isInterface() ) {
			return true;
		}
	}
	return false;
}
 
Example #9
Source File: SpringletsWebMvcExcludeFilter.java    From springlets with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean defaultInclude(MetadataReader metadataReader,
    MetadataReaderFactory metadataReaderFactory) throws IOException {
  if (super.defaultInclude(metadataReader, metadataReaderFactory)) {
    return true;
  }
  for (Class<?> controller : this.annotation.controllers()) {
    if (isTypeOrAnnotated(metadataReader, metadataReaderFactory, controller)) {
      return true;
    }
  }
  return false;
}
 
Example #10
Source File: AssignableTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void directMatch() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	String classUnderTest = "org.springframework.core.type.AssignableTypeFilterTests$TestNonInheritingClass";
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);

	AssignableTypeFilter matchingFilter = new AssignableTypeFilter(TestNonInheritingClass.class);
	AssignableTypeFilter notMatchingFilter = new AssignableTypeFilter(TestInterface.class);
	assertFalse(notMatchingFilter.match(metadataReader, metadataReaderFactory));
	assertTrue(matchingFilter.match(metadataReader, metadataReaderFactory));
}
 
Example #11
Source File: LocalSessionFactoryBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Check whether any of the configured entity type filters matches
 * the current class descriptor contained in the metadata reader.
 */
private boolean matchesEntityTypeFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException {
	if (this.entityTypeFilters != null) {
		for (TypeFilter filter : this.entityTypeFilters) {
			if (filter.match(reader, readerFactory)) {
				return true;
			}
		}
	}
	return false;
}
 
Example #12
Source File: ConfigurationClassParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
public Class<?> loadClass() throws ClassNotFoundException {
	if (this.source instanceof Class) {
		return (Class<?>) this.source;
	}
	String className = ((MetadataReader) this.source).getClassMetadata().getClassName();
	return ClassUtils.forName(className, resourceLoader.getClassLoader());
}
 
Example #13
Source File: AnnotationTypeFilterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testNonInheritedAnnotationDoesNotMatch() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	String classUnderTest = "org.springframework.core.type.AnnotationTypeFilterTests$SomeSubclassOfSomeClassMarkedWithNonInheritedAnnotation";
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);

	AnnotationTypeFilter filter = new AnnotationTypeFilter(NonInheritedAnnotation.class);
	// Must fail as annotation isn't inherited
	assertFalse(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
 
Example #14
Source File: JaxbClassFilter.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> doWithCandidate(MetadataReader metadataReader, Resource clazz, int count) {
	if (!metadataReader.getAnnotationMetadata().hasAnnotation(XmlRootElement.class.getName()))
		return null;
	Class<?> cls = ReflectUtils.loadClass(metadataReader.getClassMetadata().getClassName());
	return cls;
}
 
Example #15
Source File: ConfigurationClass.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a new {@link ConfigurationClass} with the given name.
 * @param metadataReader reader used to parse the underlying {@link Class}
 * @param beanName must not be {@code null}
 * @see ConfigurationClass#ConfigurationClass(Class, ConfigurationClass)
 */
public ConfigurationClass(MetadataReader metadataReader, String beanName) {
	Assert.notNull(beanName, "Bean name must not be null");
	this.metadata = metadataReader.getAnnotationMetadata();
	this.resource = metadataReader.getResource();
	this.beanName = beanName;
}
 
Example #16
Source File: HandlerAnnotationFactoryBean.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
/**
 * 检查当前扫描到的Bean含有任何一个指定的注解标记
 * 
 * @param reader
 * @param readerFactory
 * @return
 * @throws IOException
 */
private boolean matchesEntityTypeFilter(MetadataReader reader,
		MetadataReaderFactory readerFactory) throws IOException {
	if (!this.typeFilters.isEmpty()) {
		for (TypeFilter filter : this.typeFilters) {
			if (filter.match(reader, readerFactory)) {
				return true;
			}
		}
	}
	return false;
}
 
Example #17
Source File: ConfigurationClassParser.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public Class<?> loadClass() throws ClassNotFoundException {
	if (this.source instanceof Class<?>) {
		return (Class<?>) this.source;
	}
	String className = ((MetadataReader) this.source).getClassMetadata().getClassName();
	return resourceLoader.getClassLoader().loadClass(className);
}
 
Example #18
Source File: CacheXmlParser.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 = CacheConfiguration.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 CacheConfigurationException(message, exception);
    }
}
 
Example #19
Source File: DefaultPersistenceUnitManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Check whether any of the configured entity type filters matches
 * the current class descriptor contained in the metadata reader.
 */
private boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException {
	for (TypeFilter filter : entityTypeFilters) {
		if (filter.match(reader, readerFactory)) {
			return true;
		}
	}
	return false;
}
 
Example #20
Source File: AnnotationScopeMetadataResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void customRequestScopeViaAsm() throws IOException {
	MetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory();
	MetadataReader reader = readerFactory.getMetadataReader(AnnotatedWithCustomRequestScope.class.getName());
	AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(reader.getAnnotationMetadata());
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd);
	assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata);
	assertEquals("request", scopeMetadata.getScopeName());
	assertEquals(NO, scopeMetadata.getScopedProxyMode());
}
 
Example #21
Source File: CmisRegistrar.java    From spring-content with Apache License 2.0 5 votes vote down vote up
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
		throws IOException {

	for (TypeFilter filter : delegates) {
		if (!filter.match(metadataReader, metadataReaderFactory)) {
			return false;
		}
	}

	return true;
}
 
Example #22
Source File: CachingMetadataReaderLeakTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignificantLoad() throws Exception {
	Assume.group(TestGroup.LONG_RUNNING);

	// the biggest public class in the JDK (>60k)
	URL url = getClass().getResource("/java/awt/Component.class");
	assertThat(url, notNullValue());

	// look at a LOT of items
	for (int i = 0; i < ITEMS_TO_LOAD; i++) {
		Resource resource = new UrlResource(url) {

			@Override
			public boolean equals(Object obj) {
				return (obj == this);
			}

			@Override
			public int hashCode() {
				return System.identityHashCode(this);
			}
		};

		MetadataReader reader = mrf.getMetadataReader(resource);
		assertThat(reader, notNullValue());
	}

	// useful for profiling to take snapshots
	// System.in.read();
}
 
Example #23
Source File: RpcInvokerAnnotationScanner.java    From hasting with MIT License 5 votes vote down vote up
public RpcInvokerAnnotationScanner(BeanDefinitionRegistry registry,Map<String,AbstractRpcClient> rpcClients) {
	super(registry,false);
	this.rpcClients = rpcClients;
	super.addIncludeFilter(new TypeFilter(){
		@Override
		public boolean match(MetadataReader metadataReader,MetadataReaderFactory metadataReaderFactory)throws IOException {
			String className = metadataReader.getClassMetadata().getClassName();
			return acceptClassName(className);
		}
	});
}
 
Example #24
Source File: AspectJTypeFilterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void assertNoMatch(String type, String typePattern) throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(type);

	AspectJTypeFilter filter = new AspectJTypeFilter(typePattern, getClass().getClassLoader());
	assertFalse(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(type);
}
 
Example #25
Source File: AspectJTypeFilter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
		throws IOException {

	String className = metadataReader.getClassMetadata().getClassName();
	ResolvedType resolvedType = this.world.resolve(className);
	return this.typePattern.matchesStatically(resolvedType);
}
 
Example #26
Source File: CustomTagAnnotations.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Returns true if the metadataReader representing the class has a BeanTag or BeanTags annotation
 *
 * @param metadataReader MetadataReader representing the class to analyze
 * @return true if BeanTag or BeanTags annotation is present
 */
protected static boolean isBeanTag(MetadataReader metadataReader) {
    try {
        Class<?> c = Class.forName(metadataReader.getClassMetadata().getClassName());
        if (c.getAnnotation(BeanTag.class) != null || c.getAnnotation(BeanTags.class) != null) {
            return true;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return false;
}
 
Example #27
Source File: UiControllerResourceMeta.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected String getControllerId(MetadataReader metadataReader) {
    Map<String, Object> uiControllerAnn =
            metadataReader.getAnnotationMetadata().getAnnotationAttributes(UiController.class.getName());

    String idAttr = null;
    String valueAttr = null;
    if (uiControllerAnn != null) {
        idAttr = (String) uiControllerAnn.get(UiController.ID_ATTRIBUTE);
        valueAttr = (String) uiControllerAnn.get(UiController.VALUE_ATTRIBUTE);
    }

    String className = metadataReader.getClassMetadata().getClassName();
    return UiDescriptorUtils.getInferredScreenId(idAttr, valueAttr, className);
}
 
Example #28
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 #29
Source File: AnnotationMetadataTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-11649
public void composedAnnotationWithMetaAnnotationsWithIdenticalAttributeNamesUsingAnnotationMetadataReadingVisitor() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(NamedComposedAnnotationClass.class.getName());
	AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
	assertMultipleAnnotationsWithIdenticalAttributeNames(metadata);
}
 
Example #30
Source File: AnnotationMetadataTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-11649
public void multipleAnnotationsWithIdenticalAttributeNamesUsingAnnotationMetadataReadingVisitor() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(NamedAnnotationsClass.class.getName());
	AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
	assertMultipleAnnotationsWithIdenticalAttributeNames(metadata);
}