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:com.home.ln_spring.ch5.env.EnvironmentSample.java

public static void main(String[] args) {
    GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
    ctx.refresh();//  w ww.  j a  v a 2  s  .c om

    ConfigurableEnvironment env = ctx.getEnvironment();
    MutablePropertySources propertySources = env.getPropertySources();
    Map appMap = new HashMap();
    appMap.put("user.home", "/home/vitaliy/NetBeansProjects/Ln_Spring");
    propertySources.addFirst(new MapPropertySource("SPRING3_MAP", appMap));

    System.out.println("user.home: " + System.getProperty("user.home"));
    System.out.println("JAVA_HOME: " + System.getProperty("JAVA_HOME"));

    System.out.println("user.home: " + env.getProperty("user.home"));
    System.out.println("JAVA_HOME: " + env.getProperty("JAVA_HOME"));
}

From source file:uk.ac.kcl.Main.java

public static void main(String[] args) {
    File folder = new File(args[0]);
    File[] listOfFiles = folder.listFiles();
    assert listOfFiles != null;
    for (File listOfFile : listOfFiles) {
        if (listOfFile.isFile()) {
            if (listOfFile.getName().endsWith(".properties")) {
                System.out.println("Properties sile found:" + listOfFile.getName()
                        + ". Attempting to launch application context");
                Properties properties = new Properties();
                InputStream input;
                try {
                    input = new FileInputStream(listOfFile);
                    properties.load(input);
                    if (properties.getProperty("globalSocketTimeout") != null) {
                        TcpHelper.setSocketTimeout(
                                Integer.valueOf(properties.getProperty("globalSocketTimeout")));
                    }//from   w  w  w.  ja  v  a2s .co m
                    Map<String, Object> map = new HashMap<>();
                    properties.forEach((k, v) -> {
                        map.put(k.toString(), v);
                    });
                    ConfigurableEnvironment environment = new StandardEnvironment();
                    MutablePropertySources propertySources = environment.getPropertySources();
                    propertySources.addFirst(new MapPropertySource(listOfFile.getName(), map));
                    @SuppressWarnings("resource")
                    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
                    ctx.registerShutdownHook();
                    ctx.setEnvironment(environment);
                    String scheduling;
                    try {
                        scheduling = properties.getProperty("scheduler.useScheduling");
                        if (scheduling.equalsIgnoreCase("true")) {
                            ctx.register(ScheduledJobLauncher.class);
                            ctx.refresh();
                        } else if (scheduling.equalsIgnoreCase("false")) {
                            ctx.register(SingleJobLauncher.class);
                            ctx.refresh();
                            SingleJobLauncher launcher = ctx.getBean(SingleJobLauncher.class);
                            launcher.launchJob();
                        } else if (scheduling.equalsIgnoreCase("slave")) {
                            ctx.register(JobConfiguration.class);
                            ctx.refresh();
                        } else {
                            throw new RuntimeException(
                                    "useScheduling not configured. Must be true, false or slave");
                        }
                    } catch (NullPointerException ex) {
                        throw new RuntimeException(
                                "useScheduling not configured. Must be true, false or slave");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:org.greencheek.utils.environment.propertyplaceholder.examples.spring.profile.AppBootstrap.java

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer config = new PropertySourcesPlaceholderConfigurer();

    MutablePropertySources sources = new MutablePropertySources();
    sources.addFirst(new PropertiesPropertySource("p", environmentalProperties));

    config.setPropertySources(sources);//from  w  ww .  j a v a 2 s. co m

    return config;
}

From source file:com.cloudera.director.aws.common.PropertyResolvers.java

/**
 * Creates a new property resolver that gets properties from the given map.
 *
 * @param m property map//  w ww .  j  av  a2s .c  o  m
 * @return new property resolver
 * @throws NullPointerException if the map is null
 */
public static PropertyResolver newMapPropertyResolver(Map<String, String> m) {
    checkNotNull(m, "map is null");
    MutablePropertySources sources = new MutablePropertySources();
    sources.addFirst(new MapPropertySource("map", ImmutableMap.<String, Object>copyOf(m)));
    return new PropertySourcesPropertyResolver(sources);
}

From source file:org.openbaton.autoscaling.utils.Utils.java

public static void loadExternalProperties(ConfigurableEnvironment properties) {
    if (properties.containsProperty("external-properties-file")
            && properties.getProperty("external-properties-file") != null) {
        try {/*from  ww  w . ja v  a2 s. c  o  m*/
            InputStream is = new FileInputStream(new File(properties.getProperty("external-properties-file")));
            Properties externalProperties = new Properties();
            externalProperties.load(is);
            PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(
                    "external-properties", externalProperties);

            MutablePropertySources propertySources = properties.getPropertySources();
            propertySources.addFirst(propertiesPropertySource);
        } catch (IOException e) {
            log.warn("Not found external-properties-file: "
                    + properties.getProperty("external-properties-file"));
        }
    }
}

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

/**
 * Tries to retrieve the named PropertySource from the environment. If not found it creates a
 * new one.//from  www  . j  a v  a2s . com
 * <p>
 *
 * @param aEnv
 * @param aPropertySourceName
 * @return the embedded property map
 * @throws SdiException if the found property source is not instance of PropertiesPropertySource
 */
public static Map<String, Object> getOrCreatePropertySource(ConfigurableEnvironment aEnv,
        String aPropertySourceName) throws SdiException {
    MutablePropertySources mps = aEnv.getPropertySources();
    PropertySource<?> ps = mps.get(aPropertySourceName);
    PropertiesPropertySource pps = null;

    if (ps == null) {
        Properties props = new Properties();
        pps = new PropertiesPropertySource(aPropertySourceName, props);
        mps.addFirst(pps);
    } else {
        if (!(ps instanceof PropertiesPropertySource)) {
            throw new SdiException("Found property source is not instance of PropertiesPropertySource "
                    + " but: " + ps.getClass().getName(), SdiException.EXIT_CODE_CONFIG_ERROR);
        } // if !( ps instanceof PropertiesPropertySource )

        pps = (PropertiesPropertySource) ps;
    }

    Map<String, Object> map = pps.getSource();
    return map;
}

From source file:io.bitsquare.app.BitsquareEnvironment.java

BitsquareEnvironment(PropertySource commandLineProperties) {
    String userDataDir = commandLineProperties.containsProperty(USER_DATA_DIR_KEY)
            ? (String) commandLineProperties.getProperty(USER_DATA_DIR_KEY)
            : DEFAULT_USER_DATA_DIR;//  www . j  a va2s.  c  om

    this.appName = commandLineProperties.containsProperty(APP_NAME_KEY)
            ? (String) commandLineProperties.getProperty(APP_NAME_KEY)
            : DEFAULT_APP_NAME;

    this.appDataDir = commandLineProperties.containsProperty(APP_DATA_DIR_KEY)
            ? (String) commandLineProperties.getProperty(APP_DATA_DIR_KEY)
            : appDataDir(userDataDir, appName);

    MutablePropertySources propertySources = this.getPropertySources();
    propertySources.addFirst(commandLineProperties);
    try {
        propertySources.addLast(filesystemProperties());
        propertySources.addLast(classpathProperties());
        propertySources.addLast(defaultProperties());
    } catch (Exception ex) {
        throw new BitsquareException(ex);
    }
}

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

/**
 * Test method for {@link ch.sdi.core.impl.cfg.ConfigUtils#getPropertyNamesStartingWith(Class)}.
 *///w w w.  j a  v a2 s  . c  o  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.textocat.textokit.eval.matching.MatchingConfigurationInitializerTest.java

private PropertyResolver makePropertyResolver(Map<String, Object> properties) {
    MutablePropertySources propSources = new MutablePropertySources();
    propSources.addFirst(new MapPropertySource("default", properties));
    PropertyResolver result = new PropertySourcesPropertyResolver(propSources);
    return result;
}

From source file:io.gravitee.management.idp.core.plugin.impl.IdentityProviderManagerImpl.java

private <T> T create(Plugin plugin, Class<T> identityClass, Map<String, Object> properties) {
    if (identityClass == null) {
        return null;
    }/*from   w ww.j a v  a2  s .  c om*/

    try {
        T identityObj = createInstance(identityClass);
        final Import annImport = identityClass.getAnnotation(Import.class);
        Set<Class<?>> configurations = (annImport != null) ? new HashSet<>(Arrays.asList(annImport.value()))
                : Collections.emptySet();

        ApplicationContext idpApplicationContext = pluginContextFactory
                .create(new AnnotationBasedPluginContextConfigurer(plugin) {
                    @Override
                    public Set<Class<?>> configurations() {
                        return configurations;
                    }

                    @Override
                    public ConfigurableEnvironment environment() {
                        return new StandardEnvironment() {
                            @Override
                            protected void customizePropertySources(MutablePropertySources propertySources) {
                                propertySources.addFirst(new MapPropertySource(plugin.id(), properties));
                                super.customizePropertySources(propertySources);
                            }
                        };
                    }
                });

        idpApplicationContext.getAutowireCapableBeanFactory().autowireBean(identityObj);

        return identityObj;
    } catch (Exception ex) {
        LOGGER.error("An unexpected error occurs while loading identity provider", ex);
        return null;
    }
}