org.springframework.core.env.MapPropertySource

Here are the examples of the java api org.springframework.core.env.MapPropertySource taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

79 Examples 7

19 Source : SpringBootTestRandomPortEnvironmentPostProcessorTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndSameInProduction() {
    addTestPropertySource("0", null);
    Map<String, Object> other = new HashMap<>();
    other.put("server.port", "8081");
    other.put("management.server.port", "8081");
    MapPropertySource otherSource = new MapPropertySource("other", other);
    this.propertySources.addLast(otherSource);
    this.postProcessor.postProcessEnvironment(this.environment, null);
    replacedertThat(this.environment.getProperty("server.port")).isEqualTo("0");
    replacedertThat(this.environment.getProperty("management.server.port")).isEqualTo("");
}

19 Source : SpringBootTestRandomPortEnvironmentPostProcessorTests.java
with Apache License 2.0
from yuanmabiji

private void addTestPropertySource(String serverPort, String managementPort) {
    Map<String, Object> source = new HashMap<>();
    source.put("server.port", serverPort);
    source.put("management.server.port", managementPort);
    MapPropertySource inlineTestSource = new MapPropertySource(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME, source);
    this.propertySources.addFirst(inlineTestSource);
}

19 Source : SpringBootTestRandomPortEnvironmentPostProcessor.java
with Apache License 2.0
from yuanmabiji

private boolean isTestServerPortFixed(MapPropertySource source, ConversionService conversionService) {
    return !Integer.valueOf(0).equals(getPropertyAsInteger(source, SERVER_PORT_PROPERTY, conversionService));
}

19 Source : PropertySourceOriginTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void toStringShouldShowDetails() {
    MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>());
    PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo");
    replacedertThat(origin.toString()).isEqualTo("\"foo\" from property source \"test\"");
}

19 Source : PropertySourceOriginTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void getPropertyNameShouldReturnPropertyName() {
    MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>());
    PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo");
    replacedertThat(origin.getPropertyName()).isEqualTo("foo");
}

19 Source : PropertySourceOriginTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void getPropertySourceShouldReturnPropertySource() {
    MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>());
    PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo");
    replacedertThat(origin.getPropertySource()).isEqualTo(propertySource);
}

19 Source : PropertySourceOriginTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void getWhenPropertySourceIsNotOriginAwareShouldWrap() {
    MapPropertySource propertySource = new MapPropertySource("test", new HashMap<>());
    PropertySourceOrigin origin = new PropertySourceOrigin(propertySource, "foo");
    replacedertThat(origin.getPropertySource()).isEqualTo(propertySource);
    replacedertThat(origin.getPropertyName()).isEqualTo("foo");
}

19 Source : SpringConfigurationPropertySourcesTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void shouldTrackChanges() {
    MutablePropertySources sources = new MutablePropertySources();
    SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources(sources);
    replacedertThat(configurationSources.iterator()).hreplacedize(0);
    MapPropertySource source1 = new MapPropertySource("test1", Collections.singletonMap("a", "b"));
    sources.addLast(source1);
    replacedertThat(configurationSources.iterator()).hreplacedize(1);
    MapPropertySource source2 = new MapPropertySource("test2", Collections.singletonMap("b", "c"));
    sources.addLast(source2);
    replacedertThat(configurationSources.iterator()).hreplacedize(2);
}

19 Source : PropertySourceAnnotationTests.java
with MIT License
from Vip-Augus

@Test
public void orderingDoesntReplaceExisting() throws Exception {
    // SPR-12198: mySource should 'win' as it was registered manually
    AnnotationConfigApplicationContext ctxWithoutName = new AnnotationConfigApplicationContext();
    MapPropertySource mySource = new MapPropertySource("mine", Collections.singletonMap("testbean.name", "myTestBean"));
    ctxWithoutName.getEnvironment().getPropertySources().addLast(mySource);
    ctxWithoutName.register(ConfigWithFourResourceLocations.clreplaced);
    ctxWithoutName.refresh();
    replacedertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name"), equalTo("myTestBean"));
}

19 Source : ConfigurationChangeDetectorTest.java
with Apache License 2.0
from spring-cloud

@Test
public void testChangedLeftNonNullRightNull() {
    MapPropertySource left = new MapPropertySource("leftNonNull", Collections.emptyMap());
    boolean changed = stub.changed(left, null);
    replacedert.replacedertTrue(changed);
}

19 Source : ConfigurationChangeDetectorTest.java
with Apache License 2.0
from spring-cloud

@Test
public void testChangedLeftNullRightNonNull() {
    MapPropertySource right = new MapPropertySource("rightNonNull", Collections.emptyMap());
    boolean changed = stub.changed(null, right);
    replacedert.replacedertTrue(changed);
}

19 Source : ConfigurationChangeDetectorTest.java
with Apache License 2.0
from spring-cloud

@Test
public void testChangedNonEqualMaps() {
    Object value = new Object();
    Map<String, Object> leftMap = new HashMap<>();
    leftMap.put("key", value);
    leftMap.put("anotherKey", value);
    Map<String, Object> rightMap = new HashMap<>();
    rightMap.put("key", value);
    MapPropertySource left = new MapPropertySource("left", leftMap);
    MapPropertySource right = new MapPropertySource("right", rightMap);
    boolean changed = stub.changed(left, right);
    replacedert.replacedertTrue(changed);
}

19 Source : ConfigurationChangeDetectorTest.java
with Apache License 2.0
from spring-cloud

@Test
public void testChangedEqualMaps() {
    Object value = new Object();
    Map<String, Object> leftMap = new HashMap<>();
    leftMap.put("key", value);
    Map<String, Object> rightMap = new HashMap<>();
    rightMap.put("key", value);
    MapPropertySource left = new MapPropertySource("left", leftMap);
    MapPropertySource right = new MapPropertySource("right", rightMap);
    boolean changed = stub.changed(left, right);
    replacedert.replacedertFalse(changed);
}

19 Source : SofaBootstrapRunListener.java
with Apache License 2.0
from sofastack

/**
 * @author qilong.zql
 * @since 3.0.0
 */
public clreplaced SofaBootstrapRunListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {

    private static AtomicBoolean executed = new AtomicBoolean(false);

    private final static MapPropertySource HIGH_PRIORITY_CONFIG = new MapPropertySource(SofaBootConstants.SOFA_HIGH_PRIORITY_CONFIG, new HashMap<>());

    /**
     * config log settings
     */
    private void replacedemblyLogSetting(ConfigurableEnvironment environment) {
        StreamSupport.stream(environment.getPropertySources().spliterator(), false).filter(propertySource -> propertySource instanceof EnumerablePropertySource).map(propertySource -> Arrays.asList(((EnumerablePropertySource) propertySource).getPropertyNames())).flatMap(Collection::stream).filter(LogEnvUtils::isSofaCommonLoggingConfig).forEach((key) -> HIGH_PRIORITY_CONFIG.getSource().put(key, environment.getProperty(key)));
    }

    /**
     * config required properties
     * @param environment
     */
    private void replacedemblyRequireProperties(ConfigurableEnvironment environment) {
        if (StringUtils.hasText(environment.getProperty(SofaBootConstants.APP_NAME_KEY))) {
            HIGH_PRIORITY_CONFIG.getSource().put(SofaBootConstants.APP_NAME_KEY, environment.getProperty(SofaBootConstants.APP_NAME_KEY));
        }
    }

    /**
     * Mark this environment as SOFA bootstrap environment
     * @param environment
     */
    private void replacedemblyEnvironmentMark(ConfigurableEnvironment environment) {
        environment.getPropertySources().addFirst(new MapPropertySource(SofaBootConstants.SOFA_BOOTSTRAP, new HashMap<>()));
    }

    /**
     * Un-Mark this environment as SOFA bootstrap environment
     * @param environment
     */
    private void unreplacedemblyEnvironmentMark(ConfigurableEnvironment environment) {
        environment.getPropertySources().remove(SofaBootConstants.SOFA_BOOTSTRAP);
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }

    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        SpringApplication application = event.getSpringApplication();
        if (SofaBootEnvUtils.isSpringCloud() && executed.compareAndSet(false, true)) {
            StandardEnvironment bootstrapEnvironment = new StandardEnvironment();
            StreamSupport.stream(environment.getPropertySources().spliterator(), false).filter(source -> !(source instanceof PropertySource.StubPropertySource)).forEach(source -> bootstrapEnvironment.getPropertySources().addLast(source));
            List<Clreplaced> sources = new ArrayList<>();
            for (Object s : application.getAllSources()) {
                if (s instanceof Clreplaced) {
                    sources.add((Clreplaced) s);
                } else if (s instanceof String) {
                    sources.add(ClreplacedUtils.resolveClreplacedName((String) s, null));
                }
            }
            SpringApplication bootstrapApplication = new SpringApplicationBuilder().profiles(environment.getActiveProfiles()).bannerMode(Banner.Mode.OFF).environment(bootstrapEnvironment).sources(sources.toArray(new Clreplaced[] {})).registerShutdownHook(false).logStartupInfo(false).web(WebApplicationType.NONE).listeners().initializers().build(event.getArgs());
            ApplicationEnvironmentPreparedEvent bootstrapEvent = new ApplicationEnvironmentPreparedEvent(bootstrapApplication, event.getArgs(), bootstrapEnvironment);
            application.getListeners().stream().filter(listener -> listener instanceof ConfigFileApplicationListener).forEach(listener -> ((ConfigFileApplicationListener) listener).onApplicationEvent(bootstrapEvent));
            replacedemblyLogSetting(bootstrapEnvironment);
            replacedemblyRequireProperties(bootstrapEnvironment);
            replacedemblyEnvironmentMark(environment);
        } else {
            unreplacedemblyEnvironmentMark(environment);
        }
        if (environment.getPropertySources().contains(SofaBootConstants.SPRING_CLOUD_BOOTSTRAP)) {
            environment.getPropertySources().addLast(HIGH_PRIORITY_CONFIG);
        }
    }
}

19 Source : PropertySourcesUtilsTest.java
with Apache License 2.0
from smallFive55

@Test
public void testGetSubProperties() {
    MutablePropertySources propertySources = new MutablePropertySources();
    Map<String, Object> source = new HashMap<String, Object>();
    Map<String, Object> source2 = new HashMap<String, Object>();
    MapPropertySource propertySource = new MapPropertySource("propertySource", source);
    MapPropertySource propertySource2 = new MapPropertySource("propertySource2", source2);
    propertySources.addLast(propertySource);
    propertySources.addLast(propertySource2);
    Map<String, Object> result = PropertySourcesUtils.getSubProperties(propertySources, "user");
    replacedert.replacedertEquals(Collections.emptyMap(), result);
    source.put("age", "31");
    source.put("user.name", "Mercy");
    source.put("user.age", "${age}");
    source2.put("user.name", "mercyblitz");
    source2.put("user.age", "32");
    Map<String, Object> expected = new HashMap<String, Object>();
    expected.put("name", "Mercy");
    expected.put("age", "31");
    result = PropertySourcesUtils.getSubProperties(propertySources, "user");
    replacedert.replacedertEquals(expected, result);
    result = PropertySourcesUtils.getSubProperties(propertySources, "");
    replacedert.replacedertEquals(Collections.emptyMap(), result);
    result = PropertySourcesUtils.getSubProperties(propertySources, "no-exists");
    replacedert.replacedertEquals(Collections.emptyMap(), result);
}

18 Source : InvalidConfigurationPropertyValueFailureAnalyzerTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void replacedysisWithKnownProperty() {
    MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid"));
    this.environment.getPropertySources().addFirst(OriginCapablePropertySource.get(source));
    InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException("test.property", "invalid", "This is not valid.");
    Failurereplacedysis replacedysis = performreplacedysis(failure);
    replacedertCommonParts(failure, replacedysis);
    replacedertThat(replacedysis.getAction()).contains("Review the value of the property with the provided reason.");
    replacedertThat(replacedysis.getDescription()).contains("Validation failed for the following reason").contains("This is not valid.").doesNotContain("Additionally, this property is also set");
}

18 Source : InvalidConfigurationPropertyValueFailureAnalyzerTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void replacedysisWithKnownPropertyAndOtherCandidates() {
    MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid"));
    MapPropertySource additional = new MapPropertySource("additional", Collections.singletonMap("test.property", "valid"));
    MapPropertySource another = new MapPropertySource("another", Collections.singletonMap("test.property", "test"));
    this.environment.getPropertySources().addFirst(OriginCapablePropertySource.get(source));
    this.environment.getPropertySources().addLast(additional);
    this.environment.getPropertySources().addLast(OriginCapablePropertySource.get(another));
    InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException("test.property", "invalid", "This is not valid.");
    Failurereplacedysis replacedysis = performreplacedysis(failure);
    replacedertCommonParts(failure, replacedysis);
    replacedertThat(replacedysis.getAction()).contains("Review the value of the property with the provided reason.");
    replacedertThat(replacedysis.getDescription()).contains("Additionally, this property is also set in the following " + "property sources:").contains("In 'additional' with the value 'valid'").contains("In 'another' with the value 'test' (originating from 'TestOrigin test.property')");
}

18 Source : InvalidConfigurationPropertyValueFailureAnalyzerTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void replacedysisWithKnownPropertyAndNoReason() {
    MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid"));
    this.environment.getPropertySources().addFirst(OriginCapablePropertySource.get(source));
    InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException("test.property", "invalid", null);
    Failurereplacedysis replacedysis = performreplacedysis(failure);
    replacedertThat(replacedysis.getAction()).contains("Review the value of the property.");
    replacedertThat(replacedysis.getDescription()).contains("No reason was provided.").doesNotContain("Additionally, this property is also set");
}

18 Source : SpringConfigurationPropertySourcesTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void shouldTrackWhenSourceHasIdenticalName() {
    MutablePropertySources sources = new MutablePropertySources();
    SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources(sources);
    ConfigurationPropertyName name = ConfigurationPropertyName.of("a");
    MapPropertySource source1 = new MapPropertySource("test", Collections.singletonMap("a", "s1"));
    sources.addLast(source1);
    replacedertThat(configurationSources.iterator().next().getConfigurationProperty(name).getValue()).isEqualTo("s1");
    MapPropertySource source2 = new MapPropertySource("test", Collections.singletonMap("a", "s2"));
    sources.remove("test");
    sources.addLast(source2);
    replacedertThat(configurationSources.iterator().next().getConfigurationProperty(name).getValue()).isEqualTo("s2");
}

18 Source : ConfigFileApplicationListenerTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void addBeforeDefaultProperties() {
    MapPropertySource defaultSource = new MapPropertySource("defaultProperties", Collections.singletonMap("the.property", "fromdefaultproperties"));
    this.environment.getPropertySources().addFirst(defaultSource);
    this.initializer.setSearchNames("testproperties");
    this.initializer.postProcessEnvironment(this.environment, this.application);
    String property = this.environment.getProperty("the.property");
    replacedertThat(property).isEqualTo("frompropertiesfile");
}

18 Source : SelfDiscoveryPropertySourceLocator.java
with GNU Lesser General Public License v2.1
from Verdoso

@Override
public PropertySource<?> locate(Environment environment) {
    MapPropertySource result = new MapPropertySource("SelfDiscoveredProperty", Collections.emptyMap());
    try {
        String localhostName = InetAddress.getLocalHost().getCanonicalHostName();
        if (localhostName != null) {
            String hostname = localhostName.toLowerCase();
            log.info("Setting hostname to {}", hostname);
            result = new MapPropertySource("SelfDiscoveredProperty", Collections.<String, Object>singletonMap("spring.cloud.consul.discovery.hostname", hostname));
        }
    } catch (UnknownHostException e) {
        log.error("Error obtaining localhost name", e);
    }
    return result;
}

18 Source : ConfigurationChangeDetector.java
with Apache License 2.0
from spring-cloud

/**
 * Determines if two property sources are different.
 * @param left left map property sources
 * @param right right map property sources
 * @return {@code true} if source has changed
 */
public boolean changed(MapPropertySource left, MapPropertySource right) {
    if (left == right) {
        return false;
    }
    if (left == null || right == null) {
        return true;
    }
    Map<String, Object> leftMap = left.getSource();
    Map<String, Object> rightMap = right.getSource();
    return !Objects.equals(leftMap, rightMap);
}

18 Source : PropertySourceAnnotationTests.java
with Apache License 2.0
from SourceHot

@Test
public void orderingDoesntReplaceExisting() throws Exception {
    // SPR-12198: mySource should 'win' as it was registered manually
    AnnotationConfigApplicationContext ctxWithoutName = new AnnotationConfigApplicationContext();
    MapPropertySource mySource = new MapPropertySource("mine", Collections.singletonMap("testbean.name", "myTestBean"));
    ctxWithoutName.getEnvironment().getPropertySources().addLast(mySource);
    ctxWithoutName.register(ConfigWithFourResourceLocations.clreplaced);
    ctxWithoutName.refresh();
    replacedertThat(ctxWithoutName.getEnvironment().getProperty("testbean.name")).isEqualTo("myTestBean");
}

18 Source : ProxyTest.java
with Apache License 2.0
from ppdaicorp

@PostConstruct
void init() {
    MapPropertySource mapPropertySource = new MapPropertySource("ProxyTest", property);
    env1.getPropertySources().addFirst(mapPropertySource);
    property.put("mq.proxy.data", "");
    property.put("mq.rb.times", "1");
    metaHelper = new MetaHelper(env1.getProperty("mq.portal.url"));
}

18 Source : LifecycleEnvironmentAware.java
with Apache License 2.0
from jufeng98

@Override
public void setEnvironment(Environment environment) {
    MutablePropertySources mutablePropertySources = ((ConfigurableEnvironment) environment).getPropertySources();
    Map<String, Object> map = new HashMap<>(1, 1);
    map.put("welcome", "helloWorld");
    MapPropertySource mapPropertySource = new MapPropertySource("customizePropertySource", map);
    mutablePropertySources.addLast(mapPropertySource);
    log.info("setEnvironment invoke:{}", environment.getClreplaced().getName());
}

18 Source : PropertySourcesUtilsTest.java
with Apache License 2.0
from boomblog

@Test
public void testGetSubProperties() {
    MutablePropertySources propertySources = new MutablePropertySources();
    Map<String, Object> source = new HashMap<String, Object>();
    MapPropertySource propertySource = new MapPropertySource("test", source);
    propertySources.addFirst(propertySource);
    String KEY_PREFIX = "user";
    String KEY_NAME = "name";
    String KEY_AGE = "age";
    Map<String, String> result = PropertySourcesUtils.getSubProperties(propertySources, KEY_PREFIX);
    replacedertions.replacedertEquals(Collections.emptyMap(), result);
    source.put(KEY_PREFIX + "." + KEY_NAME, "Mercy");
    source.put(KEY_PREFIX + "." + KEY_AGE, 31);
    Map<String, Object> expected = new HashMap<String, Object>();
    expected.put(KEY_NAME, "Mercy");
    expected.put(KEY_AGE, "31");
    result = PropertySourcesUtils.getSubProperties(propertySources, KEY_PREFIX);
    replacedertions.replacedertEquals(expected, result);
    result = PropertySourcesUtils.getSubProperties(propertySources, "");
    replacedertions.replacedertEquals(Collections.emptyMap(), result);
    result = PropertySourcesUtils.getSubProperties(propertySources, "no-exists");
    replacedertions.replacedertEquals(Collections.emptyMap(), result);
    source.put(KEY_PREFIX + ".app.name", "${info.name}");
    source.put("info.name", "Hello app");
    result = PropertySourcesUtils.getSubProperties(propertySources, KEY_PREFIX);
    String appName = result.get("app.name");
    replacedertions.replacedertEquals("Hello app", appName);
}

18 Source : EnvironmentUtilsTest.java
with Apache License 2.0
from apache

@Test
public void testExtraProperties() {
    System.setProperty("user.name", "mercyblitz");
    StandardEnvironment environment = new StandardEnvironment();
    Map<String, Object> map = new HashMap<>();
    map.put("user.name", "Mercy");
    MapPropertySource propertySource = new MapPropertySource("first", map);
    CompositePropertySource compositePropertySource = new CompositePropertySource("comp");
    compositePropertySource.addFirstPropertySource(propertySource);
    MutablePropertySources propertySources = environment.getPropertySources();
    propertySources.addFirst(compositePropertySource);
    Map<String, Object> properties = EnvironmentUtils.extractProperties(environment);
    replacedert.replacedertEquals("Mercy", properties.get("user.name"));
}

17 Source : EnvironmentUtils.java
with Apache License 2.0
from spinnaker

public static void registerPropertySource(String name, ConfigurableEnvironment environment, Map<String, Object> map) {
    MapPropertySource propertySource = new MapPropertySource(name, map);
    environment.getPropertySources().addFirst(propertySource);
}

17 Source : SofaArkEmbedAppInitializer.java
with Apache License 2.0
from sofastack

@Override
public void initialize(ConfigurableApplicationContext ctx) {
    if (!APP_NAME_SET.add(appName)) {
        throw new IllegalStateException("same appName " + appName + " can only be used once!");
    }
    ConfigurableEnvironment cenv = ctx.getEnvironment();
    MutablePropertySources mps = cenv.getPropertySources();
    MapPropertySource lookoutallSubView = getLookoutAllSubView();
    if (lookoutallSubView != null) {
        mps.addFirst(lookoutallSubView);
    }
    String prefix = appName + ".";
    MapPropertySource env = new MapPropertySource("sofaark-environment", EnvUtils.getEnvSubView(prefix));
    mps.addFirst(env);
    MapPropertySource sd = new MapPropertySource("sofaark-systemProperties", EnvUtils.getSystemPropertySubView(prefix));
    mps.addFirst(sd);
}

17 Source : EnvironmentUtils.java
with Apache License 2.0
from purgeteam

public static void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map, String propertySourceName) {
    MapPropertySource target = null;
    if (propertySources.contains(propertySourceName)) {
        PropertySource<?> source = propertySources.get(propertySourceName);
        if (source instanceof MapPropertySource) {
            target = (MapPropertySource) source;
            for (String key : map.keySet()) {
                if (!target.containsProperty(key)) {
                    target.getSource().put(key, map.get(key));
                }
            }
        }
    }
    if (target == null) {
        target = new MapPropertySource(propertySourceName, map);
    }
    if (!propertySources.contains(propertySourceName)) {
        propertySources.addLast(target);
    }
}

17 Source : MyPropertySourceProvider.java
with MIT License
from JavaZakariae

@Override
public void setEnvironment(Environment environment) {
    Map<String, Object> newEnvironementVariables = new HashMap<>();
    newEnvironementVariables.put("July", 7);
    newEnvironementVariables.put("out", 8);
    newEnvironementVariables.put("September", 9);
    newEnvironementVariables.put("Ocober", 10);
    MapPropertySource sourceProvider = new MapPropertySource("newEnvironementVariables", newEnvironementVariables);
    ((StandardEnvironment) environment).getPropertySources().addLast(sourceProvider);
    System.out.println(environment.getProperty("July"));
// System.out.println(environment.getProperty("belgium.brussels.street"));
}

17 Source : PropertySourcesUtilsTest.java
with Apache License 2.0
from alibaba

@Test
public void testGetSubProperties() {
    ConfigurableEnvironment environment = new AbstractEnvironment() {
    };
    MutablePropertySources propertySources = environment.getPropertySources();
    Map<String, Object> source = new HashMap<String, Object>();
    Map<String, Object> source2 = new HashMap<String, Object>();
    MapPropertySource propertySource = new MapPropertySource("propertySource", source);
    MapPropertySource propertySource2 = new MapPropertySource("propertySource2", source2);
    propertySources.addLast(propertySource);
    propertySources.addLast(propertySource2);
    Map<String, Object> result = getSubProperties(propertySources, "user");
    replacedertEquals(Collections.emptyMap(), result);
    source.put("age", "31");
    source.put("user.name", "Mercy");
    source.put("user.age", "${age}");
    source2.put("user.name", "mercyblitz");
    source2.put("user.age", "32");
    Map<String, Object> expected = new HashMap<String, Object>();
    expected.put("name", "Mercy");
    expected.put("age", "31");
    replacedertEquals(expected, getSubProperties((Iterable) propertySources, "user"));
    replacedertEquals(expected, getSubProperties(environment, "user"));
    replacedertEquals(expected, getSubProperties(propertySources, "user"));
    replacedertEquals(expected, getSubProperties(propertySources, environment, "user"));
    result = getSubProperties(propertySources, "");
    replacedertEquals(Collections.emptyMap(), result);
    result = getSubProperties(propertySources, "no-exists");
    replacedertEquals(Collections.emptyMap(), result);
}

17 Source : RocketMQBusEnvironmentPostProcessor.java
with Apache License 2.0
from alibaba

/**
 * Copy from.
 * {@link BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map)}
 * @param propertySources {@link MutablePropertySources}
 * @param map Default RocketMQ Bus Properties
 */
private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
    MapPropertySource target = null;
    if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
        PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
        if (source instanceof MapPropertySource) {
            target = (MapPropertySource) source;
            for (String key : map.keySet()) {
                if (!target.containsProperty(key)) {
                    target.getSource().put(key, map.get(key));
                }
            }
        }
    }
    if (target == null) {
        target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
    }
    if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
        propertySources.addLast(target);
    }
}

16 Source : SpringBootTestRandomPortEnvironmentPostProcessor.java
with Apache License 2.0
from yuanmabiji

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    MapPropertySource source = (MapPropertySource) environment.getPropertySources().get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME);
    if (source == null || isTestServerPortFixed(source, environment.getConversionService()) || isTestManagementPortConfigured(source)) {
        return;
    }
    Integer managementPort = getPropertyAsInteger(environment, MANAGEMENT_PORT_PROPERTY, null);
    if (managementPort == null || managementPort.equals(-1)) {
        return;
    }
    Integer serverPort = getPropertyAsInteger(environment, SERVER_PORT_PROPERTY, 8080);
    if (!managementPort.equals(serverPort)) {
        source.getSource().put(MANAGEMENT_PORT_PROPERTY, "0");
    } else {
        source.getSource().put(MANAGEMENT_PORT_PROPERTY, "");
    }
}

16 Source : ConfigurationBrusher.java
with MIT License
from Toparvion

private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
    MapPropertySource target = null;
    if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
        PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
        if (source instanceof MapPropertySource) {
            target = (MapPropertySource) source;
            for (String key : map.keySet()) {
                if (!target.containsProperty(key)) {
                    target.getSource().put(key, map.get(key));
                }
            }
        }
    }
    if (target == null) {
        target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
    }
    if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
        propertySources.addLast(target);
    }
}

16 Source : CustomRuntimeEnvironmentPostProcessor.java
with Apache License 2.0
from spring-cloud

private Map<String, Object> getDefaultProperties(ConfigurableEnvironment environment) {
    if (environment.getPropertySources().contains("defaultProperties")) {
        MapPropertySource source = (MapPropertySource) environment.getPropertySources().get("defaultProperties");
        return source.getSource();
    }
    HashMap<String, Object> map = new HashMap<String, Object>();
    environment.getPropertySources().addLast(new MapPropertySource("defaultProperties", map));
    return map;
}

16 Source : KeycloakContainerFactory.java
with MIT License
from Playtika

private void registerKeycloakEnvironment(KeycloakContainer keycloak) {
    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
    map.put("embedded.keycloak.host", keycloak.getIp());
    map.put("embedded.keycloak.http-port", keycloak.getHttpPort());
    map.put("embedded.keycloak.auth-server-url", keycloak.getAuthServerUrl());
    log.info("Started Keycloak server. Connection details: {}", map);
    MapPropertySource propertySource = new MapPropertySource("embeddedKeycloakInfo", map);
    environment.getPropertySources().addFirst(propertySource);
}

16 Source : ExtendPropertySourcesRunListener.java
with Apache License 2.0
from mercyblitz

@Override
public void contextPrepared(ConfigurableApplicationContext context) {
    // 从 ConfigurableApplicationContext 获取 ConfigurableEnvironment
    ConfigurableEnvironment environment = context.getEnvironment();
    Map<String, Object> source = new HashMap<>();
    // 内部化配置设置 user.name 属性
    source.put("user.name", "mercyblitz 2018");
    MapPropertySource mapPropertySource = new MapPropertySource("contextPrepared", source);
    environment.getPropertySources().addFirst(mapPropertySource);
}

16 Source : DubboDefaultPropertiesEnvironmentPostProcessor.java
with Apache License 2.0
from apache

/**
 * Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map)
 *
 * @param propertySources {@link MutablePropertySources}
 * @param map             Default Dubbo Properties
 */
private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
    MapPropertySource target = null;
    if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
        PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
        if (source instanceof MapPropertySource) {
            target = (MapPropertySource) source;
            for (String key : map.keySet()) {
                if (!target.containsProperty(key)) {
                    target.getSource().put(key, map.get(key));
                }
            }
        }
    }
    if (target == null) {
        target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
    }
    if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
        propertySources.addLast(target);
    }
}

16 Source : DubboNonWebApplicationEnvironmentPostProcessor.java
with Apache License 2.0
from alibaba

/**
 * Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map).
 * @param propertySources {@link MutablePropertySources}
 * @param map Default Dubbo Properties
 */
private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
    MapPropertySource target = null;
    if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
        PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
        if (source instanceof MapPropertySource) {
            target = (MapPropertySource) source;
            for (String key : map.keySet()) {
                if (!target.containsProperty(key)) {
                    target.getSource().put(key, map.get(key));
                }
            }
        }
    }
    if (target == null) {
        target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
    }
    if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
        propertySources.addLast(target);
    }
}

15 Source : EnvUtils.java
with MIT License
from Playtika

static Map<String, Object> registerRedisEnvironment(ConfigurableEnvironment environment, GenericContainer redis, RedisProperties properties, int port) {
    String host = redis.getContainerIpAddress();
    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
    map.put("embedded.redis.port", port);
    map.put("embedded.redis.host", host);
    map.put("embedded.redis.preplacedword", properties.getPreplacedword());
    map.put("embedded.redis.user", properties.getUser());
    MapPropertySource propertySource = new MapPropertySource("embeddedRedisInfo", map);
    environment.getPropertySources().addFirst(propertySource);
    return map;
}

15 Source : EmbeddedLocalStackBootstrapConfiguration.java
with MIT License
from Playtika

private void registerLocalStackEnvironment(EmbeddedLocalStackContainer localStack, ConfigurableEnvironment environment, LocalStackProperties properties) {
    String host = localStack.getContainerIpAddress();
    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
    map.put("embedded.localstack.host", host);
    map.put("embedded.localstack.accessKey", localStack.getAccessKey());
    map.put("embedded.localstack.secretKey", localStack.getSecretKey());
    map.put("embedded.localstack.region", localStack.getRegion());
    String prefix = "embedded.localstack.";
    for (LocalStackContainer.Service service : properties.services) {
        map.put(prefix + service, localStack.getEndpointConfiguration(service).getServiceEndpoint());
        map.put(prefix + service + ".port", localStack.getMappedPort(service.getPort()));
    }
    log.info("Started Localstack. Connection details: {}", map);
    MapPropertySource propertySource = new MapPropertySource("embeddedLocalstackInfo", map);
    environment.getPropertySources().addFirst(propertySource);
    setSystemProperties(localStack);
}

15 Source : EmbeddedInfluxDBBootstrapConfiguration.java
with MIT License
from Playtika

private void registerInfluxEnvironment(ConcreteInfluxDbContainer influx, ConfigurableEnvironment environment, InfluxDBProperties properties) {
    Integer mappedPort = influx.getMappedPort(properties.getPort());
    String host = influx.getContainerIpAddress();
    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
    map.put("embedded.influxdb.port", mappedPort);
    map.put("embedded.influxdb.host", host);
    map.put("embedded.influxdb.database", properties.getDatabase());
    map.put("embedded.influxdb.user", properties.getUser());
    map.put("embedded.influxdb.preplacedword", properties.getPreplacedword());
    String influxDBURL = "http://{}:{}";
    log.info("Started InfluxDB server. Connection details: {}, " + "HTTP connection url: " + influxDBURL, map, host, mappedPort);
    MapPropertySource propertySource = new MapPropertySource("embeddedInfluxDBInfo", map);
    environment.getPropertySources().addFirst(propertySource);
}

15 Source : EmbeddedDynamoDBBootstrapConfiguration.java
with MIT License
from Playtika

private void registerDynamodbEnvironment(GenericContainer container, ConfigurableEnvironment environment, DynamoDBProperties properties) {
    Integer mappedPort = container.getMappedPort(properties.port);
    String host = container.getContainerIpAddress();
    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
    map.put("embedded.dynamodb.port", mappedPort);
    map.put("embedded.dynamodb.host", host);
    map.put("embedded.dynamodb.accessKey", properties.getAccessKey());
    map.put("embedded.dynamodb.secretKey", properties.getSecretKey());
    log.info("Started DynamoDb server. Connection details: {}, ", map);
    log.info("Consult with the doc " + "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.UsageNotes.html " + "for more details");
    MapPropertySource propertySource = new MapPropertySource("embeddedDynamodbInfo", map);
    environment.getPropertySources().addFirst(propertySource);
}

15 Source : EmbeddedClickHouseBootstrapConfiguration.java
with MIT License
from Playtika

private void registerClickHouseEnvironment(ConcreteClickHouseContainer clickHouseContainer, ConfigurableEnvironment environment, ClickHouseProperties properties) {
    Integer mappedPort = clickHouseContainer.getMappedPort(properties.port);
    String host = clickHouseContainer.getContainerIpAddress();
    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
    map.put("embedded.clickhouse.schema", "default");
    map.put("embedded.clickhouse.host", host);
    map.put("embedded.clickhouse.port", mappedPort);
    map.put("embedded.clickhouse.user", clickHouseContainer.getUsername());
    map.put("embedded.clickhouse.preplacedword", clickHouseContainer.getPreplacedword());
    log.info("Started ClickHouse server. Connection details: {}", map);
    MapPropertySource propertySource = new MapPropertySource("embeddedClickHouseInfo", map);
    environment.getPropertySources().addFirst(propertySource);
}

15 Source : EmbeddedCassandraBootstrapConfiguration.java
with MIT License
from Playtika

static Map<String, Object> registerCreplacedandraEnvironment(ConfigurableEnvironment environment, CreplacedandraContainer creplacedandra, CreplacedandraProperties properties) {
    String host = creplacedandra.getContainerIpAddress();
    Integer mappedPort = creplacedandra.getMappedPort(properties.getPort());
    LinkedHashMap<String, Object> creplacedandraEnv = new LinkedHashMap<>();
    creplacedandraEnv.put("embedded.creplacedandra.port", mappedPort);
    creplacedandraEnv.put("embedded.creplacedandra.host", host);
    creplacedandraEnv.put("embedded.creplacedandra.datacenter", DEFAULT_DATACENTER);
    creplacedandraEnv.put("embedded.creplacedandra.keyspace-name", properties.keyspaceName);
    MapPropertySource propertySource = new MapPropertySource("embeddedCreplacedandraInfo", creplacedandraEnv);
    environment.getPropertySources().addFirst(propertySource);
    return creplacedandraEnv;
}

15 Source : GrpcMockApplicationListener.java
with Apache License 2.0
from Fadelis

private void registerPort(ConfigurableEnvironment environment) {
    Integer httpPort = environment.getProperty("grpcmock.server.port", Integer.clreplaced);
    // If httpPort is not found it means the AutoConfigureGrpcMock hasn't been initialised.
    if (httpPort == null) {
        return;
    }
    if (httpPort.equals(0)) {
        int availablePort = SocketUtils.findAvailableTcpPort();
        MapPropertySource properties = ofNullable(environment.getPropertySources().remove("grpcmock")).map(MapPropertySource.clreplaced::cast).orElseGet(() -> new MapPropertySource("grpcmock", new HashMap<>()));
        environment.getPropertySources().addFirst(properties);
        properties.getSource().put("grpcmock.server.port", availablePort);
        properties.getSource().put("grpcmock.server.port-dynamic", true);
    }
}

14 Source : EmbeddedPostgreSQLBootstrapConfiguration.java
with MIT License
from Playtika

private void registerPostgresqlEnvironment(ConcretePostgreSQLContainer postgresql, ConfigurableEnvironment environment, PostgreSQLProperties properties) {
    Integer mappedPort = postgresql.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT);
    String host = postgresql.getContainerIpAddress();
    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
    map.put("embedded.postgresql.port", mappedPort);
    map.put("embedded.postgresql.host", host);
    map.put("embedded.postgresql.schema", properties.getDatabase());
    map.put("embedded.postgresql.user", properties.getUser());
    map.put("embedded.postgresql.preplacedword", properties.getPreplacedword());
    String jdbcURL = "jdbc:postgresql://{}:{}/{}";
    log.info("Started postgresql server. Connection details: {}, " + "JDBC connection url: " + jdbcURL, map, host, mappedPort, properties.getDatabase());
    MapPropertySource propertySource = new MapPropertySource("embeddedPostgreInfo", map);
    environment.getPropertySources().addFirst(propertySource);
}

14 Source : ExtendPropertySourcesApplicationListener.java
with Apache License 2.0
from mercyblitz

// 处理 ApplicationPreparedEvent
public void onApplicationEvent(ApplicationPreparedEvent event) {
    // 从事件获取 Environment 对象
    ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
    Map<String, Object> source = new HashMap<>();
    // 内部化配置设置 user.name 属性
    source.put("user.name", "马昕曦(小马哥)");
    MapPropertySource propertySource = new MapPropertySource("ApplicationPreparedEvent", source);
    // 添加至最高优先级
    environment.getPropertySources().addFirst(propertySource);
}

14 Source : TestPropertySourceUtils.java
with Apache License 2.0
from langtianya

/**
 * Add the given <em>inlined properties</em> (in the form of <em>key-value</em>
 * pairs) to the supplied {@link ConfigurableEnvironment environment}.
 * <p>All key-value pairs will be added to the {@code Environment} as a
 * single {@link MapPropertySource} with the highest precedence.
 * <p>For details on the parsing of <em>inlined properties</em>, consult the
 * Javadoc for {@link #convertInlinedPropertiesToMap}.
 * @param environment the environment to update; never {@code null}
 * @param inlinedProperties the inlined properties to add to the environment;
 * potentially empty but never {@code null}
 * @since 4.1.5
 * @see MapPropertySource
 * @see #INLINED_PROPERTIES_PROPERTY_SOURCE_NAME
 * @see TestPropertySource#properties
 * @see #convertInlinedPropertiesToMap
 */
public static void addInlinedPropertiesToEnvironment(ConfigurableEnvironment environment, String[] inlinedProperties) {
    replacedert.notNull(environment, "environment must not be null");
    replacedert.notNull(inlinedProperties, "inlinedProperties must not be null");
    if (!ObjectUtils.isEmpty(inlinedProperties)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Adding inlined properties to environment: " + ObjectUtils.nullSafeToString(inlinedProperties));
        }
        MapPropertySource ps = new MapPropertySource(INLINED_PROPERTIES_PROPERTY_SOURCE_NAME, convertInlinedPropertiesToMap(inlinedProperties));
        environment.getPropertySources().addFirst(ps);
    }
}

See More Examples