private ConditionOutcome isWebApplication(ConditionContext context, AnnotatedTypeMetadata metadata, boolean required) { ConditionMessage.Builder message = ConditionMessage.forCondition( ConditionalOnWebApplication.class, required ? "(required)" : ""); if (!ClassUtils.isPresent(WEB_CONTEXT_CLASS, context.getClassLoader())) { return ConditionOutcome .noMatch(message.didNotFind("web application classes").atAll()); } if (context.getBeanFactory() != null) { String[] scopes = context.getBeanFactory().getRegisteredScopeNames(); if (ObjectUtils.containsElement(scopes, "session")) { return ConditionOutcome.match(message.foundExactly("'session' scope")); } } if (context.getEnvironment() instanceof StandardServletEnvironment) { return ConditionOutcome .match(message.foundExactly("StandardServletEnvironment")); } if (context.getResourceLoader() instanceof WebApplicationContext) { return ConditionOutcome.match(message.foundExactly("WebApplicationContext")); } return ConditionOutcome.noMatch(message.because("not a web application")); }
@Test public void environmentOperations() { DispatcherServlet servlet = new DispatcherServlet(); ConfigurableEnvironment defaultEnv = servlet.getEnvironment(); assertThat(defaultEnv, notNullValue()); ConfigurableEnvironment env1 = new StandardServletEnvironment(); servlet.setEnvironment(env1); // should succeed assertThat(servlet.getEnvironment(), sameInstance(env1)); try { servlet.setEnvironment(new DummyEnvironment()); fail("expected IllegalArgumentException for non-configurable Environment"); } catch (IllegalArgumentException ex) { } class CustomServletEnvironment extends StandardServletEnvironment { } @SuppressWarnings("serial") DispatcherServlet custom = new DispatcherServlet() { @Override protected ConfigurableWebEnvironment createEnvironment() { return new CustomServletEnvironment(); } }; assertThat(custom.getEnvironment(), instanceOf(CustomServletEnvironment.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); }
private ConditionOutcome isWebApplication(ConditionContext context, AnnotatedTypeMetadata metadata) { if (!ClassUtils.isPresent(WEB_CONTEXT_CLASS, context.getClassLoader())) { return ConditionOutcome.noMatch("web application classes not found"); } if (context.getBeanFactory() != null) { String[] scopes = context.getBeanFactory().getRegisteredScopeNames(); if (ObjectUtils.containsElement(scopes, "session")) { return ConditionOutcome.match("found web application 'session' scope"); } } if (context.getEnvironment() instanceof StandardServletEnvironment) { return ConditionOutcome .match("found web application StandardServletEnvironment"); } if (context.getResourceLoader() instanceof WebApplicationContext) { return ConditionOutcome.match("found web application WebApplicationContext"); } return ConditionOutcome.noMatch("not a web application"); }
@Override public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException { super.postProcessBeanFactory(beanFactory); final StandardServletEnvironment propertySources = (StandardServletEnvironment) super.getAppliedPropertySources().get(ENVIRONMENT_PROPERTIES).getSource(); propertySources.getPropertySources().forEach(propertySource -> { if (propertySource.getSource() instanceof Map) { // it will print systemProperties, systemEnvironment, application.properties and other overrides of // application.properties log.trace("#######" + propertySource.getName() + "#######"); //noinspection unchecked ((Map) propertySource.getSource()).forEach((key, value) -> log.trace(key+"="+value)); } }); }
@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()); }
/** * this test is an integration test (use of a spring context) * * It begins with a Jndi instanciation and then try to load a spring context depending on jndi properties. * * The goal of this test is to validate that we can read jndi encoded properties from spring */ @Test public void process_properties_should_decode_all_encrypted_props() throws Exception { //Jndi setup //Set fictive jndi properties (some of them are encoded) SimpleNamingContextBuilder.emptyActivatedContextBuilder(); InitialContext initialContext = new InitialContext(); initialContext.bind("jndi.prop1", "ENC(VLCeFXg9nPrx7Bmsbcb0h3v5ivRinKQ4)"); initialContext.bind("jndi.prop2", "testjndiValue2"); //when ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:/com/francetelecom/clara/cloud/commons/jasypt/jndiPropsDecoding.xml"){ @Override protected ConfigurableEnvironment createEnvironment() { return new StandardServletEnvironment(); } }; //Then TestBean bean = context.getBean(TestBean.class); assertEquals("testjndivalue",bean.getSampleProp1()); assertEquals("testjndiValue2",bean.getSampleProp2()); assertEquals("testlocalvalue",bean.getSampleProp3()); assertEquals("testlocalvalue2",bean.getSampleProp4()); }
public void testEnvironmentOperations() { DispatcherServlet servlet = new DispatcherServlet(); ConfigurableEnvironment defaultEnv = servlet.getEnvironment(); assertThat(defaultEnv, notNullValue()); ConfigurableEnvironment env1 = new StandardServletEnvironment(); servlet.setEnvironment(env1); // should succeed assertThat(servlet.getEnvironment(), sameInstance(env1)); try { servlet.setEnvironment(new DummyEnvironment()); fail("expected IllegalArgumentException for non-configurable Environment"); } catch (IllegalArgumentException ex) { } class CustomServletEnvironment extends StandardServletEnvironment { } @SuppressWarnings("serial") DispatcherServlet custom = new DispatcherServlet() { @Override protected ConfigurableWebEnvironment createEnvironment() { return new CustomServletEnvironment(); } }; assertThat(custom.getEnvironment(), instanceOf(CustomServletEnvironment.class)); }
@Override // TODO throw corresponding exceptions, not just Exception instances. protected BrokerService createBroker(ServletContext sc) throws Exception { // Initialize Web environment to make Spring resolve external // properties. StandardServletEnvironment standardServletEnvironment = new ReversePropertySourcesStandardServletEnvironment(); WebApplicationContextUtils.initServletPropertySources(standardServletEnvironment.getPropertySources(), sc); URI configURI = new URI(standardServletEnvironment.getProperty(BROKER_URI_PROP)); LOG.info("Loading message broker from: " + configURI); return BrokerFactory.createBroker(configURI); }
@Test public void customizePropertySources() { MutablePropertySources propertySources = new MutablePropertySources(); ReversePropertySourcesStandardServletEnvironment env = new ReversePropertySourcesStandardServletEnvironment(); env.customizePropertySources(propertySources); String[] sourceNames = { StandardServletEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, StandardServletEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME, StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME }; List<String> result = new ArrayList<>(); propertySources.forEach(a -> result.add(a.getName())); Assert.assertArrayEquals(sourceNames, result.toArray()); }
@Test public void registerServletParamPropertySources_GenericWebApplicationContext() { MockServletContext servletContext = new MockServletContext(); servletContext.addInitParameter("pCommon", "pCommonContextValue"); servletContext.addInitParameter("pContext1", "pContext1Value"); GenericWebApplicationContext ctx = new GenericWebApplicationContext(); ctx.setServletContext(servletContext); ctx.refresh(); ConfigurableEnvironment environment = ctx.getEnvironment(); assertThat(environment, instanceOf(StandardServletEnvironment.class)); MutablePropertySources propertySources = environment.getPropertySources(); assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME), is(true)); // ServletContext params are available assertThat(environment.getProperty("pCommon"), is("pCommonContextValue")); assertThat(environment.getProperty("pContext1"), is("pContext1Value")); // Servlet* PropertySources have precedence over System* PropertySources assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)), lessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)))); // Replace system properties with a mock property source for convenience MockPropertySource mockSystemProperties = new MockPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); mockSystemProperties.setProperty("pCommon", "pCommonSysPropsValue"); mockSystemProperties.setProperty("pSysProps1", "pSysProps1Value"); propertySources.replace(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, mockSystemProperties); // assert that servletcontext init params resolve with higher precedence than sysprops assertThat(environment.getProperty("pCommon"), is("pCommonContextValue")); assertThat(environment.getProperty("pSysProps1"), is("pSysProps1Value")); }
private String findPropertySource(MutablePropertySources sources) { if (ClassUtils.isPresent(SERVLET_ENVIRONMENT_CLASS, null) && sources .contains(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)) { return StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME; } return StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME; }
private ConfigurableEnvironment getOrCreateEnvironment() { if (this.environment != null) { return this.environment; } if (this.webEnvironment) { return new StandardServletEnvironment(); } return new StandardEnvironment(); }
@Before public void setUp() { prodEnv = new StandardEnvironment(); prodEnv.setActiveProfiles(PROD_ENV_NAME); devEnv = new StandardEnvironment(); devEnv.setActiveProfiles(DEV_ENV_NAME); prodWebEnv = new StandardServletEnvironment(); prodWebEnv.setActiveProfiles(PROD_ENV_NAME); }
@Override public void setEnvironment ( Environment environment ) { this.environment = ( StandardServletEnvironment ) environment; }
@Test public void registerServletParamPropertySources_AbstractRefreshableWebApplicationContext() { MockServletContext servletContext = new MockServletContext(); servletContext.addInitParameter("pCommon", "pCommonContextValue"); servletContext.addInitParameter("pContext1", "pContext1Value"); MockServletConfig servletConfig = new MockServletConfig(servletContext); servletConfig.addInitParameter("pCommon", "pCommonConfigValue"); servletConfig.addInitParameter("pConfig1", "pConfig1Value"); AbstractRefreshableWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.setConfigLocation(EnvironmentAwareBean.class.getName()); ctx.setServletConfig(servletConfig); ctx.refresh(); ConfigurableEnvironment environment = ctx.getEnvironment(); assertThat(environment, instanceOf(StandardServletEnvironment.class)); MutablePropertySources propertySources = environment.getPropertySources(); assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME), is(true)); assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME), is(true)); // ServletConfig gets precedence assertThat(environment.getProperty("pCommon"), is("pCommonConfigValue")); assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), lessThan(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)))); // but all params are available assertThat(environment.getProperty("pContext1"), is("pContext1Value")); assertThat(environment.getProperty("pConfig1"), is("pConfig1Value")); // Servlet* PropertySources have precedence over System* PropertySources assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), lessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)))); // Replace system properties with a mock property source for convenience MockPropertySource mockSystemProperties = new MockPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); mockSystemProperties.setProperty("pCommon", "pCommonSysPropsValue"); mockSystemProperties.setProperty("pSysProps1", "pSysProps1Value"); propertySources.replace(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, mockSystemProperties); // assert that servletconfig params resolve with higher precedence than sysprops assertThat(environment.getProperty("pCommon"), is("pCommonConfigValue")); assertThat(environment.getProperty("pSysProps1"), is("pSysProps1Value")); }
@Test public void registerServletParamPropertySources_StaticWebApplicationContext() { MockServletContext servletContext = new MockServletContext(); servletContext.addInitParameter("pCommon", "pCommonContextValue"); servletContext.addInitParameter("pContext1", "pContext1Value"); MockServletConfig servletConfig = new MockServletConfig(servletContext); servletConfig.addInitParameter("pCommon", "pCommonConfigValue"); servletConfig.addInitParameter("pConfig1", "pConfig1Value"); StaticWebApplicationContext ctx = new StaticWebApplicationContext(); ctx.setServletConfig(servletConfig); ctx.refresh(); ConfigurableEnvironment environment = ctx.getEnvironment(); MutablePropertySources propertySources = environment.getPropertySources(); assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME), is(true)); assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME), is(true)); // ServletConfig gets precedence assertThat(environment.getProperty("pCommon"), is("pCommonConfigValue")); assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), lessThan(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)))); // but all params are available assertThat(environment.getProperty("pContext1"), is("pContext1Value")); assertThat(environment.getProperty("pConfig1"), is("pConfig1Value")); // Servlet* PropertySources have precedence over System* PropertySources assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), lessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)))); // Replace system properties with a mock property source for convenience MockPropertySource mockSystemProperties = new MockPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); mockSystemProperties.setProperty("pCommon", "pCommonSysPropsValue"); mockSystemProperties.setProperty("pSysProps1", "pSysProps1Value"); propertySources.replace(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, mockSystemProperties); // assert that servletconfig params resolve with higher precedence than sysprops assertThat(environment.getProperty("pCommon"), is("pCommonConfigValue")); assertThat(environment.getProperty("pSysProps1"), is("pSysProps1Value")); }
private void assertHasStandardServletEnvironment(WebApplicationContext ctx) { // ensure a default servlet environment exists Environment defaultEnv = ctx.getEnvironment(); assertThat(defaultEnv, notNullValue()); assertThat(defaultEnv, instanceOf(StandardServletEnvironment.class)); }
@Test public void should_not_found_any_dependant_model_item_without_active_plugin_in_production() throws Exception { String datacenter = System.getProperty("datacenter", "hudson"); initJndiValues("com/francetelecom/clara/cloud/commons/testconfigurations/credentials-" + datacenter + ".properties"); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{ "classpath:/spring-config/application-context-plugins.xml", "classpath:/spring-config/datasources-hsqldb-context.xml", "classpath:/com/francetelecom/clara/cloud/commons/testconfigurations/mock-liquibase-context.xml", "classpath:/META-INF/spring/paas-activation-stubbed-context.xml", "classpath:/spring-config/mock-spring-authentication-manager-context.xml"}) { @Override protected ConfigurableEnvironment createEnvironment() { return new StandardServletEnvironment(); } }; ActivationPluginStrategy strategy = (ActivationPluginStrategy) context.getBean("pluginStrategy"); ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AssignableTypeFilter(DependantModelItem.class)); Set<BeanDefinition> findCandidateComponents = provider.findCandidateComponents("com/francetelecom/clara/cloud/model"); ActivationStepEnum[] steps = ActivationStepEnum.values(); Set<Class<?>> errorItems = new HashSet<Class<?>>(); for (BeanDefinition beanDefinition : findCandidateComponents) { ActivationPlugin foundPlugin = null; Class<?> testedClass = Class.forName(beanDefinition.getBeanClassName()); LOGGER.info("Lookin for a plugin handling {}", testedClass.getSimpleName()); for (ActivationStepEnum activationStepEnum : steps) { if (foundPlugin == null) { try { foundPlugin = strategy.getPlugin(testedClass, activationStepEnum); } catch (TechnicalException e) { //Ignore not found error } } } if (foundPlugin == null) { if (ignoredClasses.contains(testedClass)) { LOGGER.info("No plugin found for {} but ignored !", testedClass.getSimpleName()); } else { LOGGER.info("No plugin found for {}", testedClass.getSimpleName()); } errorItems.add(testedClass); } else { assertFalse(testedClass.getSimpleName() + " is ignored but a plugin has been found : " + foundPlugin.getClass().getSimpleName() + ".\nDid you activate new feature without refactoring this test specs ?", ignoredClasses.contains(testedClass)); LOGGER.info("Plugin found for {} : {}", testedClass.getSimpleName(), foundPlugin.getClass().getSimpleName()); } } errorItems.removeAll(ignoredClasses); assertTrue("No plugin found for some items " + errorItems.toString() + ".\nDid you miss some configuration in cloud-paas-webapp spring config?", errorItems.isEmpty()); }
/** * Environment need to be overriden to map with normal webapp spring * context behavior (jndi resolution of properties) */ @Override protected ConfigurableEnvironment createEnvironment() { return new StandardServletEnvironment(); }
@Autowired public MainConfig(StandardServletEnvironment env) { this.env = env; }
/** * Customize the set of property sources with those contributed by superclasses as * well as those appropriate for standard portlet-based environments: * <ul> * <li>{@value #PORTLET_CONFIG_PROPERTY_SOURCE_NAME} * <li>{@value #PORTLET_CONTEXT_PROPERTY_SOURCE_NAME} * <li>{@linkplain StandardServletEnvironment#SERVLET_CONTEXT_PROPERTY_SOURCE_NAME "servletContextInitParams"} * <li>{@linkplain StandardServletEnvironment#JNDI_PROPERTY_SOURCE_NAME "jndiProperties"} * </ul> * <p>Properties present in {@value #PORTLET_CONFIG_PROPERTY_SOURCE_NAME} will * take precedence over those in {@value #PORTLET_CONTEXT_PROPERTY_SOURCE_NAME}, * which takes precedence over those in {@linkplain * StandardServletEnvironment#SERVLET_CONTEXT_PROPERTY_SOURCE_NAME "servletContextInitParams"} * and so on. * <p>Properties in any of the above will take precedence over system properties and * environment variables contributed by the {@link StandardEnvironment} superclass. * <p>The property sources are added as stubs for now, and will be * {@linkplain PortletApplicationContextUtils#initPortletPropertySources fully * initialized} once the actual {@link PortletConfig}, {@link PortletContext}, and * {@link ServletContext} objects are available. * @see StandardEnvironment#customizePropertySources * @see org.springframework.core.env.AbstractEnvironment#customizePropertySources * @see PortletConfigPropertySource * @see PortletContextPropertySource * @see PortletApplicationContextUtils#initPortletPropertySources */ @Override protected void customizePropertySources(MutablePropertySources propertySources) { propertySources.addLast(new StubPropertySource(PORTLET_CONFIG_PROPERTY_SOURCE_NAME)); propertySources.addLast(new StubPropertySource(PORTLET_CONTEXT_PROPERTY_SOURCE_NAME)); propertySources.addLast(new StubPropertySource(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)); if (JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) { propertySources.addLast(new JndiPropertySource(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)); } super.customizePropertySources(propertySources); }
/** * Create and return a new {@link StandardServletEnvironment}. Subclasses may override * in order to configure the environment or specialize the environment type returned. */ protected ConfigurableEnvironment createEnvironment() { return new StandardServletEnvironment(); }