Example usage for org.springframework.core.env ConfigurableEnvironment getPropertySources

List of usage examples for org.springframework.core.env ConfigurableEnvironment getPropertySources

Introduction

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

Prototype

MutablePropertySources getPropertySources();

Source Link

Document

Return the PropertySources for this Environment in mutable form, allowing for manipulation of the set of PropertySource objects that should be searched when resolving properties against this Environment object.

Usage

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.security.preauth.WebAnnoApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext aApplicationContext) {
    WebAnnoLoggingFilter.setLoggingUsername("SYSTEM");

    log.info("  _      __    __   ___                ");
    log.info(" | | /| / /__ / /  / _ | ___  ___  ___ ");
    log.info(" | |/ |/ / -_) _ \\/ __ |/ _ \\/ _ \\/ _ \\");
    log.info(" |__/|__/\\__/_.__/_/ |_/_//_/_//_/\\___/");
    log.info(SettingsUtil.getVersionString());

    ConfigurableEnvironment aEnvironment = aApplicationContext.getEnvironment();

    File settings = SettingsUtil.getSettingsFile();

    // If settings were found, add them to the environment
    if (settings != null) {
        log.info("Settings: " + settings);
        try {/*from w w w  .j  a  va2 s .c om*/
            aEnvironment.getPropertySources()
                    .addFirst(new ResourcePropertySource(new FileSystemResource(settings)));
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    // Activate bean profile depending on authentication mode
    if (AUTH_MODE_PREAUTH.equals(aEnvironment.getProperty(PROP_AUTH_MODE))) {
        aEnvironment.setActiveProfiles(PROFILE_PREAUTH);
        log.info("Authentication: pre-auth");
    } else {
        aEnvironment.setActiveProfiles(PROFILE_DATABASE);
        log.info("Authentication: database");
    }
}

From source file:com.capgemini.boot.core.factory.internal.SpringBootSettingsResolver.java

@SuppressWarnings("unchecked")
@Override/*from w ww .jav a2s. co m*/
public <T> T resolveSettings(Class<T> settingsClass, String prefix, ConfigurableEnvironment environment) {
    try {
        T newSettings = (T) Class.forName(settingsClass.getName()).newInstance();

        PropertiesConfigurationFactory<Object> factory = new PropertiesConfigurationFactory<Object>(
                newSettings);
        factory.setTargetName(prefix);
        factory.setPropertySources(environment.getPropertySources());
        factory.setConversionService(environment.getConversionService());
        factory.bindPropertiesToTarget();

        return newSettings;
    } catch (Exception ex) {
        throw new FatalBeanException("Could not bind DataSourceSettings properties", ex);
    }
}

From source file:org.osiam.OsiamHome.java

public void configure(ConfigurableEnvironment environment) {
    String rawOsiamHome = environment.getProperty("osiam.home", System.getenv("HOME") + "/.osiam");
    checkState(!Strings.isNullOrEmpty(rawOsiamHome), "'osiam.home' is not set");
    osiamHome = Paths.get(rawOsiamHome).toAbsolutePath();
    environment.getPropertySources().addFirst(new PropertySource<Path>("osiamHome", osiamHome) {
        @Override//from w w w  .  j  a v  a 2  s.c o  m
        public Object getProperty(String name) {
            return "osiam.home".equals(name) ? source.toString() : null;
        }
    });
}

From source file:com.example.journal.env.JournalEnvironmentPostProcessor.java

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    Map<String, Object> map = new LinkedHashMap<>();
    contributeDefaults(map, new ClassPathResource("journal.yml"));
    map.put("spring.cloud.stream.bindings." + JournalSink.INPUT + ".content-type",
            "application/x-java-object;type=" + JournalEntry.class.getName());
    addOrReplace(environment.getPropertySources(), map);
}

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

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    try {//from ww  w. j a  v a  2  s.com
        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:io.lavagna.common.LavagnaEnvironment.java

public LavagnaEnvironment(ConfigurableEnvironment environment) {
    this.environment = environment;

    if (environment.containsProperty(LAVAGNA_CONFIG_LOCATION)
            && StringUtils.isNotBlank(environment.getProperty(LAVAGNA_CONFIG_LOCATION))) {

        String configLocation = environment.getProperty(LAVAGNA_CONFIG_LOCATION);

        LOG.info("Detected config file {}, loading it", configLocation);
        try {/*from   ww  w  .j ava  2  s  .co  m*/
            environment.getPropertySources()
                    .addFirst(new ResourcePropertySource(new UrlResource(configLocation)));
        } catch (IOException ioe) {
            throw new IllegalStateException(
                    "error while loading external configuration file at " + configLocation, ioe);
        }
    }

    setSystemPropertyIfNull(environment, "datasource.dialect", "HSQLDB");
    setSystemPropertyIfNull(environment, "datasource.url", "jdbc:hsqldb:mem:lavagna");
    setSystemPropertyIfNull(environment, "datasource.username", "sa");
    setSystemPropertyIfNull(environment, "datasource.password", "");
    setSystemPropertyIfNull(environment, "spring.profiles.active", "dev");

    logUse("datasource.dialect");
    logUse("datasource.url");
    logUse("datasource.username");
    logUse("spring.profiles.active");

}

From source file:it.scoppelletti.programmerpower.web.spring.config.WebApplicationContextInitializer.java

/**
 * Inizializzazione./*from   ww w . j  a  v a2s . c o  m*/
 * 
 * @param applCtx Contesto dell&rsquo;applicazione.
 */
public void initialize(AbstractRefreshableWebApplicationContext applCtx) {
    ConfigurableEnvironment env;
    PropertySource<?> propSource;
    MutablePropertySources propSources;

    env = applCtx.getEnvironment();

    // Acquisisco gli eventuali profili configurati prima di aggiungere
    // quelli di Programmer Power
    env.getActiveProfiles();

    env.addActiveProfile(WebApplicationContextInitializer.PROFILE);
    env.addActiveProfile(DataUtils.PROFILE);

    propSources = env.getPropertySources();

    propSource = BeanConfigUtils.loadPropertySource();
    if (propSource != null) {
        propSources.addFirst(propSource);
    }

    propSources.addLast(new WebPropertySource(WebPropertySource.class.getName(), applCtx));
}

From source file:org.jrecruiter.web.config.DefaultApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    final String profile = System.getProperty("jrecruiter-spring-profile");

    if (profile == null) {
        LOGGER.info("System property 'jrecruiter-spring-profile' not set. Setting active profile to '{}'.",
                SpringContextMode.DemoContextConfiguration.getCode());
        applicationContext.getEnvironment()
                .setActiveProfiles(SpringContextMode.DemoContextConfiguration.getCode());
    } else {//from  w  w w  .  j  a v  a2  s .c  om
        applicationContext.getEnvironment().setActiveProfiles(profile);
    }

    final ConfigurableEnvironment environment = applicationContext.getEnvironment();

    if (environment.acceptsProfiles("standalone")) {
        String tingHome = environment.getProperty(Apphome.APP_HOME_DIRECTORY);
        try {
            ResourcePropertySource source = new ResourcePropertySource(
                    "file:" + tingHome + File.separator + SystemInformationUtils.JRECRUITER_CONFIG_FILENAME);
            environment.getPropertySources().addFirst(source);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Properties for standalone mode loaded");
    } else {
        try {
            environment.getPropertySources()
                    .addFirst(new ResourcePropertySource("classpath:jrecruiter-demo.properties"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Properties for demo mode loaded");
    }

    final Boolean twitterEnabled = environment.getProperty("twitter.enabled", Boolean.class, Boolean.FALSE);

    if (twitterEnabled) {
        applicationContext.getEnvironment().addActiveProfile("twitter-enabled");
    }
    System.out.println("::Twitter enabled: " + twitterEnabled);

    final Boolean mailEnabled = environment.getProperty("mail.enabled", Boolean.class, Boolean.FALSE);

    if (mailEnabled) {
        applicationContext.getEnvironment().addActiveProfile("mail-enabled");
    }
    System.out.println("::Mail enabled: " + mailEnabled);

    final Boolean bitlyEnabled = environment.getProperty("mail.enabled", Boolean.class, Boolean.FALSE);

    if (bitlyEnabled) {
        applicationContext.getEnvironment().addActiveProfile("bitly-enabled");
    }
    System.out.println("::Bitly enabled: " + bitlyEnabled);
}

From source file:org.alfresco.bm.tools.BMTestRunner.java

/**
 * Execute the default test against the given MongoDB or an in-memory instance
 * /*from   ww  w.  j ava2s.c om*/
 * @param mongoConfigHost           the MongoDB host to connect to for configuraton data or <tt>null</tt> to use an in-memory version
 * @param mongoTestHost             the MongoDB host to connect to for test data data or <tt>null</tt> to use the same database as the config
 * @param testProperties            any properties to specifically set for the test or <tt>null</tt> if there are none
 */
public void run(String mongoConfigHost, String mongoTestHost, Properties testProperties) throws Exception {
    // Secure the listeners against modification
    List<BMTestRunnerListener> listeners = new ArrayList<BMTestRunnerListener>(this.listeners);

    // If no MongoDB URL is provided, then we have to start one
    MongoDBForTestsFactory mongoDBForTestsFactory = null;
    ClassPathXmlApplicationContext ctx = null;
    try {
        // Ensure that required system properties are present
        System.setProperty(PROP_APP_CONTEXT_PATH, System.getProperty("user.dir"));
        System.setProperty(PROP_APP_DIR, System.getProperty("user.dir"));

        // Create a MongoDB for use if one has not been specified
        if (mongoConfigHost == null) {
            mongoDBForTestsFactory = new MongoDBForTestsFactory();
            String uriWithoutDB = mongoDBForTestsFactory.getMongoURIWithoutDB();
            mongoConfigHost = new MongoClientURI(uriWithoutDB).getHosts().get(0);
        }
        // Fill in the URI for the test MongoDB
        if (mongoTestHost == null) {
            mongoTestHost = mongoConfigHost;
        }

        // Fill in the properties required for the test
        Properties mongoProps = new Properties();
        mongoProps.put(PROP_MONGO_CONFIG_HOST, mongoConfigHost);

        // Construct the application context
        ctx = new ClassPathXmlApplicationContext(new String[] { PATH_APP_CONTEXT }, false);
        // Push cluster properties into the context (must be done AFTER setting parent context)
        ConfigurableEnvironment ctxEnv = ctx.getEnvironment();
        // Mongo properties come first
        ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("mongo-props", mongoProps));
        // Finally, system properties overrule them all
        ctxEnv.getPropertySources()
                .addFirst(new PropertiesPropertySource("system-props", System.getProperties()));

        // Kick it all off
        try {
            ctx.refresh();
        } catch (Exception e) {
            Throwable root = ExceptionUtils.getRootCause(e);
            if (root != null
                    && (root instanceof MongoSocketException || root instanceof UnknownHostException)) {
                // We deal with this specifically as it's a simple case of not finding the MongoDB
                logger.error("Set the configuration property '" + PROP_MONGO_CONFIG_HOST
                        + "' (<server>:<port>) as required.");
            } else {
                // Log application start failure because test frameworks might not do so nicely
                logger.error("Failed to start application.", e);
            }
            throw new RuntimeException("Failed to start application.", e);
        }

        // Get the test
        Test test = ctx.getBean(Test.class);
        String release = test.getRelease();
        Integer schema = test.getSchema();

        TestRestAPI api = ctx.getBean(TestRestAPI.class);

        // Create a new test
        TestDetails testDetails = new TestDetails();
        String testName = "BMTestRunner_" + System.currentTimeMillis();
        testDetails.setName(testName);
        testDetails.setDescription("Test created by BMTestRunner on " + new Date());
        testDetails.setRelease(release);
        testDetails.setSchema(schema);
        api.createTest(testDetails);

        // We need to tell the test which MongoDB to write data to
        PropSetBean propSet = new PropSetBean();
        propSet.setValue(mongoTestHost);
        propSet.setVersion(0);
        api.setTestProperty(testName, PROP_MONGO_TEST_HOST, propSet);

        // Now set any properties that have been explicitly passed in for the test
        if (testProperties != null) {
            for (Map.Entry<Object, Object> entry : testProperties.entrySet()) {
                String propKey = (String) entry.getKey();
                String propVal = (String) entry.getValue();

                propSet.setValue(propVal);
                propSet.setVersion(0);
                api.setTestProperty(testName, propKey, propSet);
            }
        }

        // Call listeners: the test has been created
        for (BMTestRunnerListener listener : listeners) {
            listener.testReady(ctx, testName);
        }

        // Create a new test run
        TestRunDetails testRunDetails = new TestRunDetails();
        String testRunName = "BMTestRunner_" + System.currentTimeMillis();
        testRunDetails.setName(testRunName);
        testRunDetails.setDescription("Test run created by BMTestRunner on " + new Date());
        api.createTestRun(testDetails.getName(), testRunDetails);

        // Call listeners: the test run has been created
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunReady(ctx, testName, testRunName);
        }

        // Get all the test run properties for logging
        String jsonTestRun = api.getTestRun(testName, testRunName);

        // Start the test run
        logger.info("Starting test run: " + testRunName + "\n" + jsonTestRun);
        TestRunSchedule testRunSchedule = new TestRunSchedule();
        testRunSchedule.setScheduled(System.currentTimeMillis());
        api.scheduleTestRun(testName, testRunName, testRunSchedule);

        // Call listeners: the test run has started
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunStarted(ctx, testName, testRunName);
        }

        // Wait for the test run to complete
        long timeInit = System.currentTimeMillis();
        long timeLastChange = -1L;
        String jsonLastChange = null;
        String testRunStateStr = api.getTestRunState(testName, testRunName);

        // Keep looking until the test run completes
        while (!TestRunState.COMPLETED.toString().equals(testRunStateStr)) {
            long now = System.currentTimeMillis();

            // Check that we have not exceeded the maximum time
            if (now - timeInit > maxTestTime) {
                throw new RuntimeException("Test run failed to complete in " + (int) maxTestTime / 1000 + "s.");
            }

            testRunStateStr = api.getTestRunState(testName, testRunName);

            if (TestRunState.SCHEDULED.toString().equals(testRunStateStr) && (now - timeInit) > 10000L) {
                throw new RuntimeException("Test run failed to start in 10s.");
            }

            // Check that there are updates to the test run
            String jsonNow = api.getTestRunSummary(testName, testRunName);
            if (jsonLastChange != null && jsonLastChange.equals(jsonNow)) {
                if ((now - timeLastChange) > 60000L) {
                    throw new RuntimeException("Test run has not been updated in the last 60s");
                }
            }
            // Store values for next iteration
            timeLastChange = now;
            jsonLastChange = jsonNow;

            synchronized (testRunStateStr) {
                try {
                    testRunStateStr.wait(1000L);
                } catch (InterruptedException e) {
                }
            }
        }
        // Call listeners: the test run has finished
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunFinished(ctx, testName, testRunName);
        }
    } finally {
        // Close the context
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                logger.error("Failed to shut down application context.", e);
            }
        }
        // Close the local Mongo instance
        if (mongoDBForTestsFactory != null) {
            try {
                mongoDBForTestsFactory.destroy();
            } catch (Exception e) {
                logger.error("Failed to stop in-memory MongoDB instance.", e);
            }
        }
    }
}

From source file:com.devnexus.ting.common.IntegrationTestApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    LOGGER.info("System property 'ting-spring-profile' not set. Setting active profile to '{}'.",
            SpringContextMode.DemoContextConfiguration.getCode());
    applicationContext.getEnvironment().addActiveProfile(SpringContextMode.DemoContextConfiguration.getCode());

    final ConfigurableEnvironment environment = applicationContext.getEnvironment();

    final String demoPropertySourceLocation = "classpath:application.yml";

    final PropertySource<?> propertySource;
    final YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();

    try {/*from  w w w.  ja v  a  2 s.c o  m*/
        propertySource = yamlPropertySourceLoader.load("devnexus-test",
                new DefaultResourceLoader().getResource(demoPropertySourceLocation), null);
    } catch (IOException e) {
        throw new IllegalStateException(
                "Unable to get ResourcePropertySource '" + demoPropertySourceLocation + "'", e);
    }
    environment.getPropertySources().addFirst(propertySource);

    LOGGER.info("Properties for demo mode loaded [" + demoPropertySourceLocation + "]");

}