Java Code Examples for org.springframework.core.env.PropertySource

The following examples show how to use org.springframework.core.env.PropertySource. These examples are extracted from open source projects. 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 Project: jasypt-spring-boot   Author: ulisesbocchio   File: EncryptablePropertySourceBeanFactoryPostProcessor.java    License: MIT License 6 votes vote down vote up
private PropertySource createPropertySource(AnnotationAttributes attributes, ConfigurableEnvironment environment, ResourceLoader resourceLoader, EncryptablePropertyResolver resolver, EncryptablePropertyFilter propertyFilter, List<PropertySourceLoader> loaders) throws Exception {
    String name = generateName(attributes.getString("name"));
    String[] locations = attributes.getStringArray("value");
    boolean ignoreResourceNotFound = attributes.getBoolean("ignoreResourceNotFound");
    CompositePropertySource compositePropertySource = new CompositePropertySource(name);
    Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
    for (String location : locations) {
        String resolvedLocation = environment.resolveRequiredPlaceholders(location);
        Resource resource = resourceLoader.getResource(resolvedLocation);
        if (!resource.exists()) {
            if (!ignoreResourceNotFound) {
                throw new IllegalStateException(String.format("Encryptable Property Source '%s' from location: %s Not Found", name, resolvedLocation));
            } else {
                log.info("Ignoring NOT FOUND Encryptable Property Source '{}' from locations: {}", name, resolvedLocation);
            }
        } else {
            String actualName = name + "#" + resolvedLocation;
            loadPropertySource(loaders, resource, actualName)
                    .ifPresent(psources -> psources.forEach(compositePropertySource::addPropertySource));
        }
    }
    return new EncryptableEnumerablePropertySourceWrapper<>(compositePropertySource, resolver, propertyFilter);
}
 
Example #2
Source Project: spring-cloud-services-connector   Author: pivotal-cf   File: ServiceInfoPropertySourceAdapter.java    License: Apache License 2.0 6 votes vote down vote up
private void conditionallyExcludeRabbitAutoConfiguration() {
	if (appIsBoundToRabbitMQ()) {
		return;
	}

	Map<String, Object> properties = new LinkedHashMap<>();
	String existingExcludes = environment.getProperty(SPRING_AUTOCONFIGURE_EXCLUDE);
	if (existingExcludes == null) {
		properties.put(SPRING_AUTOCONFIGURE_EXCLUDE, RABBIT_AUTOCONFIG_CLASS);
	} else if (!existingExcludes.contains(RABBIT_AUTOCONFIG_CLASS)) {
		properties.put(SPRING_AUTOCONFIGURE_EXCLUDE, RABBIT_AUTOCONFIG_CLASS + "," + existingExcludes);
	}

	PropertySource<?> propertySource = new MapPropertySource("springCloudServicesRabbitAutoconfigExcluder",
			properties);
	environment.getPropertySources().addFirst(propertySource);
}
 
Example #3
Source Project: spring-boot-data-geode   Author: spring-projects   File: VcapPropertySourceUnitTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void fromEnvironmentIsSuccessful() {

	ConfigurableEnvironment mockEnvironment = mock(ConfigurableEnvironment.class);

	MutablePropertySources propertySources = spy(new MutablePropertySources());

	PropertySource mockVcapPropertySource = mock(EnumerablePropertySource.class);

	when(mockEnvironment.getPropertySources()).thenReturn(propertySources);
	doReturn(mockVcapPropertySource).when(propertySources).get(eq("vcap"));
	when(mockVcapPropertySource.containsProperty(anyString())).thenReturn(true);
	when(mockVcapPropertySource.getName()).thenReturn("vcap");

	VcapPropertySource propertySource = VcapPropertySource.from(mockEnvironment);

	assertThat(propertySource).isNotNull();
	assertThat(propertySource.getSource()).isEqualTo(mockVcapPropertySource);

	verify(mockEnvironment, times(1)).getPropertySources();
	verify(propertySources, times(1)).get(eq("vcap"));
	verify(mockVcapPropertySource, times(1))
		.containsProperty(eq("vcap.application.name"));
	verify(mockVcapPropertySource, times(1))
		.containsProperty(eq("vcap.application.uris"));
}
 
Example #4
Source Project: grails-boot   Author: grails   File: GspAutoConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void updateFlatConfig() {
    super.updateFlatConfig();
    if(this.environment instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment configurableEnv = ((ConfigurableEnvironment)environment);
        for(PropertySource<?> propertySource : configurableEnv.getPropertySources()) {
            if(propertySource instanceof EnumerablePropertySource) {
                EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource)propertySource;
                for(String propertyName : enumerablePropertySource.getPropertyNames()) {
                    flatConfig.put(propertyName, enumerablePropertySource.getProperty(propertyName));
                }
            }
        }
    }
}
 
Example #5
Source Project: flowable-engine   Author: flowable   File: FlowableRestApplicationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void contextShouldLoadPropertiesInACorrectOrder() {
    assertThat(environment.getPropertySources())
        .extracting(PropertySource::getName)
        .containsExactly(
            "configurationProperties",
            "Inlined Test Properties",
            "systemProperties",
            "systemEnvironment",
            "random",
            "class path resource [db.properties]",
            "class path resource [engine.properties]",
            "applicationConfig: [classpath:/application.properties]",
            "flowableDefaultConfig: [classpath:/flowable-default.properties]",
            "flowable-liquibase-override",
            "Management Server"
        );
}
 
Example #6
Source Project: spring-cloud-commons   Author: spring-cloud   File: ContextRefresherOrderingIntegrationTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void orderingIsCorrect() {
	refresher.refresh();
	MutablePropertySources propertySources = environment.getPropertySources();
	PropertySource<?> test1 = propertySources
			.get("bootstrapProperties-testContextRefresherOrdering1");
	PropertySource<?> test2 = propertySources
			.get("bootstrapProperties-testContextRefresherOrdering2");
	PropertySource<?> test3 = propertySources
			.get("bootstrapProperties-testContextRefresherOrdering3");
	int index1 = propertySources.precedenceOf(test1);
	int index2 = propertySources.precedenceOf(test2);
	int index3 = propertySources.precedenceOf(test3);
	assertThat(index1).as("source1 index not less then source2").isLessThan(index2);
	assertThat(index2).as("source2 index not less then source3").isLessThan(index3);
}
 
Example #7
Source Project: spring-analysis-note   Author: Vip-Augus   File: PropertySourcesPlaceholderConfigurerTests.java    License: MIT License 6 votes vote down vote up
@Test
public void withNonEnumerablePropertySource() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${foo}")
				.getBeanDefinition());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();

	PropertySource<?> ps = new PropertySource<Object>("simplePropertySource", new Object()) {
		@Override
		public Object getProperty(String key) {
			return "bar";
		}
	};

	MockEnvironment env = new MockEnvironment();
	env.getPropertySources().addFirst(ps);
	ppc.setEnvironment(env);

	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("bar"));
}
 
Example #8
Source Project: spring-cloud-vault   Author: spring-cloud   File: VaultPropertySourceLocatorSupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create {@link PropertySource}s given {@link Environment} from the property
 * configuration.
 * @param environment must not be {@literal null}.
 * @return a {@link List} of ordered {@link PropertySource}s.
 */
protected List<PropertySource<?>> doCreatePropertySources(Environment environment) {

	Collection<SecretBackendMetadata> secretBackends = this.propertySourceLocatorConfiguration
			.getSecretBackends();
	List<SecretBackendMetadata> sorted = new ArrayList<>(secretBackends);
	List<PropertySource<?>> propertySources = new ArrayList<>();

	AnnotationAwareOrderComparator.sort(sorted);

	propertySources.addAll(doCreateKeyValuePropertySources(environment));

	for (SecretBackendMetadata backendAccessor : sorted) {

		PropertySource<?> vaultPropertySource = createVaultPropertySource(
				backendAccessor);
		propertySources.add(vaultPropertySource);
	}

	return propertySources;
}
 
Example #9
Source Project: radar   Author: geekshop   File: EnvProp.java    License: Apache License 2.0 6 votes vote down vote up
public Map<String, Map<String, Object>> getAllEnv() {
	Map<String, Map<String, Object>> result = new LinkedHashMap<String, Map<String, Object>>();		
	for (Entry<String, PropertySource<?>> entry : getPropertySources().entrySet()) {
		PropertySource<?> source = entry.getValue();
		String sourceName = entry.getKey();
		if (source instanceof EnumerablePropertySource) {
			EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) source;
			Map<String, Object> properties = new LinkedHashMap<String, Object>();
			for (String name : enumerable.getPropertyNames()) {
				properties.put(name, sanitize(name, enumerable.getProperty(name)));
			}
			result.put(sourceName, properties);				
		}
	}
	return result;
}
 
Example #10
Source Project: mPaaS   Author: lihangqi   File: ResourceLoadFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    PropertySource<?> propSource = null;
    String propName = name;
    if (StringUtils.isEmpty(propName)) {
        propName = getNameForResource(resource.getResource());
    }
    if (resource.getResource().exists()) {
        String fileName = resource.getResource().getFilename();
        for (PropertySourceLoader loader : loaders) {
            if (checkFileType(fileName, loader.getFileExtensions())) {
                List<PropertySource<?>> propertySources = loader.load(propName, resource.getResource());
                if (!propertySources.isEmpty()) {
                    propSource = propertySources.get(0);
                }
            }
        }
    } else {
        throw new FileNotFoundException(propName + "对应文件'" + resource.getResource().getFilename() + "'不存在");
    }
    return propSource;
}
 
Example #11
Source Project: pmq   Author: ppdaicorp   File: MqEnvProp.java    License: Apache License 2.0 6 votes vote down vote up
public Map<String, Map<String, Object>> getAllEnv() {  
	Map<String, Map<String, Object>> result = new LinkedHashMap<String, Map<String, Object>>();		
	for (Entry<String, PropertySource<?>> entry : getPropertySources().entrySet()) {
		PropertySource<?> source = entry.getValue();
		String sourceName = entry.getKey();
		if (source instanceof EnumerablePropertySource) {
			EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) source;
			Map<String, Object> properties = new LinkedHashMap<String, Object>();
			for (String name : enumerable.getPropertyNames()) {
				properties.put(name, sanitize(name, enumerable.getProperty(name)));
			}
			result.put(sourceName, properties);				
		}
	}
	return result;
}
 
Example #12
Source Project: tutorials   Author: eugenp   File: PriceCalculationEnvironmentPostProcessor.java    License: MIT License 6 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

    PropertySource<?> system = environment.getPropertySources()
        .get(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);

    Map<String, Object> prefixed = new LinkedHashMap<>();

    if (!hasOurPriceProperties(system)) {
        // Baeldung-internal code so this doesn't break other examples
        logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", CALCUATION_MODE_DEFAULT_VALUE,
            GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
        prefixed = names.stream()
            .collect(Collectors.toMap(this::rename, this::getDefaultValue));
        environment.getPropertySources()
            .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));
        return;
    }

    prefixed = names.stream()
        .collect(Collectors.toMap(this::rename, system::getProperty));
    environment.getPropertySources()
        .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));

}
 
Example #13
Source Project: jeesuite-config   Author: vakinge   File: CCPropertySourceLoader.java    License: Apache License 2.0 6 votes vote down vote up
public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {

		logger.info("load PropertySource -> name:{},profile:{}", name, profile);
		if (profile == null) {
			Properties properties = loadProperties(name,resource);
			if (profiles == null) {
				profiles = properties.getProperty("spring.profiles.active");
			} else {
				logger.info("spring.profiles.active = " + profiles + ",ignore load remote config");
			}
			// 如果指定了profile,则也不加载远程配置
			if (profiles == null && ccContext.isRemoteEnabled() && !ccContext.isProcessed()) {
				ccContext.init(properties, true);
				ccContext.mergeRemoteProperties(properties);
			}

			if (!properties.isEmpty()) {
				return new PropertiesPropertySource(name, properties);
			}
		}
		return null;
	}
 
Example #14
Source Project: spring-cloud-vault   Author: spring-cloud   File: LeasingVaultPropertySourceLocatorUnitTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLocateLeaseAwareSources() {

	RequestedSecret rotating = RequestedSecret.rotating("secret/rotating");
	DefaultSecretBackendConfigurer configurer = new DefaultSecretBackendConfigurer();
	configurer.add(rotating);
	configurer.add("database/mysql/creds/readonly");

	this.propertySourceLocator = new LeasingVaultPropertySourceLocator(
			new VaultProperties(), configurer, this.secretLeaseContainer);

	PropertySource<?> propertySource = this.propertySourceLocator
			.locate(this.configurableEnvironment);

	assertThat(propertySource).isInstanceOf(CompositePropertySource.class);

	verify(this.secretLeaseContainer).addRequestedSecret(rotating);
	verify(this.secretLeaseContainer).addRequestedSecret(
			RequestedSecret.renewable("database/mysql/creds/readonly"));
}
 
Example #15
Source Project: kafka-graphs   Author: rayokota   File: AppContextEventListener.java    License: Apache License 2.0 6 votes vote down vote up
private void logActiveProperties(ConfigurableEnvironment env) {
    List<MapPropertySource> propertySources = new ArrayList<>();

    for (PropertySource<?> source : env.getPropertySources()) {
        if (source instanceof MapPropertySource && source.getName().contains("applicationConfig")) {
            propertySources.add((MapPropertySource) source);
        }
    }

    propertySources.stream()
        .map(propertySource -> propertySource.getSource().keySet())
        .flatMap(Collection::stream)
        .distinct()
        .sorted()
        .forEach(key -> {
            try {
                log.debug(key + "=" + env.getProperty(key));
            } catch (Exception e) {
                log.warn("{} -> {}", key, e.getMessage());
            }
        });
}
 
Example #16
Source Project: spring-cloud-gray   Author: SpringCloud   File: ConfigurationPropertySources.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Attach a {@link ConfigurationPropertySource} support to the specified
 * {@link Environment}. Adapts each {@link PropertySource} managed by the environment
 * to a {@link ConfigurationPropertySource} and allows classic
 * {@link PropertySourcesPropertyResolver} calls to resolve using
 * {@link ConfigurationPropertyName configuration property names}.
 * <p>
 * The attached resolver will dynamically track any additions or removals from the
 * underlying {@link Environment} property sources.
 *
 * @param environment the source environment (must be an instance of
 *                    {@link ConfigurableEnvironment})
 * @see #get(Environment)
 */
public static void attach(Environment environment) {
    Assert.isInstanceOf(ConfigurableEnvironment.class, environment);
    MutablePropertySources sources = ((ConfigurableEnvironment) environment)
            .getPropertySources();
    PropertySource<?> attached = sources.get(ATTACHED_PROPERTY_SOURCE_NAME);
    if (attached != null && attached.getSource() != sources) {
        sources.remove(ATTACHED_PROPERTY_SOURCE_NAME);
        attached = null;
    }
    if (attached == null) {
        sources.addFirst(new ConfigurationPropertySourcesPropertySource(
                ATTACHED_PROPERTY_SOURCE_NAME,
                new SpringConfigurationPropertySources(sources)));
    }
}
 
Example #17
Source Project: spring-cloud-formula   Author: baidu   File: LauncherInfoContributor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected PropertySource<?> toSimplePropertySource() {
    Properties props = new Properties();

    AtomicInteger index = new AtomicInteger(0);
    getProperties().getArchives().forEach(archive -> {
        props.setProperty("archives[" + index.get() + "]", archive);
        index.getAndIncrement();
    });

    copyIfSet(props, "git.branch");
    String commitId = getProperties().getGit().getShortCommitId();
    if (commitId != null) {
        props.put("git.commit.id", commitId);
    }
    copyIfSet(props, "git.commit.time");
    return new PropertiesPropertySource("launcher", props);
}
 
Example #18
Source Project: DataSphereStudio   Author: WeBankFinTech   File: DSSSpringApplication.java    License: Apache License 2.0 6 votes vote down vote up
private static void addOrUpdateRemoteConfig(Environment env, boolean isUpdateOrNot) {
    StandardEnvironment environment = (StandardEnvironment) env;
    PropertySource propertySource = environment.getPropertySources().get("bootstrapProperties");
    if(propertySource == null) {
        return;
    }
    CompositePropertySource source = (CompositePropertySource) propertySource;
    for (String key: source.getPropertyNames()) {
        Object val = source.getProperty(key);
        if(val == null) {
            continue;
        }
        if(isUpdateOrNot) {
            logger.info("update remote config => " + key + " = " + source.getProperty(key));
            BDPConfiguration.set(key, val.toString());
        } else {
            logger.info("add remote config => " + key + " = " + source.getProperty(key));
            BDPConfiguration.setIfNotExists(key, val.toString());
        }
    }
}
 
Example #19
Source Project: spring-boot-data-geode   Author: spring-projects   File: CustomConfiguredSessionCachingIntegrationTests.java    License: Apache License 2.0 6 votes vote down vote up
private Function<ConfigurableApplicationContext, ConfigurableApplicationContext> newSpringSessionGemFirePropertiesConfigurationFunction() {

		return applicationContext -> {

			PropertySource springSessionGemFireProperties = new MockPropertySource("TestSpringSessionGemFireProperties")
				.withProperty(springSessionPropertyName("cache.client.region.shortcut"), "LOCAL")
				.withProperty(springSessionPropertyName("session.attributes.indexable"), "one, two")
				.withProperty(springSessionPropertyName("session.expiration.max-inactive-interval-seconds"), "600")
				.withProperty(springSessionPropertyName("cache.client.pool.name"), "MockPool")
				.withProperty(springSessionPropertyName("session.region.name"), "MockRegion")
				.withProperty(springSessionPropertyName("cache.server.region.shortcut"), "REPLICATE")
				.withProperty(springSessionPropertyName("session.serializer.bean-name"), "MockSessionSerializer");

			applicationContext.getEnvironment().getPropertySources().addFirst(springSessionGemFireProperties);

			return applicationContext;
		};
	}
 
Example #20
Source Project: spring-cloud-vault   Author: spring-cloud   File: LeasingVaultPropertySourceLocator.java    License: Apache License 2.0 6 votes vote down vote up
private PropertySource<?> createVaultPropertySource(RequestedSecret secret,
		SecretBackendMetadata accessor) {

	if (accessor instanceof LeasingSecretBackendMetadata) {
		((LeasingSecretBackendMetadata) accessor).beforeRegistration(secret,
				this.secretLeaseContainer);
	}

	LeaseAwareVaultPropertySource propertySource = new LeaseAwareVaultPropertySource(
			accessor.getName(), this.secretLeaseContainer, secret,
			accessor.getPropertyTransformer());

	if (accessor instanceof LeasingSecretBackendMetadata) {
		((LeasingSecretBackendMetadata) accessor).afterRegistration(secret,
				this.secretLeaseContainer);
	}

	return propertySource;
}
 
Example #21
Source Project: java-technology-stack   Author: codeEngraver   File: PropertySourcesPlaceholderConfigurerTests.java    License: MIT License 6 votes vote down vote up
@Test
public void withNonEnumerablePropertySource() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${foo}")
				.getBeanDefinition());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();

	PropertySource<?> ps = new PropertySource<Object>("simplePropertySource", new Object()) {
		@Override
		public Object getProperty(String key) {
			return "bar";
		}
	};

	MockEnvironment env = new MockEnvironment();
	env.getPropertySources().addFirst(ps);
	ppc.setEnvironment(env);

	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("bar"));
}
 
Example #22
Source Project: spring-cloud-commons   Author: spring-cloud   File: BootstrapApplicationListener.java    License: Apache License 2.0 6 votes vote down vote up
private void mergeDefaultProperties(MutablePropertySources environment,
		MutablePropertySources bootstrap) {
	String name = DEFAULT_PROPERTIES;
	if (bootstrap.contains(name)) {
		PropertySource<?> source = bootstrap.get(name);
		if (!environment.contains(name)) {
			environment.addLast(source);
		}
		else {
			PropertySource<?> target = environment.get(name);
			if (target instanceof MapPropertySource && target != source
					&& source instanceof MapPropertySource) {
				Map<String, Object> targetMap = ((MapPropertySource) target)
						.getSource();
				Map<String, Object> map = ((MapPropertySource) source).getSource();
				for (String key : map.keySet()) {
					if (!target.containsProperty(key)) {
						targetMap.put(key, map.get(key));
					}
				}
			}
		}
	}
	mergeAdditionalPropertySources(environment, bootstrap);
}
 
Example #23
Source Project: spring-cloud-commons   Author: spring-cloud   File: PropertySourceLocator.java    License: Apache License 2.0 6 votes vote down vote up
static Collection<PropertySource<?>> locateCollection(PropertySourceLocator locator,
		Environment environment) {
	PropertySource<?> propertySource = locator.locate(environment);
	if (propertySource == null) {
		return Collections.emptyList();
	}
	if (CompositePropertySource.class.isInstance(propertySource)) {
		Collection<PropertySource<?>> sources = ((CompositePropertySource) propertySource)
				.getPropertySources();
		List<PropertySource<?>> filteredSources = new ArrayList<>();
		for (PropertySource<?> p : sources) {
			if (p != null) {
				filteredSources.add(p);
			}
		}
		return filteredSources;
	}
	else {
		return Arrays.asList(propertySource);
	}
}
 
Example #24
Source Project: tutorials   Author: eugenp   File: JsonPropertyContextInitializer.java    License: MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
    try {
        Resource resource = configurableApplicationContext.getResource("classpath:configprops.json");
        Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
        Set<Map.Entry> set = readValue.entrySet();
        List<MapPropertySource> propertySources = convertEntrySet(set, Optional.empty());
        for (PropertySource propertySource : propertySources) {
            configurableApplicationContext.getEnvironment()
                .getPropertySources()
                .addFirst(propertySource);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #25
Source Project: spring-cloud-gray   Author: SpringCloud   File: SpringConfigurationPropertySources.java    License: Apache License 2.0 6 votes vote down vote up
private ConfigurationPropertySource fetchNext() {
    if (this.next == null) {
        if (this.iterators.isEmpty()) {
            return null;
        }
        if (!this.iterators.peek().hasNext()) {
            this.iterators.pop();
            return fetchNext();
        }
        PropertySource<?> candidate = this.iterators.peek().next();
        if (candidate.getSource() instanceof ConfigurableEnvironment) {
            push((ConfigurableEnvironment) candidate.getSource());
            return fetchNext();
        }
        if (isIgnored(candidate)) {
            return fetchNext();
        }
        this.next = this.adapter.apply(candidate);
    }
    return this.next;
}
 
Example #26
Source Project: spring-cloud-vault   Author: spring-cloud   File: VaultPropertySourceLocatorUnitTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLocatePropertySourcesInEachPathSpecifiedWhenApplicationNameContainsSeveral() {

	VaultKeyValueBackendProperties backendProperties = new VaultKeyValueBackendProperties();
	backendProperties.setApplicationName("wintermute,straylight,icebreaker/armitage");
	backendProperties.setProfiles(Arrays.asList("vermillion", "periwinkle"));

	this.propertySourceLocator = new VaultPropertySourceLocator(this.operations,
			new VaultProperties(),
			VaultPropertySourceLocatorSupport.createConfiguration(backendProperties));

	PropertySource<?> propertySource = this.propertySourceLocator
			.locate(this.configurableEnvironment);

	assertThat(propertySource).isInstanceOf(CompositePropertySource.class);

	CompositePropertySource composite = (CompositePropertySource) propertySource;
	assertThat(composite.getPropertySources()).extracting("name").contains(
			"secret/wintermute", "secret/straylight", "secret/icebreaker/armitage",
			"secret/wintermute/vermillion", "secret/wintermute/periwinkle",
			"secret/straylight/vermillion", "secret/straylight/periwinkle",
			"secret/icebreaker/armitage/vermillion",
			"secret/icebreaker/armitage/periwinkle");
}
 
Example #27
Source Project: spring-cloud-gray   Author: SpringCloud   File: SpringConfigurationPropertySource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link SpringConfigurationPropertySource} implementation.
 *
 * @param propertySource       the source property source
 * @param mapper               the property mapper
 * @param containsDescendantOf function used to implement
 *                             {@link #containsDescendantOf(ConfigurationPropertyName)} (may be {@code null})
 */
SpringConfigurationPropertySource(PropertySource<?> propertySource,
                                  PropertyMapper mapper,
                                  Function<ConfigurationPropertyName, ConfigurationPropertyState> containsDescendantOf) {
    Assert.notNull(propertySource, "PropertySource must not be null");
    Assert.notNull(mapper, "Mapper must not be null");
    this.propertySource = propertySource;
    this.mapper = (mapper instanceof DelegatingPropertyMapper) ? mapper
            : new DelegatingPropertyMapper(mapper);
    this.containsDescendantOf = (containsDescendantOf != null) ? containsDescendantOf
            : (n) -> ConfigurationPropertyState.UNKNOWN;
}
 
Example #28
Source Project: spring-cloud-vault   Author: spring-cloud   File: VaultPropertySourceLocatorSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link CompositePropertySource}.
 * @param environment must not be {@literal null}.
 * @return the composite {@link PropertySource}.
 */
protected CompositePropertySource createCompositePropertySource(
		Environment environment) {

	List<PropertySource<?>> propertySources = doCreatePropertySources(environment);

	return doCreateCompositePropertySource(this.propertySourceName, propertySources);
}
 
Example #29
Source Project: spring-cloud-services-connector   Author: pivotal-cf   File: EurekaServiceConnector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected PropertySource<?> toPropertySource(EurekaServiceInfo eurekaServiceInfo) {
	Map<String, Object> map = new LinkedHashMap<>();
	map.put(EUREKA_CLIENT + "serviceUrl.defaultZone", eurekaServiceInfo.getUri() + EUREKA_API_PREFIX);
	map.put(EUREKA_CLIENT + "region", DEFAULT_REGION);
	map.put(EUREKA_CLIENT_OAUTH2 + "clientId", eurekaServiceInfo.getClientId());
	map.put(EUREKA_CLIENT_OAUTH2 + "clientSecret", eurekaServiceInfo.getClientSecret());
	map.put(EUREKA_CLIENT_OAUTH2 + "accessTokenUri", eurekaServiceInfo.getAccessTokenUri());
	return new MapPropertySource(PROPERTY_SOURCE_NAME, map);
}
 
Example #30
Source Project: spring-context-support   Author: alibaba   File: PropertySourcesUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get prefixed {@link Properties}
 *
 * @param propertySources  {@link PropertySources}
 * @param propertyResolver {@link PropertyResolver} to resolve the placeholder if present
 * @param prefix           the prefix of property name
 * @return Map
 * @see Properties
 * @since 1.0.3
 */
public static Map<String, Object> getSubProperties(PropertySources propertySources, PropertyResolver propertyResolver, String prefix) {

    Map<String, Object> subProperties = new LinkedHashMap<String, Object>();

    String normalizedPrefix = normalizePrefix(prefix);

    Iterator<PropertySource<?>> iterator = propertySources.iterator();

    while (iterator.hasNext()) {
        PropertySource<?> source = iterator.next();
        if (source instanceof EnumerablePropertySource) {
            for (String name : ((EnumerablePropertySource<?>) source).getPropertyNames()) {
                if (!subProperties.containsKey(name) && name.startsWith(normalizedPrefix)) {
                    String subName = name.substring(normalizedPrefix.length());
                    if (!subProperties.containsKey(subName)) { // take first one
                        Object value = source.getProperty(name);
                        if (value instanceof String) {
                            // Resolve placeholder
                            value = propertyResolver.resolvePlaceholders((String) value);
                        }
                        subProperties.put(subName, value);
                    }
                }
            }
        }
    }

    return unmodifiableMap(subProperties);
}