Example usage for org.springframework.core.env MapPropertySource MapPropertySource

List of usage examples for org.springframework.core.env MapPropertySource MapPropertySource

Introduction

In this page you can find the example usage for org.springframework.core.env MapPropertySource MapPropertySource.

Prototype

public MapPropertySource(String name, Map<String, Object> source) 

Source Link

Usage

From source file:org.grails.datastore.mapping.core.AbstractDatastore.java

protected static PropertyResolver mapToPropertyResolver(Map<String, Object> connectionDetails) {
    if (connectionDetails instanceof PropertyResolver) {
        return (PropertyResolver) connectionDetails;
    } else {//from w  w  w  .  j a va2 s .c o  m
        StandardEnvironment env = new StandardEnvironment();
        if (connectionDetails != null) {
            MutablePropertySources propertySources = env.getPropertySources();
            propertySources.addFirst(new MapPropertySource("datastoreConfig", connectionDetails));
            if (connectionDetails instanceof ConfigObject) {
                propertySources.addFirst(new MapPropertySource("datastoreConfigFlat",
                        ((ConfigObject) connectionDetails).flatten()));
            }
        }
        return env;
    }
}

From source file:org.springframework.boot.context.logging.LoggingApplicationListenerTests.java

@Test
public void lowPriorityPropertySourceShouldNotOverrideRootLoggerConfig() {
    MutablePropertySources propertySources = this.context.getEnvironment().getPropertySources();
    propertySources//from   w  w w .jav a 2  s.co  m
            .addFirst(new MapPropertySource("test1", Collections.singletonMap("logging.level.ROOT", "DEBUG")));
    propertySources
            .addLast(new MapPropertySource("test2", Collections.singletonMap("logging.level.root", "WARN")));
    this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
    this.logger.debug("testatdebug");
    assertThat(this.outputCapture.toString()).contains("testatdebug");
}

From source file:org.springframework.boot.devtools.env.DevToolsPropertyDefaultsPostProcessor.java

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    if (isLocalApplication(environment) && canAddProperties(environment)) {
        logger.info(// w ww  .j  a  v a  2s . c om
                "Devtools property and logging defaults active! Set '" + ENABLED + "' to 'false' to disable");
        environment.getPropertySources().addLast(new MapPropertySource("devtools", PROPERTIES));
    }
}

From source file:org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor.java

private void processJson(ConfigurableEnvironment environment, String json) {
    try {/*  w  w  w. j  a va  2s.co  m*/
        JsonParser parser = JsonParserFactory.getJsonParser();
        Map<String, Object> map = parser.parseMap(json);
        if (!map.isEmpty()) {
            addJsonPropertySource(environment, new MapPropertySource("spring.application.json", flatten(map)));
        }
    } catch (Exception ex) {
        logger.warn("Cannot parse JSON for spring.application.json: " + json, ex);
    }
}

From source file:org.springframework.boot.ResourceBanner.java

private PropertyResolver getVersionResolver(Class<?> sourceClass) {
    MutablePropertySources propertySources = new MutablePropertySources();
    propertySources.addLast(new MapPropertySource("version", getVersionsMap(sourceClass)));
    return new PropertySourcesPropertyResolver(propertySources);
}

From source file:org.springframework.boot.SpringApplication.java

/**
 * Add, remove or re-order any {@link PropertySource}s in this application's
 * environment./* w w  w  . j av a  2 s .  c  o m*/
 * @param environment this application's environment
 * @param args arguments passed to the {@code run} method
 * @see #configureEnvironment(ConfigurableEnvironment, String[])
 */
protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) {
    MutablePropertySources sources = environment.getPropertySources();
    if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
        sources.addLast(new MapPropertySource("defaultProperties", this.defaultProperties));
    }
    if (this.addCommandLineProperties && args.length > 0) {
        String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
        if (sources.contains(name)) {
            PropertySource<?> source = sources.get(name);
            CompositePropertySource composite = new CompositePropertySource(name);
            composite
                    .addPropertySource(new SimpleCommandLinePropertySource(name + "-" + args.hashCode(), args));
            composite.addPropertySource(source);
            sources.replace(name, composite);
        } else {
            sources.addFirst(new SimpleCommandLinePropertySource(args));
        }
    }
}

From source file:org.springframework.cloud.bootstrap.encrypt.EnvironmentDecryptApplicationInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    MapPropertySource decrypted = new MapPropertySource(DECRYPTED_PROPERTY_SOURCE_NAME,
            decrypt(environment.getPropertySources()));
    if (!decrypted.getSource().isEmpty()) {
        // We have some decrypted properties
        insert(environment.getPropertySources(), decrypted);
        ApplicationContext parent = applicationContext.getParent();
        if (parent != null && (parent.getEnvironment() instanceof ConfigurableEnvironment)) {
            ConfigurableEnvironment mutable = (ConfigurableEnvironment) parent.getEnvironment();
            // The parent is actually the bootstrap context, and it is fully
            // initialized, so we can fire an EnvironmentChangeEvent there to rebind
            // @ConfigurationProperties, in case they were encrypted.
            insert(mutable.getPropertySources(), decrypted);
            parent.publishEvent(new EnvironmentChangeEvent(decrypted.getSource().keySet()));
        }//from ww  w .  j  a  v a 2s. c  om
    }
}

From source file:org.springframework.cloud.bootstrap.encrypt.EnvironmentDecryptApplicationListener.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    Map<String, Object> overrides = new LinkedHashMap<String, Object>();
    for (PropertySource<?> source : environment.getPropertySources()) {
        decrypt(source, overrides);//w  ww .  ja va2s . c o  m
    }
    if (!overrides.isEmpty()) {
        environment.getPropertySources().addFirst(new MapPropertySource("decrypted", overrides));
    }
}

From source file:org.springframework.cloud.config.client.AbstractConfigServicePropertyLocator.java

CompositePropertySource exchange(ConfigClientProperties client, CompositePropertySource composite) {
    RestTemplate restTemplate = this.restTemplate == null ? getSecureRestTemplate(client) : this.restTemplate;
    logger.info("Attempting to load environment from source: " + client.getRawUri());
    org.springframework.cloud.config.Environment result = restTemplate
            .exchange(client.getRawUri() + "/{name}/{profile}/{label}", HttpMethod.GET,
                    new HttpEntity<Void>((Void) null), org.springframework.cloud.config.Environment.class,
                    client.getName(), client.getProfile(), client.getLabel())
            .getBody();//  w ww.  java  2s.  c  o  m
    for (org.springframework.cloud.config.PropertySource source : result.getPropertySources()) {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) source.getSource();
        composite.addPropertySource(new MapPropertySource(source.getName(), map));
    }
    return composite;
}

From source file:org.springframework.cloud.config.client.ConfigServicePropertySourceLocator.java

@Override
@Retryable(interceptor = "configServerRetryInterceptor")
public org.springframework.core.env.PropertySource<?> locate(
        org.springframework.core.env.Environment environment) {
    ConfigClientProperties properties = this.defaultProperties.override(environment);
    CompositePropertySource composite = new CompositePropertySource("configService");
    RestTemplate restTemplate = this.restTemplate == null ? getSecureRestTemplate(properties)
            : this.restTemplate;
    Exception error = null;//from   ww  w  .j a  va 2  s.  c  o  m
    String errorBody = null;
    logger.info("Fetching config from server at: " + properties.getRawUri());
    try {
        String[] labels = new String[] { "" };
        if (StringUtils.hasText(properties.getLabel())) {
            labels = StringUtils.commaDelimitedListToStringArray(properties.getLabel());
        }

        String state = ConfigClientStateHolder.getState();

        // Try all the labels until one works
        for (String label : labels) {
            Environment result = getRemoteEnvironment(restTemplate, properties, label.trim(), state);
            if (result != null) {
                logger.info(String.format(
                        "Located environment: name=%s, profiles=%s, label=%s, version=%s, state=%s",
                        result.getName(),
                        result.getProfiles() == null ? "" : Arrays.asList(result.getProfiles()),
                        result.getLabel(), result.getVersion(), result.getState()));

                for (PropertySource source : result.getPropertySources()) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> map = (Map<String, Object>) source.getSource();
                    composite.addPropertySource(new MapPropertySource(source.getName(), map));
                }

                if (StringUtils.hasText(result.getState()) || StringUtils.hasText(result.getVersion())) {
                    HashMap<String, Object> map = new HashMap<>();
                    putValue(map, "config.client.state", result.getState());
                    putValue(map, "config.client.version", result.getVersion());
                    composite.addFirstPropertySource(new MapPropertySource("configClient", map));
                }
                return composite;
            }
        }
    } catch (HttpServerErrorException e) {
        error = e;
        if (MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) {
            errorBody = e.getResponseBodyAsString();
        }
    } catch (Exception e) {
        error = e;
    }
    if (properties.isFailFast()) {
        throw new IllegalStateException(
                "Could not locate PropertySource and the fail fast property is set, failing", error);
    }
    logger.warn("Could not locate PropertySource: "
            + (errorBody == null ? error == null ? "label not found" : error.getMessage() : errorBody));
    return null;

}