List of usage examples for org.springframework.core.env ConfigurableEnvironment getPropertySources
MutablePropertySources getPropertySources();
From source file:com.devnexus.ting.web.config.DefaultApplicationContextInitializer.java
@Override public void initialize(ConfigurableApplicationContext applicationContext) { final CloudEnvironment env = new CloudEnvironment(); if (env.getInstanceInfo() != null) { LOGGER.info("cloud API: " + env.getCloudApiUri()); applicationContext.getEnvironment().setActiveProfiles("cloud", SpringContextMode.DemoContextConfiguration.getCode()); } else {//from w w w .j av a 2 s . co m final String profile = System.getProperty("ting-spring-profile"); if (profile == null) { LOGGER.info("System property 'ting-spring-profile' not set. Setting active profile to '{}'.", SpringContextMode.DemoContextConfiguration.getCode()); applicationContext.getEnvironment() .setActiveProfiles(SpringContextMode.DemoContextConfiguration.getCode()); } else { applicationContext.getEnvironment().setActiveProfiles(profile); } } final ConfigurableEnvironment environment = applicationContext.getEnvironment(); if (environment.acceptsProfiles(SpringProfile.STANDALONE)) { final String tingHome = environment.getProperty(Apphome.APP_HOME_DIRECTORY); final ResourcePropertySource propertySource; final String productionPropertySourceLocation = "file:" + tingHome + File.separator + SystemInformationUtils.TING_CONFIG_FILENAME; try { propertySource = new ResourcePropertySource(productionPropertySourceLocation); } catch (IOException e) { throw new IllegalStateException( "Unable to get ResourcePropertySource '" + productionPropertySourceLocation + "'", e); } environment.getPropertySources().addFirst(propertySource); LOGGER.info("Properties for standalone mode loaded [" + productionPropertySourceLocation + "]"); } else { final String demoPropertySourceLocation = "classpath:ting-demo.properties"; final ResourcePropertySource propertySource; try { propertySource = new ResourcePropertySource(demoPropertySourceLocation); } catch (IOException e) { throw new IllegalStateException( "Unable to get ResourcePropertySource '" + demoPropertySourceLocation + "'", e); } environment.getPropertySources().addFirst(propertySource); LOGGER.info("Properties for demo mode loaded [" + demoPropertySourceLocation + "]"); } final boolean mailEnabled = environment.getProperty("mail.enabled", Boolean.class, Boolean.FALSE); final boolean twitterEnabled = environment.getProperty("twitter.enabled", Boolean.class, Boolean.FALSE); final boolean websocketEnabled = environment.getProperty("websocket.enabled", Boolean.class, Boolean.FALSE); if (mailEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.MAIL_ENABLED); } if (twitterEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.TWITTER_ENABLED); } if (websocketEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.WEBSOCKET_ENABLED); } }
From source file:io.spring.initializr.web.autoconfigure.CloudfoundryEnvironmentPostProcessor.java
@Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication springApplication) { Map<String, Object> map = new LinkedHashMap<>(); String uri = environment.getProperty("vcap.services.stats-index.credentials.uri"); if (StringUtils.hasText(uri)) { UriComponents uriComponents = UriComponentsBuilder.fromUriString(uri).build(); String userInfo = uriComponents.getUserInfo(); if (StringUtils.hasText(userInfo)) { String[] credentials = userInfo.split(":"); map.put("initializr.stats.elastic.username", credentials[0]); map.put("initializr.stats.elastic.password", credentials[1]); }// www.ja va2 s .c o m map.put("initializr.stats.elastic.uri", UriComponentsBuilder.fromUriString(uri).userInfo(null).build().toString()); addOrReplace(environment.getPropertySources(), map); } }
From source file:it.scoppelletti.programmerpower.console.spring.ConsoleApplicationRunner.java
/** * Inizializza il contesto dell’applicazione. * /* w w w. ja va 2 s . c o m*/ * @param ui Interfaccia utente. * @return Oggetto. */ private GenericApplicationContext initApplicationContext(UserInterfaceProvider ui) { SingletonBeanRegistry beanRegistry; GenericApplicationContext ctx = null; GenericApplicationContext applCtx; XmlBeanDefinitionReader reader; ConfigurableEnvironment env; PropertySource<?> propSource; MutablePropertySources propSources; try { ctx = new GenericApplicationContext(); reader = new XmlBeanDefinitionReader(ctx); reader.loadBeanDefinitions(ConsoleApplicationRunner.CONSOLE_CONTEXT); reader.loadBeanDefinitions(initApplicationContextResourceName()); beanRegistry = ctx.getBeanFactory(); beanRegistry.registerSingleton(ConsoleApplicationRunner.BEAN_NAME, this); beanRegistry.registerSingleton(UserInterfaceProvider.BEAN_NAME, ui); env = ctx.getEnvironment(); // Acquisisco gli eventuali profili configurati prima di aggiungere // quello di Programmer Power env.getActiveProfiles(); env.addActiveProfile(ConsoleApplicationRunner.PROFILE); propSources = env.getPropertySources(); propSources.addFirst(new ConsolePropertySource(ConsolePropertySource.class.getName(), this)); propSource = BeanConfigUtils.loadPropertySource(); if (propSource != null) { propSources.addFirst(propSource); } ctx.refresh(); applCtx = ctx; ctx = null; } finally { if (ctx != null) { ctx.close(); ctx = null; } } return applCtx; }
From source file:org.carewebframework.ui.spring.FrameworkAppContext.java
/** * Constructor for creating an application context. Disallows bean overrides by default. * /*from ww w . jav a 2 s .co m*/ * @param desktop The desktop associated with this application context. Will be null for the * root application context. * @param testConfig If true, use test profiles. * @param locations Optional list of configuration file locations. If not specified, defaults to * the default configuration locations ({@link #getDefaultConfigLocations}). */ public FrameworkAppContext(Desktop desktop, boolean testConfig, String... locations) { super(); setAllowBeanDefinitionOverriding(false); this.desktop = desktop; ConfigurableEnvironment env = getEnvironment(); Set<String> aps = new LinkedHashSet<String>(); Collections.addAll(aps, env.getActiveProfiles()); if (desktop != null) { desktop.setAttribute(APP_CONTEXT_ATTRIB, this); final Session session = desktop.getSession(); final ServletContext sc = session.getWebApp().getServletContext(); final WebApplicationContext rootContext = WebApplicationContextUtils .getRequiredWebApplicationContext(sc); setDisplayName("Child XmlWebApplicationContext " + desktop); setParent(rootContext); setServletContext(sc); this.ctxListener = new ContextClosedListener(); getParent().getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class) .addApplicationListener(this.ctxListener); // Set up profiles (remove root profiles merged from parent) aps.removeAll(Arrays.asList(Constants.PROFILES_ROOT)); Collections.addAll(aps, testConfig ? Constants.PROFILES_DESKTOP_TEST : Constants.PROFILES_DESKTOP_PROD); } else { AppContextFinder.rootContext = this; Collections.addAll(aps, testConfig ? Constants.PROFILES_ROOT_TEST : Constants.PROFILES_ROOT_PROD); env.getPropertySources().addLast(new LabelPropertySource(this)); env.getPropertySources().addLast(new DomainPropertySource(this)); } env.setActiveProfiles(aps.toArray(new String[aps.size()])); setConfigLocations(locations == null || locations.length == 0 ? null : locations); }
From source file:com.devnexus.ting.DefaultApplicationContextInitializer.java
@Override public void initialize(ConfigurableApplicationContext applicationContext) { final CloudEnvironment env = new CloudEnvironment(); if (env.getInstanceInfo() != null) { LOGGER.info("Running in the cloud - API: " + env.getCloudApiUri()); applicationContext.getEnvironment().setActiveProfiles(SpringProfile.CLOUD); } else {//from w w w . j a v a2 s .com final Apphome apphome = SystemInformationUtils.retrieveBasicSystemInformation(); SpringContextMode springContextMode; LOGGER.info("DevNexus Apphome: " + apphome); if (SystemInformationUtils.existsConfigFile(apphome.getAppHomePath())) { springContextMode = SpringContextMode.ProductionContextConfiguration; } else { springContextMode = SpringContextMode.DemoContextConfiguration; } applicationContext.getEnvironment().setActiveProfiles(springContextMode.getCode()); } final ConfigurableEnvironment environment = applicationContext.getEnvironment(); if (environment.acceptsProfiles(SpringProfile.STANDALONE)) { final String tingHome = environment.getProperty(Apphome.APP_HOME_DIRECTORY); final PropertySource<?> propertySource; final YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader(); final String productionPropertySourceLocation; final Apphome apphome = SystemInformationUtils.retrieveBasicSystemInformation(); if (apphome.getAppHomeSource() == AppHomeSource.USER_DIRECTORY) { productionPropertySourceLocation = "file:" + apphome.getAppHomePath() + File.separator + SystemInformationUtils.TING_CONFIG_FILENAME; } else { productionPropertySourceLocation = "file:" + tingHome + File.separator + SystemInformationUtils.TING_CONFIG_FILENAME; } try { propertySource = yamlPropertySourceLoader.load("devnexus-standalone", new DefaultResourceLoader().getResource(productionPropertySourceLocation), null); } catch (IOException e) { throw new IllegalStateException( "Unable to get ResourcePropertySource '" + productionPropertySourceLocation + "'", e); } environment.getPropertySources().addFirst(propertySource); LOGGER.info("Properties for standalone mode loaded [" + productionPropertySourceLocation + "]."); } else { LOGGER.info("Using Properties for demo mode."); } final String emailProviderAsString = environment.getProperty("devnexus.mail.emailProvider"); final EmailProvider emailProvider = EmailProvider.valueOf(emailProviderAsString.trim().toUpperCase()); final boolean twitterEnabled = environment.getProperty("devnexus.twitter.enabled", Boolean.class, Boolean.FALSE); final boolean websocketEnabled = environment.getProperty("devnexus.websocket.enabled", Boolean.class, Boolean.FALSE); final boolean payPalEnabled = environment.containsProperty("PAYPAL_MODE"); LOGGER.info("Uses Settings:" + "\nEmail Provider: " + emailProvider + "\nTwitter Enabled: " + twitterEnabled + "\nPayPal Enabled: " + payPalEnabled + "\nWebsocket Enabled: " + websocketEnabled); if (EmailProvider.SENDGRID.equals(emailProvider)) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.SENDGRID_ENABLED); } else if (EmailProvider.SMTP.equals(emailProvider)) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.SMTP_ENABLED); } else if (EmailProvider.AMAZON_SES.equals(emailProvider)) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.AMAZON_SES_ENABLED); } else if (EmailProvider.NONE.equals(emailProvider)) { } else { throw new IllegalArgumentException("Unknown EmailProvider: " + emailProvider); } if (!EmailProvider.NONE.equals(emailProvider)) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.MAIL_ENABLED); } if (twitterEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.TWITTER_ENABLED); } if (websocketEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.WEBSOCKET_ENABLED); } if (payPalEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_ENABLED); switch (environment.getProperty("PAYPAL_MODE")) { case "live": applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_LIVE); break; default: applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_SANDBOX); break; } } if (environment.getProperty("DEVELOPMENT_MODE", Boolean.class, Boolean.FALSE)) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.DEVELOPMENT_ENABLED); } }
From source file:org.alfresco.bm.api.v1.RestAPITest.java
@Before public void setUp() throws Exception { gson = new Gson(); // Create a mock DB to connect to mockDBFactory = new MongoDBForTestsFactory(); mongoHost = mockDBFactory.getMongoHost(); String database = mockDBFactory.getObject().getName(); // Create an application context (don't start, yet) ctx = new ClassPathXmlApplicationContext(new String[] { PATH_APP_CONTEXT }, false); // Pass our properties to the new context Properties ctxProperties = new Properties(); {/*from w ww .ja v a2s . c o m*/ ctxProperties.put(PROP_MONGO_CONFIG_HOST, mongoHost); ctxProperties.put(PROP_MONGO_CONFIG_DATABASE, database); ctxProperties.put(PROP_MONGO_TEST_DATABASE, MONGO_TEST_DATABASE); ctxProperties.put(PROP_APP_RELEASE, RELEASE); ctxProperties.put(PROP_APP_SCHEMA, "" + SCHEMA); ctxProperties.put(PROP_APP_INHERITANCE, "COMMON, TEST"); ctxProperties.put(PROP_TEST_RUN_MONITOR_PERIOD, "" + 20000); ctxProperties.put(PROP_SYSTEM_CAPABILITIES, "Java"); ctxProperties.put(PROP_APP_CONTEXT_PATH, "/"); ctxProperties.put(PROP_APP_DIR, "."); } ConfigurableEnvironment ctxEnv = ctx.getEnvironment(); ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("RestAPITest", ctxProperties)); // Override all properties with system properties ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("system", System.getProperties())); // Start the context now ctx.refresh(); // Get beans dao = ctx.getBean(MongoTestDAO.class); appDB = dao.getDb(); TestServiceImpl testService = ctx.getBean(TestServiceImpl.class); LogService logService = ctx.getBean(LogService.class); this.testRunServicesCache = ctx.getBean(TestRunServicesCache.class); api = new TestRestAPI(dao, testService, logService, testRunServicesCache); }
From source file:org.alfresco.bm.test.TestRun.java
/** * Called to ensure that the application context is started. * <p/>//from w ww . j a va2 s. c o m * Note that we only pull out the test and test run names at this point so that we don't end up * using stale data. */ private synchronized void start() { DBObject runObj = getRunObj(true); if (runObj == null) { // Nothing much we can do here return; } // Check the application context if (testRunCtx != null) { // There is nothing to do, the context is already available return; } // INFO logging as this is a critical part of the whole application if (logger.isInfoEnabled()) { logger.info("Starting test run application context: " + runObj); } ObjectId testObjId = (ObjectId) runObj.get(FIELD_TEST); ObjectId runObjId = (ObjectId) runObj.get(FIELD_ID); String run = (String) runObj.get(FIELD_NAME); // We need to build the test run FQN out of the test run details DBObject testObj = testDAO.getTest(testObjId, false); if (testObj == null) { logger.warn("The test associated with the test run has been removed: " + runObj); logger.warn("The test run will be stopped and deleted: " + id); stop(); testDAO.deleteTestRun(id); return; } String test = (String) testObj.get(FIELD_NAME); String release = (String) testObj.get(FIELD_RELEASE); Integer schema = (Integer) testObj.get(FIELD_SCHEMA); String testRunFqn = test + "." + run; // Extract the current properties for the run Set<String> propsToMask = new HashSet<String>(7); Properties testRunProps = new Properties(); { testRunProps.put(PROP_DRIVER_ID, driverId); testRunProps.put(PROP_TEST, test); testRunProps.put(PROP_TEST_RUN, run); testRunProps.put(PROP_TEST_RUN_ID, id.toString()); testRunProps.put(PROP_TEST_RUN_FQN, testRunFqn); BasicDBList propObjs = (BasicDBList) runObj.get(FIELD_PROPERTIES); for (Object obj : propObjs) { DBObject propObj = (DBObject) obj; String propName = (String) propObj.get(FIELD_NAME); String propDef = (String) propObj.get(FIELD_DEFAULT); String propValue = (String) propObj.get(FIELD_VALUE); if (propValue == null) { propValue = propDef; } testRunProps.put(propName, propValue); // Check on the masking for later reporting boolean mask = Boolean.parseBoolean((String) propObj.get(FIELD_MASK)); if (mask) { propsToMask.add(propName); } } } // Create the child application context WITHOUT AUTOSTART // TODO: This is hard coded to "config/spring/test-context.xml". It should be one of the // test definition properties and have the same as default. ClassPathXmlApplicationContext testRunCtx = new ClassPathXmlApplicationContext( new String[] { PATH_TEST_CONTEXT }, false); // When running stand-alone, there might not be a parent context if (parentCtx != null) { testRunCtx.setParent(parentCtx); } // Push cluster properties into the context (must be done AFTER setting parent context) ConfigurableEnvironment ctxEnv = testRunCtx.getEnvironment(); ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("run-props", testRunProps)); ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("system-props", System.getProperties())); // Complete logging of what is going to be used for the test if (logger.isInfoEnabled()) { String nl = "\n"; StringBuilder sb = new StringBuilder(1024); sb.append("Test run application context starting: ").append(nl).append(" Run ID: ").append(id) .append(nl).append(" Test Name: ").append(test).append(nl).append(" Run Name: ") .append(run).append(nl).append(" Driver ID: ").append(driverId).append(nl) .append(" Release: ").append(release).append(nl).append(" Schema: ") .append(schema).append(nl).append(" Test Run Properties: ").append(nl); for (Object propNameObj : testRunProps.keySet()) { String propName = (String) propNameObj; String propValue = testRunProps.getProperty(propName); if (propsToMask.contains(propName) || propName.toLowerCase().contains("username") || propName.toLowerCase().contains("password")) { propValue = MASK; } sb.append(" ").append(propName).append("=").append(propValue).append(nl); } sb.append(" System Properties: ").append(nl); for (Object propNameObj : System.getProperties().keySet()) { String propName = (String) propNameObj; String propValue = System.getProperty(propName); if (propsToMask.contains(propName) || propName.toLowerCase().contains("username") || propName.toLowerCase().contains("password")) { propValue = MASK; } sb.append(" ").append(propName).append("=").append(propValue).append(nl); } logger.info(sb); } // Now refresh (to load beans) and start try { this.testRunCtx = testRunCtx; // 2015-08-04 fkbecker: store definitions first - for refresh() or start() may fail, too. this.test = test; this.run = run; this.release = release; this.schema = schema; testRunCtx.refresh(); testRunCtx.start(); // Make sure that the required components are present and of the correct type // There may be multiple beans of the type, so we have to use the specific bean name. @SuppressWarnings("unused") CompletionEstimator estimator = (CompletionEstimator) testRunCtx.getBean("completionEstimator"); @SuppressWarnings("unused") EventProcessor startEventProcessor = (EventProcessor) testRunCtx.getBean("event.start"); // Register the driver with the test run testDAO.addTestRunDriver(runObjId, driverId); // Log the successful startup logService.log(driverId, test, run, LogLevel.INFO, "Successful startup of test run '" + testRunFqn + "'."); } catch (Exception e) { /* Throwable root = ExceptionUtils.getRootCause(e); if (root != null && (root instanceof MongoException || root instanceof IOException)) { // 2015-08-04 fkbecker IOException also thrown by FTP file service if host not reachable ... // FIXME String msg1 = "Failed to start test run application '" + testRunFqn + "': " + e.getCause().getMessage(); //String msg2 = "Set the test run property '" + PROP_MONGO_TEST_HOST + "' (<server>:<port>) as required."; // We deal with this specifically as it's a simple case of not finding the MongoDB logger.error(msg1); //logger.error(msg2); logService.log(driverId, test, run, LogLevel.ERROR, msg1); //logService.log(driverId, test, run, LogLevel.ERROR, msg2); } else {*/ String stack = ExceptionUtils.getStackTrace(e); logger.error("Failed to start test run application '" + testRunFqn + "': ", e); String error = "Failed to start test run application '" + testRunFqn + ". \r\n" + stack; logService.log(driverId, test, run, LogLevel.ERROR, error); //} stop(); } }