Java Code Examples for org.springframework.core.annotation.AnnotationAttributes#getStringArray()

The following examples show how to use org.springframework.core.annotation.AnnotationAttributes#getStringArray() . 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: WebAdminComponentScanRegistrar.java    From wallride with Apache License 2.0 6 votes vote down vote up
private Set<String> getPackagesToScan(AnnotationMetadata metadata) {
	AnnotationAttributes attributes = AnnotationAttributes
			.fromMap(metadata.getAnnotationAttributes(WebAdminComponentScan.class.getName()));
	String[] value = attributes.getStringArray("value");
	String[] basePackages = attributes.getStringArray("basePackages");
	Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
	if (!ObjectUtils.isEmpty(value)) {
		Assert.state(ObjectUtils.isEmpty(basePackages),
				"@WebAdminComponentScan basePackages and value attributes are mutually exclusive");
	}
	Set<String> packagesToScan = new LinkedHashSet<String>();
	packagesToScan.addAll(Arrays.asList(value));
	packagesToScan.addAll(Arrays.asList(basePackages));
	for (Class<?> basePackageClass : basePackageClasses) {
		packagesToScan.add(ClassUtils.getPackageName(basePackageClass));
	}
	if (packagesToScan.isEmpty()) {
		return Collections.singleton(ClassUtils.getPackageName(metadata.getClassName()));
	}
	return packagesToScan;
}
 
Example 2
Source File: GRpcApiRegister.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(GRpcServerScan.class.getCanonicalName()));
    if (annotationAttributes == null) {
        log.warn("GrpcScan was not found.Please check your configuration.");
        return;
    }
    ClassPathBeanDefinitionScanner classPathGrpcApiScanner = new ClassPathBeanDefinitionScanner(registry, false);
    classPathGrpcApiScanner.setResourceLoader(this.resourceLoader);
    classPathGrpcApiScanner.addIncludeFilter(new AnnotationTypeFilter(GRpcApi.class));
    List<String> basePackages = AutoConfigurationPackages.get(this.beanFactory);
    for (String pkg : annotationAttributes.getStringArray("basePackages")) {
        if (StringUtils.hasText(pkg)) {
            basePackages.add(pkg);
        }
    }
    classPathGrpcApiScanner.scan(StringUtils.toStringArray(basePackages));
}
 
Example 3
Source File: ConfigurationTypeRegistrar.java    From conf4j with MIT License 6 votes vote down vote up
private void registerConfigurationType(BeanDefinitionRegistry registry, AnnotationAttributes attributes) {
    Class<?> configurationType = attributes.getClass("value");
    String[] names = attributes.getStringArray("name");

    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(configurationType);
    addConf4jConfigurationIndicator(builder.getRawBeanDefinition(), ConfigurationIndicator.MANUAL);

    String beanName;
    String[] aliases = null;
    if (names.length == 0) {
        beanName = configurationType.getName();
    } else if (names.length == 1) {
        beanName = names[0];
    } else {
        beanName = names[0];
        aliases = ArrayUtils.subarray(names, 1, names.length);
    }

    registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
    if (aliases != null) {
        for (String alias : aliases) {
            registry.registerAlias(beanName, alias);
        }
    }
}
 
Example 4
Source File: StoreUtils.java    From spring-content with Apache License 2.0 6 votes vote down vote up
public static String[] getBasePackages(AnnotationAttributes attributes, String[] defaultPackages) {

		String[] value = attributes.getStringArray("value");
		String[] basePackages = attributes.getStringArray(BASE_PACKAGES);
		Class<?>[] basePackageClasses = attributes.getClassArray(BASE_PACKAGE_CLASSES);

		// Default configuration - return package of annotated class
		if (value.length == 0 && basePackages.length == 0
				&& basePackageClasses.length == 0) {
			return defaultPackages;
		}

		Set<String> packages = new HashSet<String>();
		packages.addAll(Arrays.asList(value));
		packages.addAll(Arrays.asList(basePackages));

		for (Class<?> typeName : basePackageClasses) {
			packages.add(ClassUtils.getPackageName(typeName));
		}

		return packages.toArray(new String[] {});
	}
 
Example 5
Source File: WebGuestComponentScanRegistrar.java    From wallride with Apache License 2.0 6 votes vote down vote up
private Set<String> getPackagesToScan(AnnotationMetadata metadata) {
	AnnotationAttributes attributes = AnnotationAttributes
			.fromMap(metadata.getAnnotationAttributes(WebGuestComponentScan.class.getName()));
	String[] value = attributes.getStringArray("value");
	String[] basePackages = attributes.getStringArray("basePackages");
	Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
	if (!ObjectUtils.isEmpty(value)) {
		Assert.state(ObjectUtils.isEmpty(basePackages),
				"@WebGuestComponentScan basePackages and value attributes are mutually exclusive");
	}
	Set<String> packagesToScan = new LinkedHashSet<String>();
	packagesToScan.addAll(Arrays.asList(value));
	packagesToScan.addAll(Arrays.asList(basePackages));
	for (Class<?> basePackageClass : basePackageClasses) {
		packagesToScan.add(ClassUtils.getPackageName(basePackageClass));
	}
	if (packagesToScan.isEmpty()) {
		return Collections.singleton(ClassUtils.getPackageName(metadata.getClassName()));
	}
	return packagesToScan;
}
 
Example 6
Source File: DefaultApolloConfigRegistrarHelper.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
  AnnotationAttributes attributes = AnnotationAttributes
      .fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
  String[] namespaces = attributes.getStringArray("value");
  int order = attributes.getNumber("order");
  PropertySourcesProcessor.addNamespaces(Lists.newArrayList(namespaces), order);

  Map<String, Object> propertySourcesPlaceholderPropertyValues = new HashMap<>();
  // to make sure the default PropertySourcesPlaceholderConfigurer's priority is higher than PropertyPlaceholderConfigurer
  propertySourcesPlaceholderPropertyValues.put("order", 0);

  BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(),
      PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues);
  BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(),
      PropertySourcesProcessor.class);
  BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class.getName(),
      ApolloAnnotationProcessor.class);
  BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class.getName(),
      SpringValueProcessor.class);
  BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueDefinitionProcessor.class.getName(),
      SpringValueDefinitionProcessor.class);
  BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloJsonValueProcessor.class.getName(),
      ApolloJsonValueProcessor.class);
}
 
Example 7
Source File: OnMissingPropertyCondition.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
private String[] getNames(AnnotationAttributes annotationAttributes) {

		String[] names = annotationAttributes.getStringArray("name");
		String[] values = annotationAttributes.getStringArray("value");

		Assert.isTrue(names.length > 0 || values.length > 0,
			String.format("The name or value attribute of @%s is required",
				ConditionalOnMissingProperty.class.getSimpleName()));

		// TODO remove; not needed when using @AliasFor.
		/*
		Assert.isTrue(names.length * values.length == 0,
			String.format("The name and value attributes of @%s are exclusive",
				ConditionalOnMissingProperty.class.getSimpleName()));
		*/

		return names.length > 0 ? names : values;
	}
 
Example 8
Source File: AnnotationMetadataTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void assertMetaAnnotationOverrides(AnnotationMetadata metadata) {
	AnnotationAttributes attributes = (AnnotationAttributes) metadata.getAnnotationAttributes(
			TestComponentScan.class.getName(), false);
	String[] basePackages = attributes.getStringArray("basePackages");
	assertThat("length of basePackages[]", basePackages.length, is(1));
	assertThat("basePackages[0]", basePackages[0], is("org.example.componentscan"));
	String[] value = attributes.getStringArray("value");
	assertThat("length of value[]", value.length, is(0));
	Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
	assertThat("length of basePackageClasses[]", basePackageClasses.length, is(0));
}
 
Example 9
Source File: CacheConfiguration.java    From redisson-spring-boot-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
    Map<String, Object> enableAttrMap = importMetadata
            .getAnnotationAttributes(EnableCache.class.getName());
    AnnotationAttributes enableAttrs = AnnotationAttributes.fromMap(enableAttrMap);
    this.value=enableAttrs.getStringArray("value");
    this.maxIdleTime=enableAttrs.getNumber("maxIdleTime");
    this.ttl=enableAttrs.getNumber("ttl");
}
 
Example 10
Source File: ApiClientMethod.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public void initialize(){
	if(!ApiClientUtils.isRequestMappingPresent()){
		throw new ApiClientException(ApiClientErrors.REQUEST_MAPPING_NOT_FOUND);
	}
	Optional<AnnotationAttributes> requestMapping = SpringUtils.getAnnotationAttributes(method, RequestMapping.class);
	if(!requestMapping.isPresent()){
		throw new ApiClientException(ApiClientErrors.REQUEST_MAPPING_NOT_FOUND, method, null);
	}
	
	AnnotationAttributes reqestMappingAttrs = requestMapping.get();
	//SpringMvcContract#parseAndValidateMetadata
	this.acceptHeaders = Arrays.asList(reqestMappingAttrs.getStringArray("produces"));
	String[] consumes = reqestMappingAttrs.getStringArray("consumes");
	this.contentType = LangUtils.getFirstOptional(consumes);
	this.consumeMediaTypes = Stream.of(consumes).map(MediaType::parseMediaType).collect(Collectors.toList());
	this.headers = reqestMappingAttrs.getStringArray("headers");
	
	String[] paths = reqestMappingAttrs.getStringArray("value");
	path = LangUtils.isEmpty(paths)?"":paths[0];
	
	RequestMethod[] methods = (RequestMethod[])reqestMappingAttrs.get("method");
	requestMethod = LangUtils.isEmpty(methods)?RequestMethod.GET:methods[0];

	findParameterByType(ApiHeaderCallback.class).ifPresent(p->{
		this.apiHeaderCallbackIndex = p.getParameterIndex();
	});
	findParameterByType(HttpHeaders.class).ifPresent(p->{
		this.headerParameterIndex = p.getParameterIndex();
	});
	

	this.initHandlers();
	this.initInterceptors();
}
 
Example 11
Source File: AnnotationMetadataTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void assertMetaAnnotationOverrides(AnnotationMetadata metadata) {
	AnnotationAttributes attributes = (AnnotationAttributes) metadata.getAnnotationAttributes(
			TestComponentScan.class.getName(), false);
	String[] basePackages = attributes.getStringArray("basePackages");
	assertThat("length of basePackages[]", basePackages.length, is(1));
	assertThat("basePackages[0]", basePackages[0], is("org.example.componentscan"));
	String[] value = attributes.getStringArray("value");
	assertThat("length of value[]", value.length, is(0));
	Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
	assertThat("length of basePackageClasses[]", basePackageClasses.length, is(0));
}
 
Example 12
Source File: AnnotationMetadataTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void assertMetaAnnotationOverrides(AnnotationMetadata metadata) {
	AnnotationAttributes attributes = (AnnotationAttributes) metadata.getAnnotationAttributes(
			TestComponentScan.class.getName(), false);
	String[] basePackages = attributes.getStringArray("basePackages");
	assertThat("length of basePackages[]", basePackages.length, is(1));
	assertThat("basePackages[0]", basePackages[0], is("org.example.componentscan"));
	String[] value = attributes.getStringArray("value");
	assertThat("length of value[]", value.length, is(0));
	Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
	assertThat("length of basePackageClasses[]", basePackageClasses.length, is(0));
}
 
Example 13
Source File: ConfigurationClassParser.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Apply processing and build a complete {@link ConfigurationClass} by reading the
 * annotations, members and methods from the source class. This method can be called
 * multiple times as relevant sources are discovered.
 * @param configClass the configuration class being build
 * @param sourceClass a source class
 * @return the superclass, or {@code null} if none found or previously processed
 */
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
		throws IOException {

	// Recursively process any member (nested) classes first
	processMemberClasses(configClass, sourceClass);

	// Process any @PropertySource annotations
	for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), PropertySources.class,
			org.springframework.context.annotation.PropertySource.class)) {
		if (this.environment instanceof ConfigurableEnvironment) {
			processPropertySource(propertySource);
		}
		else {
			logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
					"]. Reason: Environment must implement ConfigurableEnvironment");
		}
	}

	// Process any @ComponentScan annotations
	Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
	if (!componentScans.isEmpty() &&
			!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
		for (AnnotationAttributes componentScan : componentScans) {
			// The config class is annotated with @ComponentScan -> perform the scan immediately
			Set<BeanDefinitionHolder> scannedBeanDefinitions =
					this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
			// Check the set of scanned definitions for any further config classes and parse recursively if needed
			for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
				if (ConfigurationClassUtils.checkConfigurationClassCandidate(
						holder.getBeanDefinition(), this.metadataReaderFactory)) {
					parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
				}
			}
		}
	}

	// Process any @Import annotations
	processImports(configClass, sourceClass, getImports(sourceClass), true);

	// Process any @ImportResource annotations
	if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) {
		AnnotationAttributes importResource =
				AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
		String[] resources = importResource.getStringArray("locations");
		Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
		for (String resource : resources) {
			String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
			configClass.addImportedResource(resolvedResource, readerClass);
		}
	}

	// Process individual @Bean methods
	Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
	for (MethodMetadata methodMetadata : beanMethods) {
		configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
	}

	// Process default methods on interfaces
	processInterfaces(configClass, sourceClass);

	// Process superclass, if any
	if (sourceClass.getMetadata().hasSuperClass()) {
		String superclass = sourceClass.getMetadata().getSuperClassName();
		if (!superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) {
			this.knownSuperclasses.put(superclass, configClass);
			// Superclass found, return its annotation metadata and recurse
			return sourceClass.getSuperClass();
		}
	}

	// No superclass -> processing is complete
	return null;
}
 
Example 14
Source File: ComponentScanAnnotationParser.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private List<TypeFilter> typeFiltersFor(AnnotationAttributes filterAttributes) {
	List<TypeFilter> typeFilters = new ArrayList<>();
	FilterType filterType = filterAttributes.getEnum("type");

	for (Class<?> filterClass : filterAttributes.getClassArray("classes")) {
		switch (filterType) {
			case ANNOTATION:
				Assert.isAssignable(Annotation.class, filterClass,
						"@ComponentScan ANNOTATION type filter requires an annotation type");
				@SuppressWarnings("unchecked")
				Class<Annotation> annotationType = (Class<Annotation>) filterClass;
				typeFilters.add(new AnnotationTypeFilter(annotationType));
				break;
			case ASSIGNABLE_TYPE:
				typeFilters.add(new AssignableTypeFilter(filterClass));
				break;
			case CUSTOM:
				Assert.isAssignable(TypeFilter.class, filterClass,
						"@ComponentScan CUSTOM type filter requires a TypeFilter implementation");
				TypeFilter filter = BeanUtils.instantiateClass(filterClass, TypeFilter.class);
				ParserStrategyUtils.invokeAwareMethods(
						filter, this.environment, this.resourceLoader, this.registry);
				typeFilters.add(filter);
				break;
			default:
				throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType);
		}
	}

	for (String expression : filterAttributes.getStringArray("pattern")) {
		switch (filterType) {
			case ASPECTJ:
				typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader.getClassLoader()));
				break;
			case REGEX:
				typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression)));
				break;
			default:
				throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType);
		}
	}

	return typeFilters;
}
 
Example 15
Source File: ConfigurationClassParser.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Apply processing and build a complete {@link ConfigurationClass} by reading the
 * annotations, members and methods from the source class. This method can be called
 * multiple times as relevant sources are discovered.
 * @param configClass the configuration class being build
 * @param sourceClass a source class
 * @return the superclass, or {@code null} if none found or previously processed
 */
@Nullable
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
		throws IOException {

	if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
		// Recursively process any member (nested) classes first
		processMemberClasses(configClass, sourceClass);
	}

	// Process any @PropertySource annotations
	for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), PropertySources.class,
			org.springframework.context.annotation.PropertySource.class)) {
		if (this.environment instanceof ConfigurableEnvironment) {
			processPropertySource(propertySource);
		}
		else {
			logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
					"]. Reason: Environment must implement ConfigurableEnvironment");
		}
	}

	// Process any @ComponentScan annotations
	Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
	if (!componentScans.isEmpty() &&
			!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
		for (AnnotationAttributes componentScan : componentScans) {
			// The config class is annotated with @ComponentScan -> perform the scan immediately
			Set<BeanDefinitionHolder> scannedBeanDefinitions =
					this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
			// Check the set of scanned definitions for any further config classes and parse recursively if needed
			for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
				BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
				if (bdCand == null) {
					bdCand = holder.getBeanDefinition();
				}
				if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
					parse(bdCand.getBeanClassName(), holder.getBeanName());
				}
			}
		}
	}

	// Process any @Import annotations
	processImports(configClass, sourceClass, getImports(sourceClass), true);

	// Process any @ImportResource annotations
	AnnotationAttributes importResource =
			AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
	if (importResource != null) {
		String[] resources = importResource.getStringArray("locations");
		Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
		for (String resource : resources) {
			String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
			configClass.addImportedResource(resolvedResource, readerClass);
		}
	}

	// Process individual @Bean methods
	Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
	for (MethodMetadata methodMetadata : beanMethods) {
		configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
	}

	// Process default methods on interfaces
	processInterfaces(configClass, sourceClass);

	// Process superclass, if any
	if (sourceClass.getMetadata().hasSuperClass()) {
		String superclass = sourceClass.getMetadata().getSuperClassName();
		if (superclass != null && !superclass.startsWith("java") &&
				!this.knownSuperclasses.containsKey(superclass)) {
			this.knownSuperclasses.put(superclass, configClass);
			// Superclass found, return its annotation metadata and recurse
			return sourceClass.getSuperClass();
		}
	}

	// No superclass -> processing is complete
	return null;
}
 
Example 16
Source File: ComponentScanAnnotationParser.java    From java-technology-stack with MIT License 4 votes vote down vote up
private List<TypeFilter> typeFiltersFor(AnnotationAttributes filterAttributes) {
	List<TypeFilter> typeFilters = new ArrayList<>();
	FilterType filterType = filterAttributes.getEnum("type");

	for (Class<?> filterClass : filterAttributes.getClassArray("classes")) {
		switch (filterType) {
			case ANNOTATION:
				Assert.isAssignable(Annotation.class, filterClass,
						"@ComponentScan ANNOTATION type filter requires an annotation type");
				@SuppressWarnings("unchecked")
				Class<Annotation> annotationType = (Class<Annotation>) filterClass;
				typeFilters.add(new AnnotationTypeFilter(annotationType));
				break;
			case ASSIGNABLE_TYPE:
				typeFilters.add(new AssignableTypeFilter(filterClass));
				break;
			case CUSTOM:
				Assert.isAssignable(TypeFilter.class, filterClass,
						"@ComponentScan CUSTOM type filter requires a TypeFilter implementation");
				TypeFilter filter = BeanUtils.instantiateClass(filterClass, TypeFilter.class);
				ParserStrategyUtils.invokeAwareMethods(
						filter, this.environment, this.resourceLoader, this.registry);
				typeFilters.add(filter);
				break;
			default:
				throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType);
		}
	}

	for (String expression : filterAttributes.getStringArray("pattern")) {
		switch (filterType) {
			case ASPECTJ:
				typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader.getClassLoader()));
				break;
			case REGEX:
				typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression)));
				break;
			default:
				throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType);
		}
	}

	return typeFilters;
}
 
Example 17
Source File: OnPropertyPrefixCondition.java    From spring-boot-web-support with GNU General Public License v3.0 4 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {

    AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(
            metadata.getAnnotationAttributes(ConditionalOnPropertyPrefix.class.getName()));

    String[] prefixValues = annotationAttributes.getStringArray("value");

    ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment();

    boolean matched = false;

    for (String prefix : prefixValues) {

        if (startsWith(environment, prefix)) {
            matched = true;
            break;
        }

    }

    return matched ? ConditionOutcome.match() : ConditionOutcome.noMatch("The prefix values " +
            Arrays.asList(prefixValues) + " were not found in Environment!");

}
 
Example 18
Source File: VaultPropertySourceRegistrar.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {

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

	if (!registry.isBeanNameInUse("VaultPropertySourceRegistrar")) {
		registry.registerBeanDefinition("VaultPropertySourceRegistrar", BeanDefinitionBuilder //
				.rootBeanDefinition(VaultPropertySourceRegistrar.class) //
				.setRole(BeanDefinition.ROLE_INFRASTRUCTURE) //
				.getBeanDefinition());
	}

	Set<AnnotationAttributes> propertySources = attributesForRepeatable(annotationMetadata,
			VaultPropertySources.class.getName(), VaultPropertySource.class.getName());

	int counter = 0;

	for (AnnotationAttributes propertySource : propertySources) {

		String[] paths = propertySource.getStringArray("value");
		String ref = propertySource.getString("vaultTemplateRef");
		String propertyNamePrefix = propertySource.getString("propertyNamePrefix");
		Renewal renewal = propertySource.getEnum("renewal");
		boolean ignoreSecretNotFound = propertySource.getBoolean("ignoreSecretNotFound");

		Assert.isTrue(paths.length > 0, "At least one @VaultPropertySource(value) location is required");

		Assert.hasText(ref, "'vaultTemplateRef' in @EnableVaultPropertySource must not be empty");

		PropertyTransformer propertyTransformer = StringUtils.hasText(propertyNamePrefix)
				? PropertyTransformers.propertyNamePrefix(propertyNamePrefix) : PropertyTransformers.noop();

		for (String propertyPath : paths) {

			if (!StringUtils.hasText(propertyPath)) {
				continue;
			}

			AbstractBeanDefinition beanDefinition = createBeanDefinition(ref, renewal, propertyTransformer,
					ignoreSecretNotFound, potentiallyResolveRequiredPlaceholders(propertyPath));

			do {
				String beanName = "vaultPropertySource#" + counter;

				if (!registry.isBeanNameInUse(beanName)) {
					registry.registerBeanDefinition(beanName, beanDefinition);
					break;
				}

				counter++;
			}
			while (true);
		}
	}
}
 
Example 19
Source File: ContextConfigurationAttributes.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Construct a new {@link ContextConfigurationAttributes} instance for the
 * supplied {@link AnnotationAttributes} (parsed from a
 * {@link ContextConfiguration @ContextConfiguration} annotation) and
 * the {@linkplain Class test class} that declared them.
 * @param declaringClass the test class that declared {@code @ContextConfiguration}
 * @param annAttrs the annotation attributes from which to retrieve the attributes
 */
@SuppressWarnings("unchecked")
public ContextConfigurationAttributes(Class<?> declaringClass, AnnotationAttributes annAttrs) {
	this(declaringClass, annAttrs.getStringArray("locations"), annAttrs.getClassArray("classes"), annAttrs.getBoolean("inheritLocations"),
		(Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>[]) annAttrs.getClassArray("initializers"),
		annAttrs.getBoolean("inheritInitializers"), annAttrs.getString("name"), (Class<? extends ContextLoader>) annAttrs.getClass("loader"));
}
 
Example 20
Source File: ContextConfigurationAttributes.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Construct a new {@link ContextConfigurationAttributes} instance for the
 * supplied {@link AnnotationAttributes} (parsed from a
 * {@link ContextConfiguration @ContextConfiguration} annotation) and
 * the {@linkplain Class test class} that declared them.
 * @param declaringClass the test class that declared {@code @ContextConfiguration}
 * @param annAttrs the annotation attributes from which to retrieve the attributes
 */
@SuppressWarnings("unchecked")
public ContextConfigurationAttributes(Class<?> declaringClass, AnnotationAttributes annAttrs) {
	this(declaringClass, annAttrs.getStringArray("locations"), annAttrs.getClassArray("classes"),
			annAttrs.getBoolean("inheritLocations"),
			(Class<? extends ApplicationContextInitializer<?>>[]) annAttrs.getClassArray("initializers"),
			annAttrs.getBoolean("inheritInitializers"), annAttrs.getString("name"), annAttrs.getClass("loader"));
}