Example usage for org.springframework.core.env MutablePropertySources addFirst

List of usage examples for org.springframework.core.env MutablePropertySources addFirst

Introduction

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

Prototype

public void addFirst(PropertySource<?> propertySource) 

Source Link

Document

Add the given property source object with highest precedence.

Usage

From source file:ch.sdi.SocialDataImporterRunner.java

/**
 * Initializes the environment.//from  ww w. j a  v a  2 s. co  m
 * <p>
 * @param aArgs the command line arguments
 * @throws SdiException on any problems
 */
private void initialize(String[] aArgs) throws SdiException {
    if (myConversionService == null) {
        throw new SdiException("ConversionService not injected", SdiException.EXIT_CODE_CONFIG_ERROR);
    } // if myConversionService == null

    ConfigUtils.setConversionService(myConversionService);

    myUserPropertyOverloader.overrideByUserProperties();

    String s = Arrays.toString(aArgs);
    myLog.debug("adding command line arguments to the environment: " + s);

    MutablePropertySources propertySources = myEnv.getPropertySources();
    propertySources.addFirst(new SimpleCommandLinePropertySource(ConfigUtils.PROP_SOURCE_NAME_CMD_LINE, aArgs));

    if (myLog.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder(
                "After self-configuration, and after user property " + "override. ");
        sb.append(myLog.isTraceEnabled() ? "Loaded properties: " : "Loaded property sources: ");

        MutablePropertySources mps = myEnv.getPropertySources();
        for (PropertySource<?> propertySource : mps) {
            sb.append("\n    PropertySource: ").append(propertySource.getName());

            if (myLog.isTraceEnabled()) {
                sb.append("\n        ").append("" + propertySource.getSource());
            } // if myLog.isTraceEnabled()
        }

        if (myLog.isTraceEnabled()) {
            myLog.trace(sb.toString());
        } // if myLog.isTraceEnabled()
        else if (myLog.isDebugEnabled()) {
            myLog.debug(sb.toString());
        }
    } // if myLog.isDebugEnabled()

    myLog.trace(
            "inputcollector.thing.alternateName: " + myEnv.getProperty("inputcollector.thing.alternateName"));
}

From source file:net.ggtools.maven.DDLGeneratorMojo.java

AnnotationConfigApplicationContext createApplicationContext() {
    final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    final ConfigurableEnvironment environment = applicationContext.getEnvironment();
    final MutablePropertySources propertySources = environment.getPropertySources();
    final MapPropertySource propertySource = createPropertySource();
    propertySources.addFirst(propertySource);
    applicationContext.register(SpringConfiguration.class);
    applicationContext.refresh();/*from ww w  . j a  v  a  2  s.  c o  m*/
    return applicationContext;
}

From source file:cf.spring.config.YamlPropertyContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    try {/* w w w.j  a  v  a2  s .c o m*/
        final ConfigurableEnvironment environment = applicationContext.getEnvironment();
        final Resource resource = applicationContext
                .getResource(environment.getProperty(locationProperty, locationDefault));
        final YamlDocument yamlDocument;
        LOGGER.info("Loading config from: {}", resource);
        yamlDocument = YamlDocument.load(resource);
        final MutablePropertySources propertySources = environment.getPropertySources();
        final PropertySource propertySource = new YamlPropertySource(name, yamlDocument);
        if (addFirst) {
            propertySources.addFirst(propertySource);
        } else {
            propertySources.addLast(propertySource);
        }

        applicationContext.getBeanFactory().registerSingleton(name, yamlDocument);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.alibaba.dubbo.config.spring.context.annotation.DubboConfigBindingRegistrar.java

private MutablePropertyValues resolveBeanPropertyValues(String beanName, boolean multiple,
        Map<String, String> properties) {

    MutablePropertyValues propertyValues = new MutablePropertyValues();

    if (multiple) { // For Multiple Beans

        MutablePropertySources propertySources = new MutablePropertySources();
        propertySources.addFirst(new MapPropertySource(beanName, new TreeMap<String, Object>(properties)));

        Map<String, String> subProperties = getSubProperties(propertySources, beanName);

        propertyValues.addPropertyValues(subProperties);

    } else { // For Single Bean

        for (Map.Entry<String, String> entry : properties.entrySet()) {
            String propertyName = entry.getKey();
            if (!propertyName.contains(".")) { // ignore property name with "."
                propertyValues.addPropertyValue(propertyName, entry.getValue());
            }//from w ww . ja  v a2  s .  c  o m
        }

    }

    return propertyValues;

}

From source file:ch.sdi.UserPropertyOverloader.java

public void overrideByUserProperties() {
    List<Class<?>> candidates = findCandidates();

    for (Class<?> clazz : candidates) {
        myLog.debug("candidate for user property overloading: " + clazz.getName());
        String fileName = SdiMainProperties.USER_OVERRIDE_PREFIX + ConfigUtils.makePropertyResourceName(clazz);
        InputStream is = this.getClass().getResourceAsStream("/" + fileName);

        if (is == null) {
            myLog.debug("Skipping non existing user overloading property file: " + fileName);
            continue;
        } // if is == null

        myLog.debug("Found overloading property file: " + fileName);
        Properties props = new Properties();
        try {/*w ww . jav  a  2 s. co m*/
            props.load(is);
        } catch (IOException t) {
            myLog.error("Problems loading property file " + fileName);
        }

        myEnv.setIgnoreUnresolvableNestedPlaceholders(true);
        try {
            props.stringPropertyNames().stream().map(key -> {
                String origValue = myEnv.getProperty(key);
                String result = "Key " + key + ": ";
                return (origValue == null || origValue.isEmpty())
                        ? result + "No default value found. Adding new value to environment: \""
                                + props.getProperty(key) + "\""
                        : result + "Overriding default value \"" + origValue + "\" with new value: \""
                                + props.getProperty(key) + "\"";
            }).forEach(msg -> myLog.debug(msg));
        } finally {
            myEnv.setIgnoreUnresolvableNestedPlaceholders(false);
        }

        PropertySource<?> ps = new PropertiesPropertySource(fileName, props);
        MutablePropertySources mps = myEnv.getPropertySources();
        if (mps.get(ConfigUtils.PROP_SOURCE_NAME_CMD_LINE) != null) {
            mps.addAfter(ConfigUtils.PROP_SOURCE_NAME_CMD_LINE, ps);
        } else {
            mps.addFirst(ps);
        }
        myLog.debug("PropertySources after adding overloading: " + mps);
    }

}

From source file:com.github.eddumelendez.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration.java

private Map<String, Object> getLdapPorts(MutablePropertySources sources) {
    PropertySource<?> propertySource = sources.get("ldap.ports");
    if (propertySource == null) {
        propertySource = new MapPropertySource("ldap.ports", new HashMap<String, Object>());
        sources.addFirst(propertySource);
    }/*from   ww w . j ava2 s. c  o  m*/
    return (Map<String, Object>) propertySource.getSource();
}

From source file:org.craftercms.deployer.impl.TargetResolverImpl.java

protected ConfigurableApplicationContext loadApplicationContext(HierarchicalConfiguration config,
        File customDeploymentAppContextFile) throws IOException {
    GenericApplicationContext appContext = new GenericApplicationContext(mainApplicationContext);

    MutablePropertySources propertySources = appContext.getEnvironment().getPropertySources();
    propertySources
            .addFirst(new ApacheCommonsConfiguration2PropertySource(CONFIG_PROPERTY_SOURCE_NAME, config));

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

    if (baseTargetAppContextResource.exists()) {
        logger.debug("Loading base target application context at {}", baseTargetAppContextResource);

        reader.loadBeanDefinitions(baseTargetAppContextResource);
    }/*  ww  w  .  j a  va2s . c o m*/
    if (baseTargetAppContextOverrideResource.exists()) {
        logger.debug("Loading base target application context override at {}", baseTargetAppContextResource);

        reader.loadBeanDefinitions(baseTargetAppContextResource);
    }
    if (customDeploymentAppContextFile.exists()) {
        logger.debug("Loading custom target application context at {}", customDeploymentAppContextFile);

        try (InputStream in = new BufferedInputStream(new FileInputStream(customDeploymentAppContextFile))) {
            reader.loadBeanDefinitions(new InputSource(in));
        }
    }

    appContext.refresh();

    return appContext;
}

From source file:com.github.dactiv.fear.commons.Apis.java

@Override
public void afterPropertiesSet() throws Exception {

    PropertySourcesPlaceholderConfigurer configurer = null;
    PropertySources propertySources = null;
    try {/*from   www.  jav  a2 s . c om*/
        configurer = applicationContext.getBean(PropertySourcesPlaceholderConfigurer.class);
        propertySources = configurer.getAppliedPropertySources();
    } catch (Exception e) {
        LOGGER.warn("install " + PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME
                + " error", e);
    }

    if (propertySources == null) {
        return;
    }

    Field field = ReflectionUtils.findField(configurer.getClass(), "environment");
    field.setAccessible(Boolean.TRUE);
    environment = (Environment) field.get(configurer);
    if (environment instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment ce = (ConfigurableEnvironment) environment;
        MutablePropertySources sources = ce.getPropertySources();
        PropertySource<?> ps = propertySources
                .get(PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME);
        sources.addFirst(ps);
    }
}

From source file:net.community.chest.gitcloud.facade.AbstractContextInitializer.java

protected File resolveApplicationBase(MutablePropertySources propSources,
        ExtendedPlaceholderResolver sourcesResolver) {
    Pair<File, Boolean> result = ConfigUtils.resolveGitcloudBase(sourcesResolver);
    File rootDir = result.getLeft();
    Boolean baseExists = result.getRight();
    if (!baseExists.booleanValue()) {
        propSources.addFirst(new MapPropertySource("gitcloudBase", Collections
                .<String, Object>singletonMap(ConfigUtils.GITCLOUD_BASE_PROP, rootDir.getAbsolutePath())));
        System.setProperty(ConfigUtils.GITCLOUD_BASE_PROP, rootDir.getAbsolutePath());
        logger.info("resolveApplicationBase - added " + ConfigUtils.GITCLOUD_BASE_PROP + ": "
                + ExtendedFileUtils.toString(rootDir));
    }//from ww  w  .  j  a v  a2 s  .  c o m

    return rootDir;
}

From source file:com.indeed.imhotep.web.config.PropertiesInitializer.java

protected boolean tryAddPropertySource(ConfigurableApplicationContext applicationContext,
        MutablePropertySources propSources, String filePath) {
    if (filePath == null) {
        return false;
    }/*from  ww  w  . j ava2 s .  co m*/
    Resource propertiesResource = applicationContext.getResource(filePath);
    if (!propertiesResource.exists()) {
        return false;
    }
    try {
        ResourcePropertySource propertySource = new ResourcePropertySource(propertiesResource);
        propSources.addFirst(propertySource);
    } catch (IOException e) {
        return false;
    }
    log.debug("Successfully added property source: " + filePath);
    return true;
}