Java Code Examples for org.springframework.core.type.AnnotationMetadata#getAnnotationAttributes()

The following examples show how to use org.springframework.core.type.AnnotationMetadata#getAnnotationAttributes() . 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: PublicApiHttpClient.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String getEntityCollectionInfo(String className) throws IOException
{
    AnnotationMetadata annotationMetaData = getAnnotationMetadata(className);
    if (annotationMetaData.isConcrete() && annotationMetaData.isIndependent())
    {
        if (annotationMetaData.getAnnotationTypes().contains(EntityResource.class.getCanonicalName()))
        {
            Map<String, Object> attrs = annotationMetaData.getAnnotationAttributes(EntityResource.class.getName());
            return (String) attrs.get("name");
        }
        else
        {
            return null;
        }
    }
    else
    {
        throw new AlfrescoRuntimeException("");
    }
}
 
Example 2
Source File: AnnotationNacosPropertySourceBuilder.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
private List<Map<String, Object>> getAnnotationAttributesList(
		AnnotationMetadata metadata, String annotationType) {

	List<Map<String, Object>> annotationAttributesList = new LinkedList<Map<String, Object>>();

	if (NacosPropertySources.class.getName().equals(annotationType)) {
		Map<String, Object> annotationAttributes = metadata
				.getAnnotationAttributes(annotationType);
		if (annotationAttributes != null) {
			annotationAttributesList.addAll(Arrays.asList(
					(Map<String, Object>[]) annotationAttributes.get("value")));
		}
	}
	else if (com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.class
			.getName().equals(annotationType)) {
		annotationAttributesList
				.add(metadata.getAnnotationAttributes(annotationType));
	}
	return annotationAttributesList;
}
 
Example 3
Source File: ServerImportSelector.java    From thinking-in-spring-boot-samples with Apache License 2.0 6 votes vote down vote up
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
    // 读取 EnableServer 中的所有的属性方法,本例中仅有 type() 属性方法
    // 其中 key 为 属性方法的名称,value 为属性方法返回对象
    Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(EnableServer.class.getName());
    // 获取名为"type" 的属相方法,并且强制转化成 Server.Type 类型
    Server.Type type = (Server.Type) annotationAttributes.get("type");
    // 导入的类名称数组
    String[] importClassNames = new String[0];
    switch (type) {
        case HTTP: // 当设置 HTTP 服务器类型时,返回 HttpServer 组件
            importClassNames = new String[]{HttpServer.class.getName()};
            break;
        case FTP: //  当设置 FTP  服务器类型时,返回 FtpServer  组件
            importClassNames = new String[]{FtpServer.class.getName()};
            break;
    }
    return importClassNames;
}
 
Example 4
Source File: GrpcAutoConfiguration.java    From spring-boot-starter-grpc with MIT License 6 votes vote down vote up
/**
 * 包扫描
 */
private Set<BeanDefinition> scanPackages(AnnotationMetadata importingClassMetadata, ClassPathBeanDefinitionScanner scanner) {
    List<String> packages = new ArrayList<>();
    Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(GrpcServiceScan.class.getCanonicalName());
    if (annotationAttributes != null) {
        String[] basePackages = (String[]) annotationAttributes.get("packages");
        if (basePackages.length > 0) {
            packages.addAll(Arrays.asList(basePackages));
        }
    }
    Set<BeanDefinition> beanDefinitions = new HashSet<>();
    if (CollectionUtils.isEmpty(packages)) {
        return beanDefinitions;
    }
    packages.forEach(pack -> beanDefinitions.addAll(scanner.findCandidateComponents(pack)));
    return beanDefinitions;
}
 
Example 5
Source File: KeyValueRepositoryConfigurationExtension.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
/**
 * Detects the query creator type to be used for the factory to set. Will lookup a {@link QueryCreatorType} annotation
 * on the {@code @Enable}-annotation or use {@link SpelQueryCreator} if not found.
 *
 * @param config must not be {@literal null}.
 * @return
 */
private static Class<?> getQueryCreatorType(AnnotationRepositoryConfigurationSource config) {

	AnnotationMetadata metadata = config.getEnableAnnotationMetadata();

	Map<String, Object> queryCreatorAnnotationAttributes = metadata
			.getAnnotationAttributes(QueryCreatorType.class.getName());

	if (CollectionUtils.isEmpty(queryCreatorAnnotationAttributes)) {
		return SpelQueryCreator.class;
	}

	AnnotationAttributes queryCreatorAttributes = new AnnotationAttributes(queryCreatorAnnotationAttributes);
	return queryCreatorAttributes.getClass("value");
}
 
Example 6
Source File: MBeanExportConfiguration.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
	Map<String, Object> map = importMetadata.getAnnotationAttributes(EnableMBeanExport.class.getName());
	this.enableMBeanExport = AnnotationAttributes.fromMap(map);
	if (this.enableMBeanExport == null) {
		throw new IllegalArgumentException(
				"@EnableMBeanExport is not present on importing class " + importMetadata.getClassName());
	}
}
 
Example 7
Source File: ChoerodonRedisHttpSessionConfiguration.java    From oauth-server with Apache License 2.0 5 votes vote down vote up
public void setImportMetadata(AnnotationMetadata importMetadata) {
    Map<String, Object> enableAttrMap = importMetadata.getAnnotationAttributes(EnableRedisHttpSession.class.getName());
    AnnotationAttributes enableAttrs = AnnotationAttributes.fromMap(enableAttrMap);
    this.maxInactiveIntervalInSeconds = enableAttrs.getNumber("maxInactiveIntervalInSeconds");
    String redisNamespaceValue = enableAttrs.getString("redisNamespace");
    if (StringUtils.hasText(redisNamespaceValue)) {
        this.redisNamespace = this.embeddedValueResolver.resolveStringValue(redisNamespaceValue);
    }

    this.redisFlushMode = enableAttrs.getEnum("redisFlushMode");
}
 
Example 8
Source File: NettyRpcRegistrar.java    From BootNettyRpc with Apache License 2.0 5 votes vote down vote up
protected Set<String> getBasePackages(AnnotationMetadata importingClassMetadata) {
    Map<String, Object> attributes = importingClassMetadata.getAnnotationAttributes( EnableNettyRpc.class.getCanonicalName() );

    Set<String> basePackages = new HashSet<>();
    for (String pkg : (String[]) attributes.get( "basePackages" )) {
        if (StringUtils.hasText( pkg )) {
            basePackages.add( pkg );
        }
    }

    if (basePackages.isEmpty()) {
        basePackages.add( ClassUtils.getPackageName( importingClassMetadata.getClassName() ) );
    }
    return basePackages;
}
 
Example 9
Source File: KeyValueRepositoryConfigurationExtension.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
/**
 * Detects the query creator type to be used for the factory to set. Will lookup a {@link QueryCreatorType} annotation
 * on the {@code @Enable}-annotation or use {@link SpelQueryCreator} if not found.
 *
 * @param config
 * @return
 */
private static Class<?> getQueryType(AnnotationRepositoryConfigurationSource config) {

	AnnotationMetadata metadata = config.getEnableAnnotationMetadata();

	Map<String, Object> queryCreatorAnnotationAttributes = metadata
			.getAnnotationAttributes(QueryCreatorType.class.getName());

	if (queryCreatorAnnotationAttributes == null) {
		return KeyValuePartTreeQuery.class;
	}

	AnnotationAttributes queryCreatorAttributes = new AnnotationAttributes(queryCreatorAnnotationAttributes);
	return queryCreatorAttributes.getClass("repositoryQueryType");
}
 
Example 10
Source File: ExecutionContextPropagationImport.java    From spring-cloud-ribbon-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String[] selectImports(AnnotationMetadata metadata) {
    List<String> imports = new ArrayList<>();
    Map<String, Object> attributes = metadata.getAnnotationAttributes(EnableContextPropagation.class.getName(), true);
    if (attributes != null) {
        ATTRIBUTES.forEach(x -> importStrategy(imports, attributes, x));
    }
    return imports.toArray(new String[imports.size()]);
}
 
Example 11
Source File: CustomBeanNameGenerator.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
	AnnotationMetadata amd = annotatedDef.getMetadata();
	Set<String> types = amd.getAnnotationTypes();
	String beanName = null;
	for (String type : types) {
		Map<String, Object> attributes = amd.getAnnotationAttributes(type);
		if (isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) {
			String value = null;
			if (PermissionForRight.class.getName().equals(type)) {
				Right right = (Right)attributes.get("value");
				value = "permission" + right.name();
			} else if (GwtRpcImplements.class.getName().equals(type)) {
				Class<?> requestClass = (Class<?>)attributes.get("value");
				value = requestClass.getName();
			} else if (GwtRpcLogging.class.getName().equals(type)) {
				continue;
			} else {
				value = (String) attributes.get("value");
			}
			if (StringUtils.hasLength(value)) {
				if (beanName != null && !value.equals(beanName)) {
					throw new IllegalStateException("Stereotype annotations suggest inconsistent " +
							"component names: '" + beanName + "' versus '" + value + "'");
				}
				beanName = value;
			}
		}
	}
	return beanName;
}
 
Example 12
Source File: VaultPropertySourceRegistrar.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static Set<AnnotationAttributes> attributesForRepeatable(AnnotationMetadata metadata, String containerClassName,
		String annotationClassName) {

	Set<AnnotationAttributes> result = new LinkedHashSet<>();
	addAttributesIfNotNull(result, metadata.getAnnotationAttributes(annotationClassName, false));

	Map<String, Object> container = metadata.getAnnotationAttributes(containerClassName, false);
	if (container != null && container.containsKey("value")) {
		for (Map<String, Object> containedAttributes : (Map<String, Object>[]) container.get("value")) {
			addAttributesIfNotNull(result, containedAttributes);
		}
	}
	return Collections.unmodifiableSet(result);
}
 
Example 13
Source File: AnnotationConfigUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static Set<AnnotationAttributes> attributesForRepeatable(AnnotationMetadata metadata,
		String containerClassName, String annotationClassName) {

	Set<AnnotationAttributes> result = new LinkedHashSet<AnnotationAttributes>();
	addAttributesIfNotNull(result, metadata.getAnnotationAttributes(annotationClassName, false));

	Map<String, Object> container = metadata.getAnnotationAttributes(containerClassName, false);
	if (container != null && container.containsKey("value")) {
		for (Map<String, Object> containedAttributes : (Map<String, Object>[]) container.get("value")) {
			addAttributesIfNotNull(result, containedAttributes);
		}
	}
	return Collections.unmodifiableSet(result);
}
 
Example 14
Source File: WindowConfig.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected void registerPrimaryEditor(WindowInfo windowInfo, AnnotationMetadata annotationMetadata) {
    Map<String, Object> primaryEditorAnnotation =
            annotationMetadata.getAnnotationAttributes(PrimaryEditorScreen.class.getName());
    registerPrimaryEditor(windowInfo, primaryEditorAnnotation);
}
 
Example 15
Source File: ReyClientBeanRegistrar.java    From x7 with Apache License 2.0 4 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {

    String startClassName = annotationMetadata.getClassName();
    String basePackage = startClassName.substring(0, startClassName.lastIndexOf("."));

    Set<Class<?>> set = ClassFileReader.getClasses(basePackage);

    Map<String, Object> attributes = annotationMetadata.getAnnotationAttributes(EnableReyClient.class.getName());
    Object obj = attributes.get("basePackages");
    if (obj != null){
        String[] strs = (String[]) obj;
        for (String str : strs){
            Set<Class<?>> set1 = ClassFileReader.getClasses(str);
            set.addAll(set1);
        }
    }

    List<String> beanNameList = new ArrayList<>();

    for (Class clz : set) {
        ReyClient annotation = (ReyClient)clz.getAnnotation(ReyClient.class);
        if (annotation == null)
            continue;

        ClientParser.parse(clz,environment);

        String beanName = clz.getName();
        beanNameList.add(beanName);

        String backend = annotation.circuitBreaker();
        if (backend.equals(" ")){
            backend = null;
        }

        boolean retry = annotation.retry();

        if (!registry.containsBeanDefinition(beanName)) {

            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clz);
            GenericBeanDefinition definition = (GenericBeanDefinition) builder.getRawBeanDefinition();
            definition.getPropertyValues().add("objectType", clz);
            definition.getPropertyValues().add("backend",backend);
            definition.getPropertyValues().add("retry",retry);
            definition.setBeanClass(HttpClientProxy.class);
            definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);

            registry.registerBeanDefinition(beanName, definition);

        }
    }
}
 
Example 16
Source File: AlfrescoProxyRegistrar.java    From alfresco-mvc with Apache License 2.0 4 votes vote down vote up
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {

		Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!");
		Assert.notNull(registry, "BeanDefinitionRegistry must not be null!");

		boolean proxyBeanRegistered = false;
		for (String beanName : PackageAutoProxyCreator.DEFAULT_INTERCEPTORS) {
			if (registry.containsBeanDefinition(beanName)) {
				proxyBeanRegistered = true;
				break;
			}
		}

		if (!proxyBeanRegistered) {
			XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(registry);
			xmlReader.loadBeanDefinitions("classpath:com/gradecak/alfresco-mvc/alfresco-mvc-aop.xml");
		}

		// Guard against calls for sub-classes
		if (annotationMetadata.getAnnotationAttributes(EnableAlfrescoMvcAop.class.getName()) == null) {
			return;
		}

		this.attributes = new AnnotationAttributes(
				annotationMetadata.getAnnotationAttributes(EnableAlfrescoMvcAop.class.getName()));
		this.metadata = annotationMetadata;

		Iterable<String> basePackages = getBasePackages();
		for (String basePackage : basePackages) {
			registerOrEscalateApcAsRequired(PackageAutoProxyCreator.class, registry, null, basePackage);
		}

		// if (!registry.containsBeanDefinition(AUTOWIRED_PROCESSOR_BEAN_NAME)) {
		// RootBeanDefinition beanDefinition = new
		// RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
		// beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		// registry.registerBeanDefinition(AUTOWIRED_PROCESSOR_BEAN_NAME,
		// beanDefinition);
		// }

		// if (!registry.containsBeanDefinition(CONFIGURATION_PROCESSOR_BEAN_NAME)) {
		// RootBeanDefinition beanDefinition = new
		// RootBeanDefinition(ConfigurationClassPostProcessor.class);
		// beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		// registry.registerBeanDefinition(CONFIGURATION_PROCESSOR_BEAN_NAME,
		// beanDefinition);
		// }
	}
 
Example 17
Source File: Java110ListenerDiscoveryRegistrar.java    From MicroCommunity with Apache License 2.0 4 votes vote down vote up
/**
 * 注册侦听
 * @param metadata
 * @param registry
 */
public void registerListener(AnnotationMetadata metadata,
                             BeanDefinitionRegistry registry) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    ClassPathScanningCandidateComponentProvider scanner = getScanner();
    scanner.setResourceLoader(this.resourceLoader);
    Set<String> basePackages;
    Map<String, Object> attrs = metadata
            .getAnnotationAttributes(Java110ListenerDiscovery.class.getName());

    Object listenerPublishClassObj =  attrs.get("listenerPublishClass");

    Assert.notNull(listenerPublishClassObj,"Java110ListenerDiscovery 没有配置 listenerPublishClass 属性");

    Class<?> listenerPublishClass = (Class<?>) listenerPublishClassObj;

    AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
            Java110Listener.class);

    scanner.addIncludeFilter(annotationTypeFilter);
    basePackages = getBasePackages(metadata);

    for (String basePackage : basePackages) {
        Set<BeanDefinition> candidateComponents = scanner
                .findCandidateComponents(basePackage);
        for (BeanDefinition candidateComponent : candidateComponents) {
            if (candidateComponent instanceof AnnotatedBeanDefinition) {
                // verify annotated class is an interface
                AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
                AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();


                Map<String, Object> attributes = annotationMetadata
                        .getAnnotationAttributes(
                                Java110Listener.class.getCanonicalName());

                String beanName = getListenerName(attributes,beanDefinition);

                /*BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(beanDefinition, beanName);
                BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);*/
                Method method = listenerPublishClass.getMethod("addListener",String.class);
                method.invoke(null,beanName);
            }
        }
    }
}
 
Example 18
Source File: SDGeneratorManager.java    From spring-data-generator with MIT License 4 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
    Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!");
    Assert.notNull(beanDefinitionRegistry, "BeanDefinitionRegistry must not be null!");

    if(annotationMetadata.getAnnotationAttributes(SDGenerator.class.getName()) != null) {

        AnnotationAttributes attributes = new AnnotationAttributes(annotationMetadata.getAnnotationAttributes(SDGenerator.class.getName()));

        String repositoryPackage = attributes.getString("repositoryPackage");
        String managerPackage = attributes.getString("managerPackage");

        if (!managerPackage.isEmpty() && repositoryPackage.isEmpty()) {
            SDLogger.error("Repositories must be generated before generating managers");
            return;
        }

        if (!repositoryPackage.isEmpty() || !managerPackage.isEmpty()){
            ScanningConfigurationSupport configurationSource = new ScanningConfigurationSupport(annotationMetadata, attributes, this.environment);

            Collection<BeanDefinition> candidates = configurationSource.getCandidates(resourceLoader);

            String absolutePath = GeneratorUtils.getAbsolutePath();
            if (absolutePath == null) {
                SDLogger.addError("Could not define the absolute path!");
                return;
            }

            if (!repositoryPackage.isEmpty()){

                String repositoriesPath = absolutePath + repositoryPackage.replace(".", "/");
                Set<String> additionalExtends = this.validateExtends(attributes.getClassArray("additionalExtends"));
                if (additionalExtends != null) {
                    RepositoryTemplateSupport repositoryTemplateSupport = new RepositoryTemplateSupport(attributes, additionalExtends);
                    repositoryTemplateSupport.initializeCreation(repositoriesPath, repositoryPackage, candidates, Iterables.toArray(configurationSource.getBasePackages(), String.class));
                }
            }

            if (!repositoryPackage.isEmpty() && !managerPackage.isEmpty()) {

                String managerPath = absolutePath + managerPackage.replace(".", "/");

                String repositoryPostfix = attributes.getString("repositoryPostfix");

                ManagerTemplateSupport managerTemplateSupport = new ManagerTemplateSupport(attributes, repositoryPackage, repositoryPostfix);
                managerTemplateSupport.initializeCreation(managerPath, managerPackage, candidates, Iterables.toArray(configurationSource.getBasePackages(), String.class));
            }

            SDLogger.printGeneratedTables(attributes.getBoolean("debug"));
        }

    }
}
 
Example 19
Source File: ConfigurationBeanBindingRegistrar.java    From spring-context-support with Apache License 2.0 3 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {

    Map<String, Object> attributes = metadata.getAnnotationAttributes(ENABLE_CONFIGURATION_BINDING_CLASS_NAME);

    registerConfigurationBeanDefinitions(attributes, registry);
}
 
Example 20
Source File: ConfigurationClassUtils.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Determine the order for the given configuration class metadata.
 * @param metadata the metadata of the annotated class
 * @return the {@code @Order} annotation value on the configuration class,
 * or {@code Ordered.LOWEST_PRECEDENCE} if none declared
 * @since 5.0
 */
@Nullable
public static Integer getOrder(AnnotationMetadata metadata) {
	Map<String, Object> orderAttributes = metadata.getAnnotationAttributes(Order.class.getName());
	return (orderAttributes != null ? ((Integer) orderAttributes.get(AnnotationUtils.VALUE)) : null);
}