public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); configurableEnvironment=environment; Properties props = new Properties(); String databaseMode = environment.getProperty("me.ramon.database-mode"); if (databaseMode != null) { if (databaseMode.equals("hibernate-multitenant")) { props.put("spring.jpa.properties.hibernate.multiTenancy", "DATABASE"); props.put("spring.jpa.properties.hibernate.tenant_identifier_resolver", "me.ramon.multitenancy.BaseCurrentTenantIdentifierResolverImp"); props.put("spring.jpa.properties.hibernate.multi_tenant_connection_provider", "me.ramon.multitenancy.BaseMultiTenantConnectionProviderImp"); } props.put("spring.jpa.hibernate.ddl-auto", "none"); props.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); props.put("hibernate.show_sql", "true"); props.put("logging.level.org.hibernate.SQL", "DEBUG"); props.put("logging.level.org.hibernate.type.descriptor.sql.BasicBinder", "TRACE"); props.put("spring.jpa.properties.hibernate.current_session_context_class", "org.springframework.orm.hibernate4.SpringSessionContext"); environment.getPropertySources().addLast(new PropertiesPropertySource("application1", props)); } }
@SuppressWarnings("unchecked") @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { if (cloud == null) { return; } for (ServiceInfo serviceInfo : cloud.getServiceInfos()) { if (serviceInfoType.isAssignableFrom(serviceInfo.getClass())) { PropertySource<?> propertySource = toPropertySource((T) serviceInfo); event.getEnvironment().getPropertySources().addFirst(propertySource); } } }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { String configFilesString = event.getEnvironment().getProperty("spring.config.location"); List<String> errors = new ArrayList<>(); if (StringUtils.isBlank(configFilesString)) { errors.add("No config file was specified."); } else { for (String configFileString : Splitter.on(',').split(configFilesString)) { File configFile = new File(configFileString); if (!configFile.exists()) { errors.add("Config file " + configFileString + " does not exist."); } else if (!configFile.isFile()) { errors.add("Config file " + configFileString + " is a directory."); } else if (!configFile.canRead()) { errors.add("Config file " + configFileString + " cannot be read."); } } } if (!errors.isEmpty()) { throw new ConfigFileValidationException(errors); } }
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationStartedEvent) { onApplicationStartedEvent((ApplicationStartedEvent) event); } else if (event instanceof ApplicationEnvironmentPreparedEvent) { onApplicationEnvironmentPreparedEvent( (ApplicationEnvironmentPreparedEvent) event); } else if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent((ApplicationPreparedEvent) event); } else if (event instanceof ContextClosedEvent && ((ContextClosedEvent) event) .getApplicationContext().getParent() == null) { onContextClosedEvent(); } }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( event.getEnvironment(), "spring."); if (resolver.containsProperty("mandatoryFileEncoding")) { String encoding = System.getProperty("file.encoding"); String desired = resolver.getProperty("mandatoryFileEncoding"); if (encoding != null && !desired.equalsIgnoreCase(encoding)) { logger.error("System property 'file.encoding' is currently '" + encoding + "'. It should be '" + desired + "' (as defined in 'spring.mandatoryFileEncoding')."); logger.error("Environment variable LANG is '" + System.getenv("LANG") + "'. You could use a locale setting that matches encoding='" + desired + "'."); logger.error("Environment variable LC_ALL is '" + System.getenv("LC_ALL") + "'. You could use a locale setting that matches encoding='" + desired + "'."); throw new IllegalStateException( "The Java Virtual Machine has not been configured to use the " + "desired default character encoding (" + desired + ")."); } } }
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { List<ApplicationListener<ApplicationEvent>> delegates = getListeners( ((ApplicationEnvironmentPreparedEvent) event).getEnvironment()); if (delegates.isEmpty()) { return; } this.multicaster = new SimpleApplicationEventMulticaster(); for (ApplicationListener<ApplicationEvent> listener : delegates) { this.multicaster.addApplicationListener(listener); } } if (this.multicaster != null) { this.multicaster.multicastEvent(event); } }
@Test public void eventsOrder() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); final List<ApplicationEvent> events = new ArrayList<ApplicationEvent>(); class ApplicationRunningEventListener implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { events.add((event)); } } application.addListeners(new ApplicationRunningEventListener()); this.context = application.run(); assertThat(events).hasSize(5); assertThat(events.get(0)).isInstanceOf(ApplicationStartedEvent.class); assertThat(events.get(1)).isInstanceOf(ApplicationEnvironmentPreparedEvent.class); assertThat(events.get(2)).isInstanceOf(ApplicationPreparedEvent.class); assertThat(events.get(3)).isInstanceOf(ContextRefreshedEvent.class); assertThat(events.get(4)).isInstanceOf(ApplicationReadyEvent.class); }
@Test public void webEnvironmentSwitchedOffInListener() throws Exception { TestSpringApplication application = new TestSpringApplication( ExampleConfig.class); application.addListeners( new ApplicationListener<ApplicationEnvironmentPreparedEvent>() { @Override public void onApplicationEvent( ApplicationEnvironmentPreparedEvent event) { assertThat(event.getEnvironment()) .isInstanceOf(StandardServletEnvironment.class); TestPropertySourceUtils.addInlinedPropertiesToEnvironment( event.getEnvironment(), "foo=bar"); event.getSpringApplication().setWebEnvironment(false); } }); this.context = application.run(); assertThat(this.context.getEnvironment()) .isNotInstanceOf(StandardServletEnvironment.class); assertThat(this.context.getEnvironment().getProperty("foo")); assertThat(this.context.getEnvironment().getPropertySources().iterator().next() .getName()).isEqualTo( TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); String url = cleanRemoteUrl(environment.getProperty(NON_OPTION_ARGS)); Assert.state(StringUtils.hasLength(url), "No remote URL specified"); Assert.state(url.indexOf(",") == -1, "Multiple URLs specified"); try { new URI(url); } catch (URISyntaxException ex) { throw new IllegalStateException("Malformed URL '" + url + "'"); } Map<String, Object> source = Collections.singletonMap("remoteUrl", (Object) url); PropertySource<?> propertySource = new MapPropertySource("remoteUrl", source); environment.getPropertySources().addLast(propertySource); }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { Environment environment = event.getEnvironment(); final String loggingFile = environment.getProperty(PROP_LOGGING_FILE); if (loggingFile != null) { System.setProperty(PROP_LOGGER, "FILE"); try { System.setProperty("logging.dir", new File(loggingFile).getParent()); } catch (Exception ex) { System.err.println("Unable to set up logging.dir from logging.file " + loggingFile + ": " + Throwables.getStackTraceAsString(ex)); } } if (environment.containsProperty("debug") && !"false".equalsIgnoreCase(environment.getProperty("debug", String.class))) { System.setProperty(PROP_SPRING_BOOT_LOG_LEVEL, "DEBUG"); } }
@Test public void issue_notDecryptedDuringBoostrapPhase() { // making spring.cloud.bootstrap.enabled=true in order to bootstrap the application. // making jasypt.encryptor.bootstrap=false otherwise JasyptSpringCloudBootstrapConfiguration becomes active. startWith(new BaseBootstrappingTestListener() { @Override public void onApplicationEvent(final ApplicationEnvironmentPreparedEvent event) { assertFalse("ENC() value is not decrypted during bootstrap phase", event.getEnvironment().getProperty("spring.cloud.config.server.svn.password").equals("mypassword")); } }, "--spring.cloud.bootstrap.enabled=true", "--jasypt.encryptor.bootstrap=false"); // to get codacy to pass. assertNotNull(this.context.getBean(EnableEncryptablePropertiesBeanFactoryPostProcessor.class)); }
@Test public void fix_decryptedDuringBoostrapPhase() { // making spring.cloud.bootstrap.enabled=true in order to bootstrap the application. // making jasypt.encryptor.bootstrap=true in order to bootstrap Jasypt. startWith(new BaseBootstrappingTestListener() { @Override public void onApplicationEvent(final ApplicationEnvironmentPreparedEvent event) { assertTrue("ENC() value is decrypted during bootstrap phase", event.getEnvironment().getProperty("spring.cloud.config.server.svn.password").equals("mypassword")); } }, "--spring.cloud.bootstrap.enabled=true", "--jasypt.encryptor.bootstrap=true"); // to get codacy to pass. assertNotNull(this.context.getBean(EnableEncryptablePropertiesBeanFactoryPostProcessor.class)); }
@Test public void eventsOrder() { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebEnvironment(false); final List<ApplicationEvent> events = new ArrayList<ApplicationEvent>(); class ApplicationRunningEventListener implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { events.add((event)); } } application.addListeners(new ApplicationRunningEventListener()); this.context = application.run(); assertThat(5, is(events.size())); assertThat(events.get(0), is(instanceOf(ApplicationStartedEvent.class))); assertThat(events.get(1), is(instanceOf(ApplicationEnvironmentPreparedEvent.class))); assertThat(events.get(2), is(instanceOf(ApplicationPreparedEvent.class))); assertThat(events.get(3), is(instanceOf(ContextRefreshedEvent.class))); assertThat(events.get(4), is(instanceOf(ApplicationReadyEvent.class))); }
@Test public void webEnvironmentSwitchedOffInListener() throws Exception { TestSpringApplication application = new TestSpringApplication( ExampleConfig.class); application.addListeners( new ApplicationListener<ApplicationEnvironmentPreparedEvent>() { @Override public void onApplicationEvent( ApplicationEnvironmentPreparedEvent event) { assertTrue(event .getEnvironment() instanceof StandardServletEnvironment); EnvironmentTestUtils.addEnvironment(event.getEnvironment(), "foo=bar"); event.getSpringApplication().setWebEnvironment(false); } }); this.context = application.run(); assertFalse(this.context.getEnvironment() instanceof StandardServletEnvironment); assertEquals("bar", this.context.getEnvironment().getProperty("foo")); assertEquals("test", this.context.getEnvironment().getPropertySources().iterator() .next().getName()); }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); String url = environment.getProperty(NON_OPTION_ARGS); Assert.state(StringUtils.hasLength(url), "No remote URL specified"); Assert.state(url.indexOf(",") == -1, "Multiple URLs specified"); try { new URI(url); } catch (URISyntaxException ex) { throw new IllegalStateException("Malformed URL '" + url + "'"); } Map<String, Object> source = Collections.singletonMap("remoteUrl", (Object) url); PropertySource<?> propertySource = new MapPropertySource("remoteUrl", source); environment.getPropertySources().addLast(propertySource); }
@Test public void shouldWrapExceptionOnEncryptionError() { // given StandardEnvironment environment = new StandardEnvironment(); Properties props = new Properties(); props.put("propertyDecryption.password", "NOT-A-PASSWORD"); props.put("someProperty", "{encrypted}NOT-ENCRYPTED"); environment.getPropertySources().addFirst(new PropertiesPropertySource("test-env", props)); exception.expect(RuntimeException.class); exception.expectMessage("Unable to decrypt property value '{encrypted}NOT-ENCRYPTED'"); exception.expectCause(isA(EncryptionOperationNotPossibleException.class)); ApplicationEnvironmentPreparedEvent event = new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], environment); // when listener.onApplicationEvent(event); // then -> exception }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { // 设置动态加载文件要使用的active.profile系统变量 ConfigurableEnvironment env = event.getEnvironment(); if(env != null){ System.out.println("start eds Application , active profiles : " + Arrays.toString(env.getActiveProfiles())); String[] activeProfiles = env.getActiveProfiles(); if(activeProfiles != null && activeProfiles.length > 0){ String active = activeProfiles[0]; System.setProperty("spring.profiles.active",active); System.out.println("eds system property [spring.profiles.active] variable : "+active); } } }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { if (cloud != null) { return; } try { cloud = new CloudFactory().getCloud(); } catch (CloudException e) { // not running on a known cloud environment, so nothing to do log.log(Level.INFO, "Error getting cloud object", e); return; } for (ServiceInfo serviceInfo : cloud.getServiceInfos()) { if (serviceInfo instanceof ConfigServerServiceInfo) { final ConfigServerServiceInfo configServerServiceInfo = (ConfigServerServiceInfo) serviceInfo; Map<String, Object> properties = new ConcurrentHashMap<>(); properties.put(SPRING_CLOUD_CONFIG_URI, configServerServiceInfo.getUri()); MapPropertySource mapPropertySource = new MapPropertySource(PROPERTY_SOURCE_NAME, properties); event.getEnvironment().getPropertySources().addFirst(mapPropertySource); } } }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); String propertySource = environment.getProperty("c2mon.client.conf.url"); if (propertySource != null) { try { environment.getPropertySources().addAfter("systemEnvironment", new ResourcePropertySource(propertySource)); } catch (IOException e) { throw new RuntimeException("Could not read property source", e); } } }
/** * Listens for the {@link ApplicationEnvironmentPreparedEvent} and injects * ${c2mon.server.properties} into the environment with the highest precedence * (if it exists). This is in order to allow users to point to an external * properties file via ${c2mon.server.properties}. */ @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); String propertySource = environment.getProperty("c2mon.server.properties"); if (propertySource != null) { try { environment.getPropertySources().addAfter("systemEnvironment", new ResourcePropertySource(propertySource)); } catch (IOException e) { throw new RuntimeException("Could not read property source", e); } } }
private void onApplicationEnvironmentPreparedEvent( ApplicationEnvironmentPreparedEvent event) { if (this.loggingSystem == null) { this.loggingSystem = LoggingSystem .get(event.getSpringApplication().getClassLoader()); } initialize(event.getEnvironment(), event.getSpringApplication().getClassLoader()); }
@Override public void onApplicationEvent(ApplicationEvent event) { if (this.logger.isDebugEnabled()) { if (event instanceof ApplicationEnvironmentPreparedEvent) { this.logger .debug("Application started with classpath: " + getClasspath()); } else if (event instanceof ApplicationFailedEvent) { this.logger.debug( "Application failed to start with classpath: " + getClasspath()); } } }
@Override public boolean supportsEventType(ResolvableType resolvableType) { Class<?> type = resolvableType.getRawClass(); if (type == null) { return false; } return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(type) || ApplicationFailedEvent.class.isAssignableFrom(type); }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { RelaxedPropertyResolver resolver = new RelaxedPropertyResolver( event.getEnvironment(), "spring.output.ansi."); if (resolver.containsProperty("enabled")) { String enabled = resolver.getProperty("enabled"); AnsiOutput.setEnabled(Enum.valueOf(Enabled.class, enabled.toUpperCase())); } if (resolver.containsProperty("console-available")) { AnsiOutput.setConsoleAvailable( resolver.getProperty("console-available", Boolean.class)); } }
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { onApplicationEnvironmentPreparedEvent( (ApplicationEnvironmentPreparedEvent) event); } if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent(event); } }
private void onApplicationEnvironmentPreparedEvent( ApplicationEnvironmentPreparedEvent event) { List<EnvironmentPostProcessor> postProcessors = loadPostProcessors(); postProcessors.add(this); AnnotationAwareOrderComparator.sort(postProcessors); for (EnvironmentPostProcessor postProcessor : postProcessors) { postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication()); } }
@Test public void orderedInitialize() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "context.listener.classes=" + MockInitB.class.getName() + "," + MockInitA.class.getName()); this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent( new SpringApplication(), new String[0], this.context.getEnvironment())); this.context.getBeanFactory().registerSingleton("testListener", this.listener); this.context.refresh(); assertThat(this.context.getBeanFactory().getSingleton("a")).isEqualTo("a"); assertThat(this.context.getBeanFactory().getSingleton("b")).isEqualTo("b"); }
@Test public void emptyInitializers() throws Exception { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "context.listener.classes:"); this.listener.onApplicationEvent(new ApplicationEnvironmentPreparedEvent( new SpringApplication(), new String[0], this.context.getEnvironment())); }
private Environment getEnvironment(SpringApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { return ((ApplicationEnvironmentPreparedEvent) event).getEnvironment(); } if (event instanceof ApplicationPreparedEvent) { return ((ApplicationPreparedEvent) event).getApplicationContext() .getEnvironment(); } return null; }
@Test public void differentEventTypes() throws Exception { File file = this.temporaryFolder.newFile(); SpringApplicationEvent event = createEnvironmentPreparedEvent("spring.pid.file", file.getAbsolutePath()); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(); listener.onApplicationEvent(event); assertThat(FileCopyUtils.copyToString(new FileReader(file))).isEmpty(); listener.setTriggerEventType(ApplicationEnvironmentPreparedEvent.class); listener.onApplicationEvent(event); assertThat(FileCopyUtils.copyToString(new FileReader(file))).isNotEmpty(); }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); try { loadProfileProperties(environment); loadPlainProperties(environment); } catch (IOException ex) { throw new IllegalStateException("Unable to load configuration files", ex); } }