Search in sources :

Example 21 with CompositePropertySource

use of org.springframework.core.env.CompositePropertySource in project spring-cloud-consul by spring-cloud.

the class ConsulPropertySourceLocator method locate.

@Override
@Retryable(interceptor = "consulRetryInterceptor")
public PropertySource<?> locate(Environment environment) {
    if (environment instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
        String appName = properties.getName();
        if (appName == null) {
            appName = env.getProperty("spring.application.name");
        }
        List<String> profiles = Arrays.asList(env.getActiveProfiles());
        String prefix = this.properties.getPrefix();
        List<String> suffixes = new ArrayList<>();
        if (this.properties.getFormat() != FILES) {
            suffixes.add("/");
        } else {
            suffixes.add(".yml");
            suffixes.add(".yaml");
            suffixes.add(".properties");
        }
        String defaultContext = getContext(prefix, this.properties.getDefaultContext());
        for (String suffix : suffixes) {
            this.contexts.add(defaultContext + suffix);
        }
        for (String suffix : suffixes) {
            addProfiles(this.contexts, defaultContext, profiles, suffix);
        }
        String baseContext = getContext(prefix, appName);
        for (String suffix : suffixes) {
            this.contexts.add(baseContext + suffix);
        }
        for (String suffix : suffixes) {
            addProfiles(this.contexts, baseContext, profiles, suffix);
        }
        Collections.reverse(this.contexts);
        CompositePropertySource composite = new CompositePropertySource("consul");
        for (String propertySourceContext : this.contexts) {
            try {
                ConsulPropertySource propertySource = null;
                if (this.properties.getFormat() == FILES) {
                    Response<GetValue> response = this.consul.getKVValue(propertySourceContext, this.properties.getAclToken());
                    addIndex(propertySourceContext, response.getConsulIndex());
                    if (response.getValue() != null) {
                        ConsulFilesPropertySource filesPropertySource = new ConsulFilesPropertySource(propertySourceContext, this.consul, this.properties);
                        filesPropertySource.init(response.getValue());
                        propertySource = filesPropertySource;
                    }
                } else {
                    propertySource = create(propertySourceContext, contextIndex);
                }
                if (propertySource != null) {
                    composite.addPropertySource(propertySource);
                }
            } catch (Exception e) {
                if (this.properties.isFailFast()) {
                    log.error("Fail fast is set and there was an error reading configuration from consul.");
                    ReflectionUtils.rethrowRuntimeException(e);
                } else {
                    log.warn("Unable to load consul config from " + propertySourceContext, e);
                }
            }
        }
        return composite;
    }
    return null;
}
Also used : ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) CompositePropertySource(org.springframework.core.env.CompositePropertySource) ArrayList(java.util.ArrayList) GetValue(com.ecwid.consul.v1.kv.model.GetValue) Retryable(org.springframework.retry.annotation.Retryable)

Example 22 with CompositePropertySource

use of org.springframework.core.env.CompositePropertySource in project spring-cloud-consul by spring-cloud.

the class ConsulPropertySourceLocatorFilesTests method propertySourcesFound.

@Test
public void propertySourcesFound() throws Exception {
    String foo = this.environment.getProperty("foo");
    assertThat("foo was wrong", foo, is(equalTo("bar-app-dev")));
    String myBaz = this.environment.getProperty("my.baz");
    assertThat("my.baz was wrong", myBaz, is(equalTo("bar-app-dev")));
    MutablePropertySources propertySources = this.environment.getPropertySources();
    PropertySource<?> bootstrapProperties = propertySources.get("bootstrapProperties");
    assertThat("bootstrapProperties was null", bootstrapProperties, is(notNullValue()));
    assertThat("bootstrapProperties was wrong type", bootstrapProperties.getClass(), is(typeCompatibleWith(CompositePropertySource.class)));
    Collection<PropertySource<?>> consulSources = ((CompositePropertySource) bootstrapProperties).getPropertySources();
    assertThat("consulSources was wrong size", consulSources, hasSize(1));
    PropertySource<?> consulSource = consulSources.iterator().next();
    assertThat("consulSource was wrong type", consulSource.getClass(), is(typeCompatibleWith(CompositePropertySource.class)));
    Collection<PropertySource<?>> fileSources = ((CompositePropertySource) consulSource).getPropertySources();
    assertThat("fileSources was wrong size", fileSources, hasSize(4));
    assertFileSourceNames(fileSources, APP_NAME_DEV_PROPS, APP_NAME_PROPS, APPLICATION_DEV_YML, APPLICATION_YML);
}
Also used : CompositePropertySource(org.springframework.core.env.CompositePropertySource) MutablePropertySources(org.springframework.core.env.MutablePropertySources) PropertySource(org.springframework.core.env.PropertySource) CompositePropertySource(org.springframework.core.env.CompositePropertySource) Test(org.junit.Test)

Example 23 with CompositePropertySource

use of org.springframework.core.env.CompositePropertySource in project gravitee-management-rest-api by gravitee-io.

the class EnvironmentUtils method getAllProperties.

public static Map<String, Object> getAllProperties(PropertySource<?> aPropSource) {
    Map<String, Object> result = new HashMap<>();
    if (aPropSource instanceof CompositePropertySource) {
        CompositePropertySource cps = (CompositePropertySource) aPropSource;
        cps.getPropertySources().forEach(ps -> addAll(result, getAllProperties(ps)));
        return result;
    }
    if (aPropSource instanceof EnumerablePropertySource<?>) {
        EnumerablePropertySource<?> ps = (EnumerablePropertySource<?>) aPropSource;
        Arrays.asList(ps.getPropertyNames()).forEach(key -> result.put(key, ps.getProperty(key)));
        return result;
    }
    // note: Most descendants of PropertySource are EnumerablePropertySource. There are some
    // few others like JndiPropertySource or StubPropertySource
    LOGGER.debug("Given PropertySource is instanceof " + aPropSource.getClass().getName() + " and cannot be iterated");
    return result;
}
Also used : EnumerablePropertySource(org.springframework.core.env.EnumerablePropertySource) CompositePropertySource(org.springframework.core.env.CompositePropertySource) HashMap(java.util.HashMap)

Example 24 with CompositePropertySource

use of org.springframework.core.env.CompositePropertySource in project spring-cloud-config by spring-cloud.

the class ConfigServicePropertySourceLocator method locate.

@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;
    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) {
                log(result);
                if (result.getPropertySources() != null) {
                    // result.getPropertySources() can be null if using xml
                    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;
}
Also used : HashMap(java.util.HashMap) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) IOException(java.io.IOException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) PropertySource(org.springframework.cloud.config.environment.PropertySource) CompositePropertySource(org.springframework.core.env.CompositePropertySource) MapPropertySource(org.springframework.core.env.MapPropertySource) CompositePropertySource(org.springframework.core.env.CompositePropertySource) MapPropertySource(org.springframework.core.env.MapPropertySource) RestTemplate(org.springframework.web.client.RestTemplate) Environment(org.springframework.cloud.config.environment.Environment) HashMap(java.util.HashMap) Map(java.util.Map) Retryable(org.springframework.retry.annotation.Retryable)

Example 25 with CompositePropertySource

use of org.springframework.core.env.CompositePropertySource in project cas by apereo.

the class MongoDbPropertySourceLocator method locate.

@Override
public PropertySource<?> locate(final Environment environment) {
    if (environment instanceof ConfigurableEnvironment) {
        val sourceName = MongoDbPropertySource.class.getSimpleName();
        val composite = new CompositePropertySource(sourceName);
        val source = new MongoDbPropertySource(sourceName, mongo);
        composite.addFirstPropertySource(source);
        return composite;
    }
    return null;
}
Also used : lombok.val(lombok.val) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) CompositePropertySource(org.springframework.core.env.CompositePropertySource)

Aggregations

CompositePropertySource (org.springframework.core.env.CompositePropertySource)35 MapPropertySource (org.springframework.core.env.MapPropertySource)11 Test (org.junit.Test)10 MutablePropertySources (org.springframework.core.env.MutablePropertySources)10 lombok.val (lombok.val)9 HashMap (java.util.HashMap)7 Test (org.junit.jupiter.api.Test)7 ConfigurableEnvironment (org.springframework.core.env.ConfigurableEnvironment)6 StandardEnvironment (org.springframework.core.env.StandardEnvironment)5 IOException (java.io.IOException)4 Map (java.util.Map)4 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)4 EnumerablePropertySource (org.springframework.core.env.EnumerablePropertySource)4 PropertySource (org.springframework.core.env.PropertySource)4 Arrays (java.util.Arrays)3 List (java.util.List)3 FileSystemResource (org.springframework.core.io.FileSystemResource)3 Resource (org.springframework.core.io.Resource)3 Config (com.ctrip.framework.apollo.Config)2 File (java.io.File)2