@Test public void testJsr250SecurityAnnotationOverride() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(Jsr250EnabledConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); this.context.getBean(OAuth2MethodSecurityConfiguration.class); ClientDetails config = this.context.getBean(ClientDetails.class); DelegatingMethodSecurityMetadataSource source = this.context .getBean(DelegatingMethodSecurityMetadataSource.class); List<MethodSecurityMetadataSource> sources = source .getMethodSecurityMetadataSources(); assertThat(sources.size()).isEqualTo(1); assertThat(sources.get(0).getClass().getName()) .isEqualTo(Jsr250MethodSecurityMetadataSource.class.getName()); verifyAuthentication(config, HttpStatus.OK); }
@Test public void agentServletWithCustomPath() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "endpoints.jolokia.path=/foo/bar"); this.context.register(EndpointsConfig.class, WebMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).hasSize(1); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); mockMvc.perform(MockMvcRequestBuilders.get("/foo/bar")) .andExpect(MockMvcResultMatchers.content() .string(Matchers.containsString("\"request\":{\"type\""))); }
@Test public void testEnvironmentalOverrides() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "security.oauth2.client.clientId:myclientid", "security.oauth2.client.clientSecret:mysecret", "security.oauth2.client.autoApproveScopes:read,write", "security.oauth2.client.accessTokenValiditySeconds:40", "security.oauth2.client.refreshTokenValiditySeconds:80"); this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); ClientDetails config = this.context.getBean(ClientDetails.class); assertThat(config.getClientId()).isEqualTo("myclientid"); assertThat(config.getClientSecret()).isEqualTo("mysecret"); assertThat(config.isAutoApprove("read")).isTrue(); assertThat(config.isAutoApprove("write")).isTrue(); assertThat(config.isAutoApprove("foo")).isFalse(); assertThat(config.getAccessTokenValiditySeconds()).isEqualTo(40); assertThat(config.getRefreshTokenValiditySeconds()).isEqualTo(80); verifyAuthentication(config); }
@Test public void testClassicSecurityAnnotationOverride() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(SecuredEnabledConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); this.context.getBean(OAuth2MethodSecurityConfiguration.class); ClientDetails config = this.context.getBean(ClientDetails.class); DelegatingMethodSecurityMetadataSource source = this.context .getBean(DelegatingMethodSecurityMetadataSource.class); List<MethodSecurityMetadataSource> sources = source .getMethodSecurityMetadataSources(); assertThat(sources.size()).isEqualTo(1); assertThat(sources.get(0).getClass().getName()) .isEqualTo(SecuredAnnotationSecurityMetadataSource.class.getName()); verifyAuthentication(config, HttpStatus.OK); }
@Test public void testSecurityFilterDoesNotCauseEarlyInitialization() throws Exception { AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext(); try { EnvironmentTestUtils.addEnvironment(context, "server.port:0", "security.user.password:password"); context.register(Config.class); context.refresh(); int port = context.getEmbeddedServletContainer().getPort(); new TestRestTemplate("user", "password") .getForEntity("http://localhost:" + port, Object.class); // If early initialization occurred a ConverterNotFoundException is thrown } finally { context.close(); } }
@Test(expected = NoSuchBeanDefinitionException.class) public void deviceDelegatingThymeleafViewResolverDisabled() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "spring.mobile.devicedelegatingviewresolver.enabled:false"); this.context.register(Config.class, WebMvcAutoConfiguration.class, ThymeleafAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, DeviceDelegatingViewResolverConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(InternalResourceViewResolver.class)).isNotNull(); assertThat(this.context.getBean(ThymeleafViewResolver.class)).isNotNull(); this.context.getBean("deviceDelegatingViewResolver", AbstractDeviceDelegatingViewResolver.class); }
@Test public void testAuthorizationServerOverride() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "security.oauth2.resourceId:resource-id"); this.context.register(AuthorizationAndResourceServerConfiguration.class, CustomAuthorizationServer.class, MinimalSecureWebApplication.class); this.context.refresh(); BaseClientDetails config = new BaseClientDetails(); config.setClientId("client"); config.setClientSecret("secret"); config.setResourceIds(Arrays.asList("resource-id")); config.setAuthorizedGrantTypes(Arrays.asList("password")); config.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("USER")); config.setScope(Arrays.asList("read")); assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0); assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1); verifyAuthentication(config); }
@Test public void testDefaultPrePostSecurityAnnotations() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); this.context.getBean(OAuth2MethodSecurityConfiguration.class); ClientDetails config = this.context.getBean(ClientDetails.class); DelegatingMethodSecurityMetadataSource source = this.context .getBean(DelegatingMethodSecurityMetadataSource.class); List<MethodSecurityMetadataSource> sources = source .getMethodSecurityMetadataSources(); assertThat(sources.size()).isEqualTo(1); assertThat(sources.get(0).getClass().getName()) .isEqualTo(PrePostAnnotationSecurityMetadataSource.class.getName()); verifyAuthentication(config); }
@Test public void deviceDelegatingThymeleafViewResolverEnabled() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "spring.mobile.devicedelegatingviewresolver.enabled:true"); this.context.register(Config.class, WebMvcAutoConfiguration.class, ThymeleafAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, DeviceDelegatingViewResolverConfiguration.class); this.context.refresh(); ThymeleafViewResolver thymeleafViewResolver = this.context .getBean(ThymeleafViewResolver.class); AbstractDeviceDelegatingViewResolver deviceDelegatingViewResolver = this.context .getBean("deviceDelegatingViewResolver", AbstractDeviceDelegatingViewResolver.class); assertThat(thymeleafViewResolver).isNotNull(); assertThat(deviceDelegatingViewResolver).isNotNull(); assertThat(deviceDelegatingViewResolver.getViewResolver()) .isInstanceOf(ThymeleafViewResolver.class); assertThat(this.context.getBean(InternalResourceViewResolver.class)).isNotNull(); assertThat(this.context.getBean(ThymeleafViewResolver.class)).isNotNull(); assertThat(deviceDelegatingViewResolver.getOrder()) .isEqualTo(thymeleafViewResolver.getOrder() - 1); }
@Override public void onApplicationEvent(ApplicationEvent event) { if(event instanceof ContextRefreshedEvent) { ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext(); if(applicationContext instanceof AnnotationConfigEmbeddedWebApplicationContext) { ((AnnotationConfigEmbeddedWebApplicationContext) applicationContext).getBeanFactory().registerSingleton("simpleBeanInListener", new SimpleBeanInListener()); } } }
protected WebApplicationContext createRootApplicationContext( ServletContext servletContext) { SpringApplicationBuilder builder = createSpringApplicationBuilder(); builder.main(getClass()); ApplicationContext parent = getExistingRootWebApplicationContext(servletContext); if (parent != null) { this.logger.info("Root context already created (using as parent)."); servletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null); builder.initializers(new ParentContextApplicationContextInitializer(parent)); } builder.initializers( new ServletContextApplicationContextInitializer(servletContext)); builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class); builder = configure(builder); SpringApplication application = builder.build(); if (application.getSources().isEmpty() && AnnotationUtils .findAnnotation(getClass(), Configuration.class) != null) { application.getSources().add(getClass()); } Assert.state(!application.getSources().isEmpty(), "No SpringApplication sources have been defined. Either override the " + "configure method or add an @Configuration annotation"); // Ensure error pages are registered if (this.registerErrorPageFilter) { application.getSources().add(ErrorPageFilter.class); } return run(application); }
@Test public void componentsAreRegistered() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(TestConfiguration.class); new ServerPortInfoApplicationContextInitializer().initialize(this.context); this.context.refresh(); String port = this.context.getEnvironment().getProperty("local.server.port"); String response = new RestTemplate() .getForObject("http://localhost:" + port + "/test", String.class); assertThat(response).isEqualTo("alpha bravo"); }
private void doTest(AnnotationConfigEmbeddedWebApplicationContext context, String resourcePath, HttpStatus status) throws Exception { int port = context.getEmbeddedServletContainer().getPort(); RestTemplate template = new RestTemplate(); ResponseEntity<String> entity = template.getForEntity( new URI("http://localhost:" + port + resourcePath), String.class); assertThat(entity.getBody()).isEqualTo("Hello World"); assertThat(entity.getStatusCode()).isEqualTo(status); }
@Override public ApplicationContext loadContext(MergedContextConfiguration config) throws Exception { AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext( config.getClasses()); context.registerShutdownHook(); return context; }
@Test public void defaultApplicationContextForWeb() throws Exception { SpringApplication application = new SpringApplication(ExampleWebConfig.class); application.setWebEnvironment(true); this.context = application.run(); assertThat(this.context) .isInstanceOf(AnnotationConfigEmbeddedWebApplicationContext.class); }
private void registerEmbeddedServletContainerFactory( AnnotationConfigEmbeddedWebApplicationContext childContext) { try { ConfigurableListableBeanFactory beanFactory = childContext.getBeanFactory(); if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; registry.registerBeanDefinition("embeddedServletContainerFactory", new RootBeanDefinition( determineEmbeddedServletContainerFactoryClass())); } } catch (NoSuchBeanDefinitionException ex) { // Ignore and assume auto-configuration } }
@Test public void agentServletRegisteredWithAppContext() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "jolokia.config[key1]:value1", "jolokia.config[key2]:value2"); this.context.register(Config.class, WebMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).hasSize(1); }
private void assertEndpointDisabled(String... pairs) { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, pairs); this.context.register(Config.class, WebMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).isEmpty(); }
private void assertEndpointEnabled(String... pairs) { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, pairs); this.context.register(Config.class, WebMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).hasSize(1); }
private void loadWeb(Class<?>... config) { AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext(); if (config.length > 0) { context.register(config); } context.register(DataSourcePoolMetadataProvidersConfiguration.class, CacheStatisticsAutoConfiguration.class, PublicMetricsAutoConfiguration.class, MockEmbeddedServletContainerFactory.class); context.refresh(); this.context = context; }
@Test public void createFromConfigClass() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(Config.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "server.port:9000"); this.context.refresh(); ServerProperties server = this.context.getBean(ServerProperties.class); assertThat(server).isNotNull(); assertThat(server.getPort().intValue()).isEqualTo(9000); verify(containerFactory).setPort(9000); }
@Test public void tomcatProperties() throws Exception { containerFactory = mock(TomcatEmbeddedServletContainerFactory.class); this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(Config.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "server.tomcat.basedir:target/foo", "server.port:9000"); this.context.refresh(); ServerProperties server = this.context.getBean(ServerProperties.class); assertThat(server).isNotNull(); assertThat(server.getTomcat().getBasedir()).isEqualTo(new File("target/foo")); verify(containerFactory).setPort(9000); }
@Test public void customizeWithJettyContainerFactory() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(CustomJettyContainerConfig.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); containerFactory = this.context .getBean(AbstractEmbeddedServletContainerFactory.class); ServerProperties server = this.context.getBean(ServerProperties.class); assertThat(server).isNotNull(); // The server.port environment property was not explicitly set so the container // factory should take precedence... assertThat(containerFactory.getPort()).isEqualTo(3000); }
@Test public void customizeWithUndertowContainerFactory() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(CustomUndertowContainerConfig.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); containerFactory = this.context .getBean(AbstractEmbeddedServletContainerFactory.class); ServerProperties server = this.context.getBean(ServerProperties.class); assertThat(server).isNotNull(); assertThat(containerFactory.getPort()).isEqualTo(3000); }
@Test public void customizeTomcatWithCustomizer() throws Exception { containerFactory = mock(TomcatEmbeddedServletContainerFactory.class); this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(Config.class, CustomizeConfig.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); ServerProperties server = this.context.getBean(ServerProperties.class); assertThat(server).isNotNull(); // The server.port environment property was not explicitly set so the container // customizer should take precedence... verify(containerFactory).setPort(3000); }
@Test public void testAccidentalMultipleServerPropertiesBeans() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(Config.class, MultiServerPropertiesBeanConfig.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.thrown.expect(ApplicationContextException.class); this.thrown.expectMessage("Multiple ServerProperties"); this.context.refresh(); }
private void load() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "spring.session.store-type=hash-map"); this.context.register(MockEmbeddedServletContainerConfiguration.class, TestRedisConfiguration.class, WebMvcAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, SecurityAutoConfiguration.class, SessionAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, HttpEncodingAutoConfiguration.class); this.context.refresh(); }
@Test public void contextAlreadyHasDispatcherServlet() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext( SpringServletConfiguration.class, BaseConfiguration.class); verifyContext(); assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) .isEqualTo(2); }
@Test public void testMethodSecurityBackingOff() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register(CustomMethodSecurity.class, TestSecurityConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); DelegatingMethodSecurityMetadataSource source = this.context .getBean(DelegatingMethodSecurityMetadataSource.class); List<MethodSecurityMetadataSource> sources = source .getMethodSecurityMetadataSources(); assertThat(sources.size()).isEqualTo(1); assertThat(sources.get(0).getClass().getName()) .isEqualTo(PrePostAnnotationSecurityMetadataSource.class.getName()); }
@Test public void contextAlreadyHasNonServlet() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext( NonServletConfiguration.class, BaseConfiguration.class); assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) .isEqualTo(0); assertThat(this.context.getBeanNamesForType(Servlet.class).length).isEqualTo(0); }
@Test public void contextAlreadyHasDispatcherServletAndRegistration() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext( DispatcherServletWithRegistrationConfiguration.class, BaseConfiguration.class); verifyContext(); assertThat(this.context.getBeanNamesForType(DispatcherServlet.class).length) .isEqualTo(1); }
@Test public void customizeContainerThroughCallback() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext( CallbackEmbeddedContainerCustomizer.class, BaseConfiguration.class); verifyContext(); assertThat(getContainerFactory().getPort()).isEqualTo(9000); }
@Test public void initParametersAreConfiguredOnTheServletContext() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "server.context_parameters.a:alpha", "server.context_parameters.b:bravo"); this.context.register(BaseConfiguration.class); this.context.refresh(); ServletContext servletContext = this.context.getServletContext(); assertThat(servletContext.getInitParameter("a")).isEqualTo("alpha"); assertThat(servletContext.getInitParameter("b")).isEqualTo("bravo"); }
@Test public void overrideIgnoreDefaultModelOnRedirect() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "spring.mvc.ignore-default-model-on-redirect:false"); this.context.register(Config.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); RequestMappingHandlerAdapter adapter = this.context .getBean(RequestMappingHandlerAdapter.class); assertThat(adapter).extracting("ignoreDefaultModelOnRedirect") .containsExactly(false); }
private void load(Class<?> config, String... environment) { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, environment); List<Class<?>> configClasses = new ArrayList<Class<?>>(); if (config != null) { configClasses.add(config); } configClasses.addAll(Arrays.asList(Config.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); this.context.register(configClasses.toArray(new Class<?>[configClasses.size()])); this.context.refresh(); }
@Test public void containerWithNothing() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext( ContainerWithNothing.class, BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); verify404(); assertThat(servlet.getMultipartResolver()).isNotNull(); assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)) .hasSize(1); assertThat(this.context.getBeansOfType(MultipartResolver.class)).hasSize(1); }
@Test public void containerWithNoMultipartJettyConfiguration() { this.context = new AnnotationConfigEmbeddedWebApplicationContext( ContainerWithNoMultipartJetty.class, BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); assertThat(servlet.getMultipartResolver()).isNotNull(); assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)) .hasSize(1); assertThat(this.context.getBeansOfType(MultipartResolver.class)).hasSize(1); verifyServletWorks(); }
@Test public void containerWithNoMultipartUndertowConfiguration() { this.context = new AnnotationConfigEmbeddedWebApplicationContext( ContainerWithNoMultipartUndertow.class, BaseConfiguration.class); DispatcherServlet servlet = this.context.getBean(DispatcherServlet.class); verifyServletWorks(); assertThat(servlet.getMultipartResolver()).isNotNull(); assertThat(this.context.getBeansOfType(StandardServletMultipartResolver.class)) .hasSize(1); assertThat(this.context.getBeansOfType(MultipartResolver.class)).hasSize(1); }