Example usage for org.springframework.core.env CompositePropertySource addPropertySource

List of usage examples for org.springframework.core.env CompositePropertySource addPropertySource

Introduction

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

Prototype

public void addPropertySource(PropertySource<?> propertySource) 

Source Link

Document

Add the given PropertySource to the end of the chain.

Usage

From source file:io.kahu.hawaii.config.HawaiiAppContextInitializer.java

private PropertySource<Object> getPropertySource() {
    List<Resource> resources = new ArrayList<Resource>();

    String configurationFiles = System.getProperty("properties.configuration");
    String[] files = StringUtils.split(configurationFiles, ",");
    for (String configFileName : files) {
        try {//from  www . ja  v a  2 s .c o m
            File file = new File(configFileName);
            if (file.exists()) {
                resources.add(0, new FileSystemResource(file));
            } else {
                System.err.println("Configured properties file '" + configFileName + "' does not exist.");
            }
        } catch (Throwable t) {
            System.err.print("Error loading properties from file '" + configFileName + "': " + t.getMessage());
            resources = null;
        }
    }

    try {
        CompositePropertySource propertySource = new CompositePropertySource("properties");
        for (Resource resource : resources) {
            propertySource.addPropertySource(new ResourcePropertySource(resource));
        }
        return propertySource;
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:ch.sdi.core.impl.cfg.ConfigUtilsTest.java

/**
 * Test method for {@link ch.sdi.core.impl.cfg.ConfigUtils#getPropertyNamesStartingWith(Class)}.
 *//*from www.  ja  v  a 2 s  .  co m*/
@Test
public void testGetPropertyNamesStartingWith() {
    Properties props1 = new Properties();
    PropertiesPropertySource pps1 = new PropertiesPropertySource("Props1", props1);
    props1.put("sdi.collect.comment.2", "//");
    props1.put("sdi.collect.comment.1", "#");
    props1.put("key", "value");

    Properties props2 = new Properties();
    PropertiesPropertySource pps2 = new PropertiesPropertySource("Props2", props2);
    props1.put("sdi.collect.comment.2", ";");
    props1.put("sdi.collect.comment.1", "?");

    MutablePropertySources mps = myEnv.getPropertySources();
    mps.addFirst(pps1);
    mps.addLast(pps2);

    Collection<String> received = ConfigUtils.getPropertyNamesStartingWith(myEnv, "sdi.collect.comment.");
    Assert.assertNotNull(received);
    myLog.debug("received: " + received);
    Assert.assertEquals(2, received.size());
    // assert also if the retrieved keys are sorted:
    int i = 1;
    for (Iterator<String> iterator = received.iterator(); iterator.hasNext();) {
        String key = iterator.next();
        Assert.assertEquals("sdi.collect.comment." + i, key);
        i++;
    }

    myLog.debug("testing composite property source");
    CompositePropertySource cps = new CompositePropertySource("CompositeTest");
    cps.addPropertySource(pps1);
    cps.addPropertySource(pps2);

    TestUtils.removeAllFromEnvironment(myEnv);
    mps = myEnv.getPropertySources();
    mps.addFirst(pps1);

    received = ConfigUtils.getPropertyNamesStartingWith(myEnv, "sdi.collect.comment.");
    Assert.assertNotNull(received);
    myLog.debug("received: " + received);
    Assert.assertEquals(2, received.size());
    for (Iterator<String> iterator = received.iterator(); iterator.hasNext();) {
        String key = iterator.next();
        Assert.assertTrue(key.startsWith("sdi.collect.comment."));
    }

}

From source file:com.bose.aem.spring.config.ConfigServicePropertySourceLocator.java

@Override
public org.springframework.core.env.PropertySource<?> locate(
        org.springframework.core.env.Environment environment) {
    ConfigClientProperties client = this.defaults.override(environment);
    CompositePropertySource composite = new CompositePropertySource("configService");
    RestTemplate restTemplate = this.restTemplate == null ? getSecureRestTemplate(client) : this.restTemplate;
    Exception error = null;//from   ww w .  j  av  a2s  . c  o  m
    String errorBody = null;
    //logger.info("Fetching config from server at: " + client.getRawUri());
    try {
        String[] labels = new String[] { "" };
        if (StringUtils.hasText(client.getLabel())) {
            labels = StringUtils.commaDelimitedListToStringArray(client.getLabel());
        }
        // Try all the labels until one works
        for (String label : labels) {
            Environment result = getRemoteEnvironment(restTemplate, client.getRawUri(), client.getName(),
                    client.getProfile(), label.trim());
            if (result != null) {
                //                    logger.info(String.format("Located environment: name=%s, profiles=%s, label=%s, version=%s",
                //                            result.getName(),
                //                            result.getProfiles() == null ? "" : Arrays.asList(result.getProfiles()),
                //                            result.getLabel(), result.getVersion()));

                for (PropertySource source : result.getPropertySources()) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> map = (Map<String, Object>) source.getSource();
                    composite.addPropertySource(new MapPropertySource(source.getName(), 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 (client != null && client.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;

}

From source file:org.apache.servicecomb.config.TestConfigurationSpringInitializer.java

@Test
public void testSetEnvironment() {
    ConfigurableEnvironment environment = Mockito.mock(ConfigurableEnvironment.class);
    MutablePropertySources propertySources = new MutablePropertySources();
    Map<String, String> propertyMap = new HashMap<>();
    final String map0Key0 = "map0-Key0";
    final String map1Key0 = "map1-Key0";
    final String map2Key0 = "map2-Key0";
    final String map3Key0 = "map3-Key0";
    propertyMap.put(map0Key0, "map0-Value0");
    propertyMap.put(map1Key0, "map1-Value0");
    propertyMap.put(map2Key0, "map2-Value0");
    propertyMap.put(map3Key0, "map3-Value0");

    /*/*from   w w w. jav a  2 s .  c o m*/
    propertySources
    |- compositePropertySource0
    |  |- mapPropertySource0
    |  |  |- map0-Key0 = map0-Value0
    |  |- compositePropertySource1
    |     |- mapPropertySource1
    |     |  |- map1-Key0 = map1-Value0
    |     |- mapPropertySource2
    |        |- map2-Key0 = map2-Value0
    |     |- JndiPropertySource(mocked)
    |- mapPropertySource3
      |- map3-Key0 = map3-Value0
     */
    CompositePropertySource compositePropertySource0 = new CompositePropertySource("compositePropertySource0");
    propertySources.addFirst(compositePropertySource0);

    HashMap<String, Object> map0 = new HashMap<>();
    map0.put(map0Key0, propertyMap.get(map0Key0));
    MapPropertySource mapPropertySource0 = new MapPropertySource("mapPropertySource0", map0);
    compositePropertySource0.addFirstPropertySource(mapPropertySource0);

    CompositePropertySource compositePropertySource1 = new CompositePropertySource("compositePropertySource1");
    compositePropertySource0.addPropertySource(compositePropertySource1);
    HashMap<String, Object> map1 = new HashMap<>();
    map1.put(map1Key0, propertyMap.get(map1Key0));
    MapPropertySource mapPropertySource1 = new MapPropertySource("mapPropertySource1", map1);
    compositePropertySource1.addPropertySource(mapPropertySource1);
    HashMap<String, Object> map2 = new HashMap<>();
    map2.put(map2Key0, propertyMap.get(map2Key0));
    MapPropertySource mapPropertySource2 = new MapPropertySource("mapPropertySource2", map2);
    compositePropertySource1.addPropertySource(mapPropertySource2);
    compositePropertySource1.addPropertySource(Mockito.mock(JndiPropertySource.class));

    HashMap<String, Object> map3 = new HashMap<>();
    map3.put(map3Key0, propertyMap.get(map3Key0));
    MapPropertySource mapPropertySource3 = new MapPropertySource("mapPropertySource3", map3);
    compositePropertySource0.addPropertySource(mapPropertySource3);

    Mockito.when(environment.getPropertySources()).thenReturn(propertySources);
    Mockito.doAnswer((Answer<String>) invocation -> {
        Object[] args = invocation.getArguments();
        String propertyName = (String) args[0];

        if ("spring.config.name".equals(propertyName) || "spring.application.name".equals(propertyName)) {
            return null;
        }

        String value = propertyMap.get(propertyName);
        if (null == value) {
            fail("get unexpected property name: " + propertyName);
        }
        return value;
    }).when(environment).getProperty(anyString());

    new ConfigurationSpringInitializer().setEnvironment(environment);

    Map<String, Map<String, Object>> extraLocalConfig = getExtraConfigMapFromConfigUtil();
    assertFalse(extraLocalConfig.isEmpty());
    Map<String, Object> extraProperties = extraLocalConfig
            .get(ConfigurationSpringInitializer.EXTRA_CONFIG_SOURCE_PREFIX + environment.getClass().getName()
                    + "@" + environment.hashCode());
    assertNotNull(extraLocalConfig);
    for (Entry<String, String> entry : propertyMap.entrySet()) {
        assertEquals(entry.getValue(), extraProperties.get(entry.getKey()));
    }
}

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

/**
 * Add, remove or re-order any {@link PropertySource}s in this application's
 * environment.//from   ww  w . ja v 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.aws.paramstore.AwsParamStorePropertySourceLocator.java

@Override
public PropertySource<?> locate(Environment environment) {
    if (!(environment instanceof ConfigurableEnvironment)) {
        return null;
    }/*from  w  w w  . ja v  a 2s. c  om*/

    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();

    String defaultContext = prefix + "/" + this.properties.getDefaultContext();
    this.contexts.add(defaultContext + "/");
    addProfiles(this.contexts, defaultContext, profiles);

    String baseContext = prefix + "/" + appName;
    this.contexts.add(baseContext + "/");
    addProfiles(this.contexts, baseContext, profiles);

    Collections.reverse(this.contexts);

    CompositePropertySource composite = new CompositePropertySource("aws-param-store");

    for (String propertySourceContext : this.contexts) {
        try {
            composite.addPropertySource(create(propertySourceContext));
        } catch (Exception e) {
            if (this.properties.isFailFast()) {
                logger.error(
                        "Fail fast is set and there was an error reading configuration from AWS Parameter Store:\n"
                                + e.getMessage());
                ReflectionUtils.rethrowRuntimeException(e);
            } else {
                logger.warn("Unable to load AWS config from " + propertySourceContext, e);
            }
        }
    }

    return composite;
}

From source file:org.springframework.cloud.aws.secretsmanager.AwsSecretsManagerPropertySourceLocator.java

@Override
public PropertySource<?> locate(Environment environment) {
    if (!(environment instanceof ConfigurableEnvironment)) {
        return null;
    }//  www  . java2  s. c o  m

    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();

    String defaultContext = prefix + "/" + this.properties.getDefaultContext();
    this.contexts.add(defaultContext);
    addProfiles(this.contexts, defaultContext, profiles);

    String baseContext = prefix + "/" + appName;
    this.contexts.add(baseContext);
    addProfiles(this.contexts, baseContext, profiles);

    Collections.reverse(this.contexts);

    CompositePropertySource composite = new CompositePropertySource("aws-secrets-manager");

    for (String propertySourceContext : this.contexts) {
        try {
            composite.addPropertySource(create(propertySourceContext));
        } catch (Exception e) {
            if (this.properties.isFailFast()) {
                logger.error(
                        "Fail fast is set and there was an error reading configuration from AWS Secrets Manager:\n"
                                + e.getMessage());
                ReflectionUtils.rethrowRuntimeException(e);
            } else {
                logger.warn("Unable to load AWS secret from " + propertySourceContext, e);
            }
        }
    }

    return composite;
}

From source file:org.springframework.cloud.bootstrap.config.ConfigServiceBootstrapConfiguration.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    CompositePropertySource composite = new CompositePropertySource("bootstrap");
    AnnotationAwareOrderComparator.sort(propertySourceLocators);
    boolean empty = true;
    for (PropertySourceLocator locator : propertySourceLocators) {
        PropertySource<?> source = null;
        try {// ww  w.  j av a2 s  . c o m
            source = locator.locate();
        } catch (Exception e) {
            logger.error("Could not locate PropertySource: " + e.getMessage());
        }
        if (source == null) {
            continue;
        }
        logger.info("Located property source: " + source);
        composite.addPropertySource(source);
        empty = false;
    }
    if (!empty) {
        MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
        if (propertySources.contains("bootstrap")) {
            propertySources.replace("bootstrap", composite);
        } else {
            propertySources.addFirst(composite);
        }
    }
}

From source file:org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    CompositePropertySource composite = new CompositePropertySource(BOOTSTRAP_PROPERTY_SOURCE_NAME);
    AnnotationAwareOrderComparator.sort(propertySourceLocators);
    boolean empty = true;
    for (PropertySourceLocator locator : propertySourceLocators) {
        PropertySource<?> source = null;
        try {/*w w w  .  j  a va 2  s  .  c o m*/
            source = locator.locate(applicationContext.getEnvironment());
        } catch (Exception e) {
            logger.error("Could not locate PropertySource: " + e.getMessage());
        }
        if (source == null) {
            continue;
        }
        logger.info("Located property source: " + source);
        composite.addPropertySource(source);
        empty = false;
    }
    if (!empty) {
        MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
        if (propertySources.contains(BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
            propertySources.replace(BOOTSTRAP_PROPERTY_SOURCE_NAME, composite);
        } else {
            propertySources.addFirst(composite);
        }
    }
}

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();/*  www.ja v a  2 s .  co  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;
}