Java Code Examples for org.springframework.web.context.support.AnnotationConfigWebApplicationContext

The following are top voted examples for showing how to use org.springframework.web.context.support.AnnotationConfigWebApplicationContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Smart-Shopping   File: WebMvcInitialiser.java   View source code 8 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
	//register config classes
	AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
	rootContext.register(WebMvcConfig.class);
	rootContext.register(JPAConfig.class);
	rootContext.register(WebSecurityConfig.class);
	rootContext.register(ServiceConfig.class);
	//set session timeout
	servletContext.addListener(new SessionListener(maxInactiveInterval));
	//set dispatcher servlet and mapping
	ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
			new DispatcherServlet(rootContext));
	dispatcher.addMapping("/");
	dispatcher.setLoadOnStartup(1);
	
	//register filters
	FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("endcodingFilter", new CharacterEncodingFilter());
	filterRegistration.setInitParameter("encoding", "UTF-8");
	filterRegistration.setInitParameter("forceEncoding", "true");
	//make sure encodingFilter is matched first
	filterRegistration.addMappingForUrlPatterns(null, false, "/*");
	//disable appending jsessionid to the URL
	filterRegistration = servletContext.addFilter("disableUrlSessionFilter", new DisableUrlSessionFilter());
	filterRegistration.addMappingForUrlPatterns(null, true, "/*");
}
 
Example 2
Project: Spring-5.0-Cookbook   File: SpringWebinitializer.java   View source code 6 votes vote down vote up
private void addDispatcherContext(ServletContext container) {
  // Create the dispatcher servlet's Spring application context
  AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
  dispatcherContext.register(SpringDispatcherConfig.class); 
  
	 
  // Declare  <servlet> and <servlet-mapping> for the DispatcherServlet
  ServletRegistration.Dynamic dispatcher = container.addServlet("ch08-servlet", 
  		new DispatcherServlet(dispatcherContext));
  dispatcher.addMapping("/");
  dispatcher.setLoadOnStartup(1);
  dispatcher.setAsyncSupported(true); 
  
  //FilterRegistration.Dynamic springSecurityFilterChain = container.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
   // springSecurityFilterChain.addMappingForUrlPatterns(null, false, "/*");
   // springSecurityFilterChain.setAsyncSupported(true);

}
 
Example 3
Project: Spring-5.0-Cookbook   File: SpringWebInitializer.java   View source code 6 votes vote down vote up
private void addDispatcherContext(ServletContext container) {
	// Create the dispatcher servlet's Spring application context
	AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
	dispatcherContext.register(SpringDispatcherConfig.class);

	// Declare <servlet> and <servlet-mapping> for the DispatcherServlet
	ServletRegistration.Dynamic dispatcher = container.addServlet("ch03-servlet",
			new DispatcherServlet(dispatcherContext));
	dispatcher.addMapping("*.html");
	dispatcher.setLoadOnStartup(1);

	FilterRegistration.Dynamic corsFilter = container.addFilter("corsFilter", new CorsFilter());
	corsFilter.setInitParameter("cors.allowed.methods", "GET, POST, HEAD, OPTIONS, PUT, DELETE");
	corsFilter.addMappingForUrlPatterns(null, true, "/*");

	FilterRegistration.Dynamic filter = container.addFilter("hiddenmethodfilter", new HiddenHttpMethodFilter());
	filter.addMappingForServletNames(null, true, "/*");

	FilterRegistration.Dynamic multipartFilter = container.addFilter("multipartFilter", new MultipartFilter());
	multipartFilter.addMappingForUrlPatterns(null, true, "/*");

}
 
Example 4
Project: Spring-5.0-Cookbook   File: SpringWebinitializer.java   View source code 6 votes vote down vote up
private void addDispatcherContext(ServletContext container) {
	// Create the dispatcher servlet's Spring application context
	AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
	dispatcherContext.register(SpringDispatcherConfig.class);

	// Declare <servlet> and <servlet-mapping> for the DispatcherServlet
	ServletRegistration.Dynamic dispatcher = container.addServlet("ch03-servlet",
			new DispatcherServlet(dispatcherContext));
	dispatcher.addMapping("*.html");
	dispatcher.setLoadOnStartup(1);

	FilterRegistration.Dynamic corsFilter = container.addFilter("corsFilter", new CorsFilter());
	corsFilter.setInitParameter("cors.allowed.methods", "GET, POST, HEAD, OPTIONS, PUT, DELETE");
	corsFilter.addMappingForUrlPatterns(null, true, "/*");

	FilterRegistration.Dynamic filter = container.addFilter("hiddenmethodfilter", new HiddenHttpMethodFilter());
	filter.addMappingForServletNames(null, true, "/*");

	FilterRegistration.Dynamic multipartFilter = container.addFilter("multipartFilter", new MultipartFilter());
	multipartFilter.addMappingForUrlPatterns(null, true, "/*");

}
 
Example 5
Project: scrumtracker2017   File: ApplicationInitializer.java   View source code 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {

    //On charge le contexte de l'app
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.setDisplayName("scrumtracker");
    rootContext.register(ApplicationContext.class);

    //Context loader listener
    servletContext.addListener(new ContextLoaderListener(rootContext));

    //Dispatcher servlet
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}
 
Example 6
Project: azure-spring-boot   File: AADAuthenticationFilterAutoConfigurationTest.java   View source code 6 votes vote down vote up
@Test
public void createAADAuthenticationFilter() throws Exception {
    System.setProperty(Constants.CLIENT_ID_PROPERTY, Constants.CLIENT_ID);
    System.setProperty(Constants.CLIENT_SECRET_PROPERTY, Constants.CLIENT_SECRET);
    System.setProperty(Constants.TARGETED_GROUPS_PROPERTY,
            Constants.TARGETED_GROUPS.toString().replace("[", "").replace("]", ""));

    try (AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext()) {
        context.register(AADAuthenticationFilterAutoConfiguration.class);
        context.refresh();

        final AADAuthenticationFilter azureADJwtTokenFilter = context.getBean(AADAuthenticationFilter.class);
        assertThat(azureADJwtTokenFilter).isNotNull();
        assertThat(azureADJwtTokenFilter).isExactlyInstanceOf(AADAuthenticationFilter.class);
    }

    System.clearProperty(Constants.CLIENT_ID_PROPERTY);
    System.clearProperty(Constants.CLIENT_SECRET_PROPERTY);
    System.clearProperty(Constants.TARGETED_GROUPS_PROPERTY);
}
 
Example 7
Project: spring-configuration-support   File: SampleApplication.java   View source code 6 votes vote down vote up
@Bean(name = "configServlet")
public ServletRegistrationBean configServlet() {
	DispatcherServlet dispatcherServlet = new DispatcherServlet();
	AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
	applicationContext.register(ConfigServletConfig.class);
	dispatcherServlet.setApplicationContext(applicationContext);
	ServletRegistrationBean registrationBean = new ServletRegistrationBean(dispatcherServlet, "/config/*");
	registrationBean.setLoadOnStartup(1);
	return registrationBean;
}
 
Example 8
Project: autopivot   File: AutoPivotWebAppInitializer.java   View source code 6 votes vote down vote up
/**
 * Configure the given {@link ServletContext} with any servlets, filters, listeners
 * context-params and attributes necessary for initializing this web application. See examples
 * {@linkplain WebApplicationInitializer above}.
 *
 * @param servletContext the {@code ServletContext} to initialize
 * @throws ServletException if any call against the given {@code ServletContext} throws a {@code ServletException}
 */
public void onStartup(ServletContext servletContext) throws ServletException {
	// Spring Context Bootstrapping
	AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
	rootAppContext.register(AutoPivotConfig.class);
	servletContext.addListener(new ContextLoaderListener(rootAppContext));

	// Set the session cookie name. Must be done when there are several servers (AP,
	// Content server, ActiveMonitor) with the same URL but running on different ports.
	// Cookies ignore the port (See RFC 6265).
	CookieUtil.configure(servletContext.getSessionCookieConfig(), CookieUtil.COOKIE_NAME);

	// The main servlet/the central dispatcher
	final DispatcherServlet servlet = new DispatcherServlet(rootAppContext);
	servlet.setDispatchOptionsRequest(true);
	Dynamic dispatcher = servletContext.addServlet("springDispatcherServlet", servlet);
	dispatcher.addMapping("/*");
	dispatcher.setLoadOnStartup(1);

	// Spring Security Filter
	final FilterRegistration.Dynamic springSecurity = servletContext.addFilter(SPRING_SECURITY_FILTER_CHAIN, new DelegatingFilterProxy());
	springSecurity.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

}
 
Example 9
Project: embedded-spring-5   File: AppConfig.java   View source code 6 votes vote down vote up
@Override
public void onStartup(ServletContext container) {
	// Create the 'root' Spring application context
	AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
	rootContext.register(AppConfig.class);

	// Manage the lifecycle of the root application context
	container.addListener(new ContextLoaderListener(rootContext));

	// Create the dispatcher servlet's Spring application context
	AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();

	// Register and map the dispatcher servlet
	ServletRegistration.Dynamic dispatcher = container
			.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
	dispatcher.setLoadOnStartup(1);
	dispatcher.addMapping("/");
}
 
Example 10
Project: springMvc4.x-project   File: WebInitializer.java   View source code 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext)
		throws ServletException {
	AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
	ctx.register(MyMvcConfig.class);
	ctx.setServletContext(servletContext); // ②

	Dynamic servlet = servletContext.addServlet("dispatcher",new DispatcherServlet(ctx)); // 3
	servlet.addMapping("/");
	servlet.setLoadOnStartup(1);
}
 
Example 11
Project: spring-seed   File: CommonWebInitializer.java   View source code 6 votes vote down vote up
private ServletRegistration.Dynamic addDispatcherServlet(ServletContext servletContext, String servletName,
														   Class<?>[] servletContextConfigClasses, boolean allowBeanDefinitionOverriding, String... mappings) {
	Assert.notNull(servletName);
	Assert.notEmpty(servletContextConfigClasses);
	Assert.notEmpty(mappings);

	AnnotationConfigWebApplicationContext servletApplicationContext = new AnnotationConfigWebApplicationContext();
	servletApplicationContext.setAllowBeanDefinitionOverriding(allowBeanDefinitionOverriding);
	servletApplicationContext.register(servletContextConfigClasses);

	ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet(servletName, new DispatcherServlet(servletApplicationContext));

	dispatcherServlet.setLoadOnStartup(1);
	dispatcherServlet.addMapping(mappings);

	return dispatcherServlet;
}
 
Example 12
Project: hojeehdiaderua   File: DiaDeRuaWebInitializer.java   View source code 6 votes vote down vote up
@Override
public void onStartup(ServletContext sc) throws ServletException {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(AppConfig.class);

    sc.addListener(new ContextLoaderListener(context));
    sc.setInitParameter("defaultHtmlEscape", "true");

    ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcherServlet", new DispatcherServlet(context));

    dispatcher.setLoadOnStartup(1);
    dispatcher.setAsyncSupported(true);
    dispatcher.addMapping("/");

    FilterRegistration.Dynamic securityFilter = sc.addFilter("springSecurityFilterChain", DelegatingFilterProxy.class);
    securityFilter.addMappingForUrlPatterns(null, false, "/*");
    securityFilter.setAsyncSupported(true);
}
 
Example 13
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: SecurityAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testCustomAuthenticationDoesNotAuthenticateWithBootSecurityUser()
		throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());

	this.context.register(AuthenticationManagerCustomizer.class,
			SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class);
	this.context.refresh();

	SecurityProperties security = this.context.getBean(SecurityProperties.class);
	AuthenticationManager manager = this.context.getBean(AuthenticationManager.class);

	UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
			security.getUser().getName(), security.getUser().getPassword());
	try {
		manager.authenticate(token);
		fail("Expected Exception");
	}
	catch (AuthenticationException success) {
		// Expected
	}

	token = new UsernamePasswordAuthenticationToken("foo", "bar");
	assertThat(manager.authenticate(token)).isNotNull();
}
 
Example 14
Project: maven-mybatis-spring-example   File: AppInitializer.java   View source code 6 votes vote down vote up
@Override
public void onStartup(ServletContext container) throws ServletException {
	AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
	ctx.register(SpringConfig.class);
	ctx.setServletContext(container);
	
	ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
	
	servlet.setLoadOnStartup(1);
	servlet.addMapping("/");
	
	//编码设置
	FilterRegistration.Dynamic fr = container.addFilter("encodingFilter", new CharacterEncodingFilter());
	fr.setInitParameter("encoding", "UTF-8");
	fr.setInitParameter("forceEncoding", "true");
}
 
Example 15
Project: spring-boot-concourse   File: JpaWebAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testDefaultRepositoryConfiguration() throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());
	this.context.register(TestConfiguration.class,
			EmbeddedDataSourceConfiguration.class,
			HibernateJpaAutoConfiguration.class,
			JpaRepositoriesAutoConfiguration.class,
			SpringDataWebAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	this.context.refresh();
	assertThat(this.context.getBean(CityRepository.class)).isNotNull();
	assertThat(this.context.getBean(PageableHandlerMethodArgumentResolver.class))
			.isNotNull();
	assertThat(this.context.getBean(FormattingConversionService.class)
			.canConvert(Long.class, City.class)).isTrue();
}
 
Example 16
Project: singular-server   File: SingleAppInitializer.java   View source code 6 votes vote down vote up
@Override
default SpringHibernateInitializer springHibernateConfiguration() {
    return new SpringHibernateInitializer() {
        @Override
        protected AnnotationConfigWebApplicationContext newApplicationContext() {
            AnnotationConfigWebApplicationContext context = super.newApplicationContext();
            context.scan(SingleAppInitializer.this.springPackagesToScan());
            return context;
        }

        @Override
        protected Class<? extends SingularDefaultPersistenceConfiguration> persistenceConfiguration() {
            return SingleAppInitializer.this.persistenceConfiguration();
        }

        @Override
        protected Class<? extends SingularDefaultBeanFactory> beanFactory() {
            return SingleAppInitializer.this.beanFactory();
        }
    };
}
 
Example 17
Project: rrs   File: Initializer.java   View source code 6 votes vote down vote up
public void onStartup(ServletContext servletContext)
			throws ServletException {
		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.register(WebAppConfig.class);
		servletContext.addListener(new ContextLoaderListener(ctx));
		
//		CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
//		characterEncodingFilter.setEncoding("UTF-8");
//		characterEncodingFilter.setForceEncoding(true);
//		javax.servlet.FilterRegistration.Dynamic filter = 
//				servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);
//		filter.addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST), 
//				true, "/*");

		ctx.setServletContext(servletContext);

		javax.servlet.ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
		servlet.addMapping("/");
		servlet.setLoadOnStartup(1);
	}
 
Example 18
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: FacebookAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void noFacebookBeanCreatedWhenPropertiesArentSet() throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.register(FacebookAutoConfiguration.class);
	this.context.register(SocialWebAutoConfiguration.class);
	this.context.refresh();
	assertNoConnectionFrameworkBeans();
	assertMissingBean(Facebook.class);
}
 
Example 19
Project: bookManager   File: SpringBootStrap.java   View source code 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
	servletContext.getServletRegistration("default").addMapping("/resources/*");

	AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
	rootContext.register(RootApplicationContextConfig.class);
	servletContext.addListener(new ContextLoaderListener(rootContext));

	AnnotationConfigWebApplicationContext servletContextConfig = new AnnotationConfigWebApplicationContext();
	servletContextConfig.register(ServletApplicationContextConfig.class);
	ServletRegistration.Dynamic dispatcher = servletContext.addServlet("springDispatcher",
			new DispatcherServlet(servletContextConfig));

	dispatcher.setLoadOnStartup(1);
	dispatcher.addMapping("/");

	FilterRegistration.Dynamic registration = servletContext.addFilter("preSecFilter", new PreSescLoggingFilter());
	registration.addMappingForUrlPatterns(null, false, "/*");

	FilterRegistration.Dynamic reg = servletContext.addFilter("encoding",
			new CharacterEncodingFilter("UTF-8", true));
	reg.addMappingForUrlPatterns(null, false, "/*");
}
 
Example 20
Project: spring-boot-concourse   File: SecurityAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testOverrideAuthenticationManagerWithBuilderAndInjectIntoSecurityFilter()
		throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());
	this.context.register(AuthenticationManagerCustomizer.class,
			SecurityCustomizer.class, SecurityAutoConfiguration.class,
			ServerPropertiesAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	this.context.refresh();
	UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(
			"foo", "bar",
			AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
	assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user))
			.isNotNull();
	pingAuthenticationListener();
}
 
Example 21
Project: flowable-engine   File: WebConfigurer.java   View source code 6 votes vote down vote up
protected ServletRegistration.Dynamic initSpringRestComponent(ServletContext servletContext, AnnotationConfigWebApplicationContext rootContext,
        String restContextRoot, Class<? extends WebMvcConfigurationSupport> webConfigClass) {

    LOGGER.debug("Configuring Spring Web application context - {} REST", restContextRoot);
    AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext();
    dispatcherServletConfiguration.setParent(rootContext);
    dispatcherServletConfiguration.register(webConfigClass);

    LOGGER.debug("Registering Spring MVC Servlet - {} REST", restContextRoot);
    ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet(restContextRoot + "-dispatcher", new DispatcherServlet(dispatcherServletConfiguration));
    dispatcherServlet.addMapping("/" + restContextRoot + "/*");
    dispatcherServlet.setLoadOnStartup(1);
    dispatcherServlet.setAsyncSupported(true);

    return dispatcherServlet;
}
 
Example 22
Project: spring-boot-concourse   File: SecurityAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testJpaCoexistsHappily() throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());
	EnvironmentTestUtils.addEnvironment(this.context,
			"spring.datasource.url:jdbc:hsqldb:mem:testsecdb");
	EnvironmentTestUtils.addEnvironment(this.context,
			"spring.datasource.initialize:false");
	this.context.register(EntityConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class,
			DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
			SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class);
	// This can fail if security @Conditionals force early instantiation of the
	// HibernateJpaAutoConfiguration (e.g. the EntityManagerFactory is not found)
	this.context.refresh();
	assertThat(this.context.getBean(JpaTransactionManager.class)).isNotNull();
}
 
Example 23
Project: spring-boot-concourse   File: CrshAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testSpringAuthenticationProviderAsDefaultConfiguration()
		throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());
	this.context.register(ManagementServerPropertiesAutoConfiguration.class);
	this.context.register(SecurityAutoConfiguration.class);
	this.context.register(SecurityConfiguration.class);
	this.context.register(CrshAutoConfiguration.class);
	this.context.refresh();
	PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class);
	AuthenticationPlugin<String> authenticationPlugin = null;
	String authentication = lifeCycle.getConfig().getProperty("crash.auth");
	assertThat(authentication).isNotNull();
	for (AuthenticationPlugin plugin : lifeCycle.getContext()
			.getPlugins(AuthenticationPlugin.class)) {
		if (authentication.equals(plugin.getName())) {
			authenticationPlugin = plugin;
			break;
		}
	}
	assertThat(authenticationPlugin.authenticate(SecurityConfiguration.USERNAME,
			SecurityConfiguration.PASSWORD)).isTrue();
	assertThat(authenticationPlugin.authenticate(UUID.randomUUID().toString(),
			SecurityConfiguration.PASSWORD)).isFalse();
}
 
Example 24
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: SecurityAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void defaultFilterDispatcherTypes() {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());
	this.context.register(SecurityAutoConfiguration.class,
			SecurityFilterAutoConfiguration.class,
			ServerPropertiesAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	this.context.refresh();
	DelegatingFilterProxyRegistrationBean bean = this.context.getBean(
			"securityFilterChainRegistration",
			DelegatingFilterProxyRegistrationBean.class);
	@SuppressWarnings("unchecked")
	EnumSet<DispatcherType> dispatcherTypes = (EnumSet<DispatcherType>) ReflectionTestUtils
			.getField(bean, "dispatcherTypes");
	assertThat(dispatcherTypes).isNull();
}
 
Example 25
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: CrshAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testSpringAuthenticationProvider() throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	EnvironmentTestUtils.addEnvironment(this.context,
			"management.shell.auth.type=spring");
	this.context.setServletContext(new MockServletContext());
	this.context.register(SecurityConfiguration.class);
	this.context.register(CrshAutoConfiguration.class);
	this.context.refresh();
	PluginLifeCycle lifeCycle = this.context.getBean(PluginLifeCycle.class);
	AuthenticationPlugin<String> authenticationPlugin = null;
	String authentication = lifeCycle.getConfig().getProperty("crash.auth");
	assertThat(authentication).isNotNull();
	for (AuthenticationPlugin plugin : lifeCycle.getContext()
			.getPlugins(AuthenticationPlugin.class)) {
		if (authentication.equals(plugin.getName())) {
			authenticationPlugin = plugin;
			break;
		}
	}
	assertThat(authenticationPlugin.authenticate(SecurityConfiguration.USERNAME,
			SecurityConfiguration.PASSWORD)).isTrue();
	assertThat(authenticationPlugin.authenticate(UUID.randomUUID().toString(),
			SecurityConfiguration.PASSWORD)).isFalse();
}
 
Example 26
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: ManagementWebSecurityAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testWebConfiguration() throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());
	this.context.register(SecurityAutoConfiguration.class,
			WebMvcAutoConfiguration.class,
			ManagementWebSecurityAutoConfiguration.class,
			JacksonAutoConfiguration.class,
			HttpMessageConvertersAutoConfiguration.class,
			EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class,
			ManagementServerPropertiesAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	EnvironmentTestUtils.addEnvironment(this.context, "security.basic.enabled:false");
	this.context.refresh();
	assertThat(this.context.getBean(AuthenticationManagerBuilder.class)).isNotNull();
	FilterChainProxy filterChainProxy = this.context.getBean(FilterChainProxy.class);
	// 1 for static resources, one for management endpoints and one for the rest
	assertThat(filterChainProxy.getFilterChains()).hasSize(3);
	assertThat(filterChainProxy.getFilters("/beans")).isNotEmpty();
	assertThat(filterChainProxy.getFilters("/beans/")).isNotEmpty();
	assertThat(filterChainProxy.getFilters("/beans.foo")).isNotEmpty();
	assertThat(filterChainProxy.getFilters("/beans/foo/bar")).isNotEmpty();
}
 
Example 27
Project: spring-boot-concourse   File: ThymeleafAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void createLayoutFromConfigClass() throws Exception {
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	context.register(ThymeleafAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	MockServletContext servletContext = new MockServletContext();
	context.setServletContext(servletContext);
	context.refresh();
	ThymeleafView view = (ThymeleafView) context.getBean(ThymeleafViewResolver.class)
			.resolveViewName("view", Locale.UK);
	MockHttpServletResponse response = new MockHttpServletResponse();
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
	view.render(Collections.singletonMap("foo", "bar"), request, response);
	String result = response.getContentAsString();
	assertThat(result).contains("<title>Content</title>");
	assertThat(result).contains("<span>bar</span>");
	context.close();
}
 
Example 28
Project: spring-boot-concourse   File: SecurityAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testOverrideAuthenticationManagerWithBuilderAndInjectBuilderIntoSecurityFilter()
		throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());
	this.context.register(AuthenticationManagerCustomizer.class,
			WorkaroundSecurityCustomizer.class, SecurityAutoConfiguration.class,
			ServerPropertiesAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	this.context.refresh();
	UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(
			"foo", "bar",
			AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
	assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user))
			.isNotNull();
}
 
Example 29
Project: spring-boot-concourse   File: ManagementWebSecurityAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testMarkAllEndpointsSensitive() throws Exception {
	// gh-4368
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());
	this.context.register(WebConfiguration.class);
	EnvironmentTestUtils.addEnvironment(this.context, "endpoints.sensitive:true");
	this.context.refresh();

	MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) //
			.apply(springSecurity()) //
			.build();

	mockMvc //
			.perform(get("/health")) //
			.andExpect(status().isUnauthorized());
	mockMvc //
			.perform(get("/info")) //
			.andExpect(status().isUnauthorized());
}
 
Example 30
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: SecurityAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testJpaCoexistsHappily() throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());
	EnvironmentTestUtils.addEnvironment(this.context,
			"spring.datasource.url:jdbc:hsqldb:mem:testsecdb");
	EnvironmentTestUtils.addEnvironment(this.context,
			"spring.datasource.initialize:false");
	this.context.register(EntityConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class,
			DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
			SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class);
	// This can fail if security @Conditionals force early instantiation of the
	// HibernateJpaAutoConfiguration (e.g. the EntityManagerFactory is not found)
	this.context.refresh();
	assertThat(this.context.getBean(JpaTransactionManager.class)).isNotNull();
}
 
Example 31
Project: flowable-engine   File: TestServerUtil.java   View source code 6 votes vote down vote up
public static TestServer createAndStartServer(Class<?>... configClasses) {
    int port = NEXT_PORT.incrementAndGet();
    Server server = new Server(port);

    HashSessionIdManager idmanager = new HashSessionIdManager();
    server.setSessionIdManager(idmanager);

    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.register(configClasses);
    applicationContext.refresh();

    try {
        server.setHandler(getServletContextHandler(applicationContext));
        server.start();
    } catch (Exception e) {
        LOGGER.error("Error starting server", e);
    }

    return new TestServer(server, applicationContext, port);
}
 
Example 32
Project: spring-boot-concourse   File: SecurityAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testCustomAuthenticationDoesNotAuthenticateWithBootSecurityUser()
		throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());

	this.context.register(AuthenticationManagerCustomizer.class,
			SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class);
	this.context.refresh();

	SecurityProperties security = this.context.getBean(SecurityProperties.class);
	AuthenticationManager manager = this.context.getBean(AuthenticationManager.class);

	UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
			security.getUser().getName(), security.getUser().getPassword());
	try {
		manager.authenticate(token);
		fail("Expected Exception");
	}
	catch (AuthenticationException success) {
		// Expected
	}

	token = new UsernamePasswordAuthenticationToken("foo", "bar");
	assertThat(manager.authenticate(token)).isNotNull();
}
 
Example 33
Project: spring-boot-concourse   File: HypermediaAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void customizationOfSupportedMediaTypesCanBeDisabled() {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());
	this.context.register(BaseConfig.class);
	EnvironmentTestUtils.addEnvironment(this.context,
			"spring.hateoas.use-hal-as-default-json-media-type:false");
	this.context.refresh();
	RequestMappingHandlerAdapter handlerAdapter = this.context
			.getBean(RequestMappingHandlerAdapter.class);
	for (HttpMessageConverter<?> converter : handlerAdapter.getMessageConverters()) {
		if (converter instanceof TypeConstrainedMappingJackson2HttpMessageConverter) {
			assertThat(converter.getSupportedMediaTypes())
					.containsExactly(MediaTypes.HAL_JSON);
		}
	}
}
 
Example 34
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: SecurityAutoConfigurationTests.java   View source code 6 votes vote down vote up
@Test
public void testDefaultUsernamePassword() throws Exception {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.setServletContext(new MockServletContext());

	this.context.register(SecurityAutoConfiguration.class,
			ServerPropertiesAutoConfiguration.class);
	this.context.refresh();

	SecurityProperties security = this.context.getBean(SecurityProperties.class);
	AuthenticationManager manager = this.context.getBean(AuthenticationManager.class);

	UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
			security.getUser().getName(), security.getUser().getPassword());
	assertThat(manager.authenticate(token)).isNotNull();
}
 
Example 35
Project: singular-server   File: FormInitializer.java   View source code 6 votes vote down vote up
public void init(ServletContext ctx, AnnotationConfigWebApplicationContext applicationContext) {
    Class<?> documentFactory = documentFactory();
    if (documentFactory != null) {
        applicationContext.register(documentFactory);
    } else {
        logger.info(SINGULAR_FORM, " Null Form Document Factory, skipping Form Document Factory configuration. ");
    }
    Class<?> typeLoader = typeLoader();
    if (typeLoader != null) {
        applicationContext.register(typeLoader);
    } else {
        logger.info(SINGULAR_FORM, " Null Form Type Loader, skipping Form Type Loader configuration. ");
    }
    Class<?> formConfigFactory = formConfigFactory();
    if (formConfigFactory != null) {
        applicationContext.register(formConfigFactory);
    } else {
        logger.info(SINGULAR_FORM, " Null Form Config Factory, skipping Form Config Factory configuration. ");
    }
}
 
Example 36
Project: spring-security-oauth2-boot   File: MultipleResourceServerConfigurationTests.java   View source code 5 votes vote down vote up
@Test
public void orderIsUnchangedWhenThereAreMultipleResourceServerConfigurations() {
	this.context = new AnnotationConfigWebApplicationContext();
	this.context.register(DoubleResourceConfiguration.class);
	TestPropertyValues.of("security.oauth2.resource.tokenInfoUri:http://example.com",
			"security.oauth2.client.clientId=acme").applyTo(this.context);
	this.context.refresh();
	assertThat(this.context
			.getBean("adminResources", ResourceServerConfiguration.class).getOrder())
					.isEqualTo(3);
	assertThat(this.context
			.getBean("otherResources", ResourceServerConfiguration.class).getOrder())
					.isEqualTo(4);
}
 
Example 37
Project: Spring-5.0-Cookbook   File: SpringWebinitializer.java   View source code 5 votes vote down vote up
private void addRootContext(ServletContext container) {
  // Create the application context
  AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
  rootContext.register(SpringContextConfig.class); 
	 
  // Register application context with ContextLoaderListener
  container.addListener(new ContextLoaderListener(rootContext));
   
}
 
Example 38
Project: Spring-5.0-Cookbook   File: SpringWebinitializer.java   View source code 5 votes vote down vote up
private void addDispatcherContext(ServletContext container) {
  // Create the dispatcher servlet's Spring application context
  AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
  dispatcherContext.register(SpringDispatcherConfig.class); 
	 
  // Declare  <servlet> and <servlet-mapping> for the DispatcherServlet
  ServletRegistration.Dynamic dispatcher = container.addServlet("ch06-servlet", 
  		new DispatcherServlet(dispatcherContext));
  dispatcher.addMapping("/");
  dispatcher.setLoadOnStartup(1);
  
 
     
}
 
Example 39
Project: Spring-5.0-Cookbook   File: SpringWebInitializer.java   View source code 5 votes vote down vote up
private void addRootContext(ServletContext container) {
  // Create the application context
  AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
  rootContext.register(SpringContextConfig.class); 
	 
  // Register application context with ContextLoaderListener
  container.addListener(new ContextLoaderListener(rootContext));
  container.addListener(new AppSessionListener());
  container.setInitParameter("contextConfigLocation", "org.packt.secured.mvc.core");
  container.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); // if URL, enable sessionManagement URL rewriting   
}
 
Example 40
Project: Spring-5.0-Cookbook   File: SpringWebInitializer.java   View source code 5 votes vote down vote up
private void addDispatcherContext(ServletContext container) {
  // Create the dispatcher servlet's Spring application context
  AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
  dispatcherContext.register(SpringDispatcherConfig.class); 
	 
  // Declare  <servlet> and <servlet-mapping> for the DispatcherServlet
  ServletRegistration.Dynamic dispatcher = container.addServlet("ch04-servlet", 
  		new DispatcherServlet(dispatcherContext));
  dispatcher.addMapping("/");
  dispatcher.setLoadOnStartup(1);
  
 
     
}