org.springframework.web.context.WebApplicationContext Java Examples

The following examples show how to use org.springframework.web.context.WebApplicationContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebApplicationContextUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Find a custom {@code WebApplicationContext} for this web app.
 * @param sc the ServletContext to find the web application context for
 * @param attrName the name of the ServletContext attribute to look for
 * @return the desired WebApplicationContext for this web app, or {@code null} if none
 */
@Nullable
public static WebApplicationContext getWebApplicationContext(ServletContext sc, String attrName) {
	Assert.notNull(sc, "ServletContext must not be null");
	Object attr = sc.getAttribute(attrName);
	if (attr == null) {
		return null;
	}
	if (attr instanceof RuntimeException) {
		throw (RuntimeException) attr;
	}
	if (attr instanceof Error) {
		throw (Error) attr;
	}
	if (attr instanceof Exception) {
		throw new IllegalStateException((Exception) attr);
	}
	if (!(attr instanceof WebApplicationContext)) {
		throw new IllegalStateException("Context attribute is not of type WebApplicationContext: " + attr);
	}
	return (WebApplicationContext) attr;
}
 
Example #2
Source File: DelegatingFilterProxy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	// Lazily initialize the delegate if necessary.
	Filter delegateToUse = this.delegate;
	if (delegateToUse == null) {
		synchronized (this.delegateMonitor) {
			delegateToUse = this.delegate;
			if (delegateToUse == null) {
				WebApplicationContext wac = findWebApplicationContext();
				if (wac == null) {
					throw new IllegalStateException("No WebApplicationContext found: " +
							"no ContextLoaderListener or DispatcherServlet registered?");
				}
				delegateToUse = initDelegate(wac);
			}
			this.delegate = delegateToUse;
		}
	}

	// Let the delegate perform the actual doFilter operation.
	invokeDelegate(delegateToUse, request, response, filterChain);
}
 
Example #3
Source File: JobExecutionUtils.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
static MockMvc createBaseJobExecutionMockMvc(JobRepository jobRepository, TaskBatchDao taskBatchDao,
		TaskExecutionDao taskExecutionDao, WebApplicationContext wac, RequestMappingHandlerAdapter adapter) {
	MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac)
			.defaultRequest(get("/").accept(MediaType.APPLICATION_JSON)).build();
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_ORIG, 1);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FOO, 1);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FOOBAR, 2);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_COMPLETED, 1, BatchStatus.COMPLETED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_STARTED, 1, BatchStatus.STARTED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_STOPPED, 1, BatchStatus.STOPPED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FAILED1, 1, BatchStatus.FAILED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FAILED2, 1, BatchStatus.FAILED);
	for (HttpMessageConverter<?> converter : adapter.getMessageConverters()) {
		if (converter instanceof MappingJackson2HttpMessageConverter) {
			final MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter;
			jacksonConverter.getObjectMapper().addMixIn(StepExecution.class, StepExecutionJacksonMixIn.class);
			jacksonConverter.getObjectMapper().addMixIn(ExecutionContext.class, ExecutionContextJacksonMixIn.class);
			jacksonConverter.getObjectMapper().setDateFormat(new ISO8601DateFormatWithMilliSeconds());
		}
	}
	return mockMvc;
}
 
Example #4
Source File: TomcatWebSocketTestServer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void deployConfig(WebApplicationContext wac, Filter... filters) {
	Assert.state(this.port != -1, "setup() was never called.");
	this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));
	this.context.addApplicationListener(WsContextListener.class.getName());
	Tomcat.addServlet(this.context, "dispatcherServlet", new DispatcherServlet(wac)).setAsyncSupported(true);
	this.context.addServletMappingDecoded("/", "dispatcherServlet");
	for (Filter filter : filters) {
		FilterDef filterDef = new FilterDef();
		filterDef.setFilterName(filter.getClass().getName());
		filterDef.setFilter(filter);
		filterDef.setAsyncSupported("true");
		this.context.addFilterDef(filterDef);
		FilterMap filterMap = new FilterMap();
		filterMap.setFilterName(filter.getClass().getName());
		filterMap.addURLPattern("/*");
		filterMap.setDispatcher("REQUEST,FORWARD,INCLUDE,ASYNC");
		this.context.addFilterMap(filterMap);
	}
}
 
Example #5
Source File: MessageResolver.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 获得国际化信息
 * 
 * @param request
 *            HttpServletRequest
 * @param code
 *            国际化代码
 * @param args
 *            替换参数
 * @return
 * @see org.springframework.context.MessageSource#getMessage(String,
 *      Object[], Locale)
 */
public static String getMessage(HttpServletRequest request, String code,
		Object... args) {
	WebApplicationContext messageSource = RequestContextUtils
			.getWebApplicationContext(request);
	if (messageSource == null) {
		throw new IllegalStateException("WebApplicationContext not found!");
	}
	LocaleResolver localeResolver = RequestContextUtils
			.getLocaleResolver(request);
	Locale locale;
	if (localeResolver != null) {
		locale = localeResolver.resolveLocale(request);
	} else {
		locale = request.getLocale();
	}
	return messageSource.getMessage(code, args, locale);
}
 
Example #6
Source File: AbstractWidgetExecutorService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected List<IFrameDecoratorContainer> extractDecorators(RequestContext reqCtx) throws ApsSystemException {
	HttpServletRequest request = reqCtx.getRequest();
	WebApplicationContext wac = ApsWebApplicationUtils.getWebApplicationContext(request);
	List<IFrameDecoratorContainer> containters = new ArrayList<IFrameDecoratorContainer>();
	try {
		String[] beanNames = wac.getBeanNamesForType(IFrameDecoratorContainer.class);
		for (int i = 0; i < beanNames.length; i++) {
			IFrameDecoratorContainer container = (IFrameDecoratorContainer) wac.getBean(beanNames[i]);
			containters.add(container);
		}
		BeanComparator comparator = new BeanComparator("order");
		Collections.sort(containters, comparator);
	} catch (Throwable t) {
		_logger.error("Error extracting widget decorators", t);
		throw new ApsSystemException("Error extracting widget decorators", t);
	}
	return containters;
}
 
Example #7
Source File: AbstractTagTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected MockPageContext createPageContext() {
	MockServletContext sc = new MockServletContext();
	SimpleWebApplicationContext wac = new SimpleWebApplicationContext();
	wac.setServletContext(sc);
	wac.setNamespace("test");
	wac.refresh();

	MockHttpServletRequest request = new MockHttpServletRequest(sc);
	MockHttpServletResponse response = new MockHttpServletResponse();
	if (inDispatcherServlet()) {
		request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
		LocaleResolver lr = new AcceptHeaderLocaleResolver();
		request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, lr);
		ThemeResolver tr = new FixedThemeResolver();
		request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, tr);
		request.setAttribute(DispatcherServlet.THEME_SOURCE_ATTRIBUTE, wac);
	}
	else {
		sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	}

	return new MockPageContext(sc, request, response);
}
 
Example #8
Source File: DelegatingFilterProxy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Return the {@code WebApplicationContext} passed in at construction time, if available.
 * Otherwise, attempt to retrieve a {@code WebApplicationContext} from the
 * {@code ServletContext} attribute with the {@linkplain #setContextAttribute
 * configured name} if set. Otherwise look up a {@code WebApplicationContext} under
 * the well-known "root" application context attribute. The
 * {@code WebApplicationContext} must have already been loaded and stored in the
 * {@code ServletContext} before this filter gets initialized (or invoked).
 * <p>Subclasses may override this method to provide a different
 * {@code WebApplicationContext} retrieval strategy.
 * @return the {@code WebApplicationContext} for this proxy, or {@code null} if not found
 * @see #DelegatingFilterProxy(String, WebApplicationContext)
 * @see #getContextAttribute()
 * @see WebApplicationContextUtils#getWebApplicationContext(javax.servlet.ServletContext)
 * @see WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
 */
@Nullable
protected WebApplicationContext findWebApplicationContext() {
	if (this.webApplicationContext != null) {
		// The user has injected a context at construction time -> use it...
		if (this.webApplicationContext instanceof ConfigurableApplicationContext) {
			ConfigurableApplicationContext cac = (ConfigurableApplicationContext) this.webApplicationContext;
			if (!cac.isActive()) {
				// The context has not yet been refreshed -> do so before returning it...
				cac.refresh();
			}
		}
		return this.webApplicationContext;
	}
	String attrName = getContextAttribute();
	if (attrName != null) {
		return WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);
	}
	else {
		return WebApplicationContextUtils.findWebApplicationContext(getServletContext());
	}
}
 
Example #9
Source File: TomcatWebSocketTestServer.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void deployConfig(WebApplicationContext wac, Filter... filters) {
	Assert.state(this.port != -1, "setup() was never called.");
	this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));
	this.context.addApplicationListener(WsContextListener.class.getName());
	Tomcat.addServlet(this.context, "dispatcherServlet", new DispatcherServlet(wac)).setAsyncSupported(true);
	this.context.addServletMappingDecoded("/", "dispatcherServlet");
	for (Filter filter : filters) {
		FilterDef filterDef = new FilterDef();
		filterDef.setFilterName(filter.getClass().getName());
		filterDef.setFilter(filter);
		filterDef.setAsyncSupported("true");
		this.context.addFilterDef(filterDef);
		FilterMap filterMap = new FilterMap();
		filterMap.setFilterName(filter.getClass().getName());
		filterMap.addURLPattern("/*");
		filterMap.setDispatcher("REQUEST,FORWARD,INCLUDE,ASYNC");
		this.context.addFilterMap(filterMap);
	}
}
 
Example #10
Source File: DelegatingFilterProxyTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testDelegatingFilterProxyWithTargetBeanName() throws ServletException, IOException {
	MockServletContext sc = new MockServletContext();

	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(sc);
	wac.registerSingleton("targetFilter", MockFilter.class);
	wac.refresh();
	sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

	MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");

	DelegatingFilterProxy filterProxy = new DelegatingFilterProxy("targetFilter");
	filterProxy.init(new MockFilterConfig(sc));

	MockHttpServletRequest request = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	filterProxy.doFilter(request, response, null);

	assertNull(targetFilter.filterConfig);
	assertEquals(Boolean.TRUE, request.getAttribute("called"));

	filterProxy.destroy();
	assertNull(targetFilter.filterConfig);
}
 
Example #11
Source File: SpringConfigurator.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private String getBeanNameByType(WebApplicationContext wac, Class<?> endpointClass) {
	String wacId = wac.getId();

	Map<Class<?>, String> beanNamesByType = cache.get(wacId);
	if (beanNamesByType == null) {
		beanNamesByType = new ConcurrentHashMap<Class<?>, String>();
		cache.put(wacId, beanNamesByType);
	}

	if (!beanNamesByType.containsKey(endpointClass)) {
		String[] names = wac.getBeanNamesForType(endpointClass);
		if (names.length == 1) {
			beanNamesByType.put(endpointClass, names[0]);
		}
		else {
			beanNamesByType.put(endpointClass, NO_VALUE);
			if (names.length > 1) {
				throw new IllegalStateException("Found multiple @ServerEndpoint's of type [" +
						endpointClass.getName() + "]: bean names " + Arrays.asList(names));
			}
		}
	}

	String beanName = beanNamesByType.get(endpointClass);
	return (NO_VALUE.equals(beanName) ? null : beanName);
}
 
Example #12
Source File: WebApplicationContextUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Register web-specific scopes ("request", "session", "globalSession", "application")
 * with the given BeanFactory, as used by the WebApplicationContext.
 * @param beanFactory the BeanFactory to configure
 * @param sc the ServletContext that we're running within
 */
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory, ServletContext sc) {
	beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
	beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope(false));
	beanFactory.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION, new SessionScope(true));
	if (sc != null) {
		ServletContextScope appScope = new ServletContextScope(sc);
		beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
		// Register as ServletContext attribute, for ContextCleanupListener to detect it.
		sc.setAttribute(ServletContextScope.class.getName(), appScope);
	}

	beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory());
	beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
	beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
	beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
	if (jsfPresent) {
		FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
	}
}
 
Example #13
Source File: SpringBeanAutowiringSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testProcessInjectionBasedOnServletContext() {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	AnnotationConfigUtils.registerAnnotationConfigProcessors(wac);

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("name", "tb");
	wac.registerSingleton("testBean", TestBean.class, pvs);

	MockServletContext sc = new MockServletContext();
	wac.setServletContext(sc);
	wac.refresh();
	sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

	InjectionTarget target = new InjectionTarget();
	SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(target, sc);
	assertTrue(target.testBean instanceof TestBean);
	assertEquals("tb", target.name);
}
 
Example #14
Source File: UriTemplateServletAnnotationControllerHandlerMethodTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void pathVarsInModel() throws Exception {
	final Map<String, Object> pathVars = new HashMap<>();
	pathVars.put("hotel", "42");
	pathVars.put("booking", 21);
	pathVars.put("other", "other");

	WebApplicationContext wac =
		initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
			@Override
			public void initialize(GenericWebApplicationContext context) {
				RootBeanDefinition beanDef = new RootBeanDefinition(ModelValidatingViewResolver.class);
				beanDef.getConstructorArgumentValues().addGenericArgumentValue(pathVars);
				context.registerBeanDefinition("viewResolver", beanDef);
			}
		}, ViewRenderingController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42;q=1,2/bookings/21-other;q=3;r=R");
	getServlet().service(request, new MockHttpServletResponse());

	ModelValidatingViewResolver resolver = wac.getBean(ModelValidatingViewResolver.class);
	assertEquals(3, resolver.validatedAttrCount);
}
 
Example #15
Source File: StaticContentTagTest.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Test
public void doStartTag_validKey() throws IOException, JspException {
    tag.setContentKey(VALID_CACHE_KEY);
    
    expect(service.getContent(VALID_CACHE_KEY)).andReturn(VALID_STATIC_CONTENT);
    expect(pageContext.getServletContext()).andReturn(servletContext).anyTimes();
    expect(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).andReturn(wContext).anyTimes();
    expect(wContext.getBean(StaticContentFetcherService.class)).andReturn(service).anyTimes();
    expect(pageContext.getOut()).andReturn(writer);
    replay(service, pageContext, servletContext, wContext, writer);

    int result = tag.doStartTag();

    assertThat(result, is(javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE));
    verify(service, pageContext, servletContext, wContext, writer);
}
 
Example #16
Source File: MvcUriComponentsBuilder.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private static CompositeUriComponentsContributor getConfiguredUriComponentsContributor() {
	WebApplicationContext wac = getWebApplicationContext();
	if (wac == null) {
		return null;
	}
	try {
		return wac.getBean(MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME, CompositeUriComponentsContributor.class);
	}
	catch (NoSuchBeanDefinitionException ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("No CompositeUriComponentsContributor bean with name '" +
					MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME + "'");
		}
		return null;
	}
}
 
Example #17
Source File: LocalDataflowResource.java    From spring-cloud-dashboard with Apache License 2.0 6 votes vote down vote up
@Override
protected void before() throws Throwable {
	originalConfigLocation = System.getProperty("spring.config.location");
	if (!StringUtils.isEmpty(configurationLocation)) {
		System.setProperty("spring.config.location", configurationLocation);
	}

	app = new SpringApplication(LocalTestDataFlowServer.class);
	configurableApplicationContext = (WebApplicationContext) app.run(new String[]{"--server.port=0"});

	Collection<Filter> filters = configurableApplicationContext.getBeansOfType(Filter.class).values();
	mockMvc = MockMvcBuilders.webAppContextSetup(configurableApplicationContext)
			.addFilters(filters.toArray(new Filter[filters.size()]))
			.build();
	dataflowPort = configurableApplicationContext.getEnvironment().resolvePlaceholders("${server.port}");
}
 
Example #18
Source File: MockMvcBuilderSupport.java    From java-technology-stack with MIT License 6 votes vote down vote up
protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig,
		WebApplicationContext webAppContext, @Nullable RequestBuilder defaultRequestBuilder,
		List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers,
		@Nullable List<DispatcherServletCustomizer> dispatcherServletCustomizers) {

	TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext);
	if (dispatcherServletCustomizers != null) {
		for (DispatcherServletCustomizer customizers : dispatcherServletCustomizers) {
			customizers.customize(dispatcherServlet);
		}
	}
	try {
		dispatcherServlet.init(servletConfig);
	}
	catch (ServletException ex) {
		// should never happen..
		throw new MockMvcBuildException("Failed to initialize TestDispatcherServlet", ex);
	}

	MockMvc mockMvc = new MockMvc(dispatcherServlet, filters);
	mockMvc.setDefaultRequest(defaultRequestBuilder);
	mockMvc.setGlobalResultMatchers(globalResultMatchers);
	mockMvc.setGlobalResultHandlers(globalResultHandlers);

	return mockMvc;
}
 
Example #19
Source File: SpringWebTestUtils.java    From junit-servers with MIT License 5 votes vote down vote up
/**
 * Ensure the servlet context can be retrieved from embedded server, and spring web application
 * context can be retrieved from it.
 *
 * @param server The embedded server.
 */
static void verifySpringWebContext(EmbeddedServer<?> server) {
	// Try to get servlet context
	ServletContext servletContext = server.getServletContext();
	assertThat(servletContext).isNotNull();

	// Try to retrieve spring webApplicationContext
	WebApplicationContext webApplicationContext = getWebApplicationContext(servletContext);
	assertThat(webApplicationContext).isNotNull();
}
 
Example #20
Source File: DelegatingFilterProxyTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testDelegatingFilterProxyWithTargetFilterLifecycle() throws ServletException, IOException {
	ServletContext sc = new MockServletContext();

	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(sc);
	wac.registerSingleton("targetFilter", MockFilter.class);
	wac.refresh();
	sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

	MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");

	MockFilterConfig proxyConfig = new MockFilterConfig(sc);
	proxyConfig.addInitParameter("targetBeanName", "targetFilter");
	proxyConfig.addInitParameter("targetFilterLifecycle", "true");
	DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
	filterProxy.init(proxyConfig);
	assertEquals(proxyConfig, targetFilter.filterConfig);

	MockHttpServletRequest request = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	filterProxy.doFilter(request, response, null);

	assertEquals(proxyConfig, targetFilter.filterConfig);
	assertEquals(Boolean.TRUE, request.getAttribute("called"));

	filterProxy.destroy();
	assertNull(targetFilter.filterConfig);
}
 
Example #21
Source File: OpenSessionInViewFilter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Look up the SessionFactory that this filter should use.
 * <p>The default implementation looks for a bean with the specified name
 * in Spring's root application context.
 * @return the SessionFactory to use
 * @see #getSessionFactoryBeanName
 */
protected SessionFactory lookupSessionFactory() {
	if (logger.isDebugEnabled()) {
		logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter");
	}
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	return wac.getBean(getSessionFactoryBeanName(), SessionFactory.class);
}
 
Example #22
Source File: SecurityAdviceTraitTest.java    From problem-spring-web with MIT License 5 votes vote down vote up
@Bean
public MockMvc mvc(final WebApplicationContext context) {
    return MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity())
            .build();
}
 
Example #23
Source File: FrameworkServlet.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Instantiate the WebApplicationContext for this servlet, either a default
 * {@link org.springframework.web.context.support.XmlWebApplicationContext}
 * or a {@link #setContextClass custom context class}, if set.
 * <p>This implementation expects custom contexts to implement the
 * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
 * interface. Can be overridden in subclasses.
 * <p>Do not forget to register this servlet instance as application listener on the
 * created context (for triggering its {@link #onRefresh callback}, and to call
 * {@link org.springframework.context.ConfigurableApplicationContext#refresh()}
 * before returning the context instance.
 * @param parent the parent ApplicationContext to use, or {@code null} if none
 * @return the WebApplicationContext for this servlet
 * @see org.springframework.web.context.support.XmlWebApplicationContext
 */
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
	// 允许我们自定义容器的类型,通过 contextClass 属性进行配置
	// 但是类型必须要继承 ConfigurableWebApplicationContext,不然将会报错
	Class<?> contextClass = getContextClass();
	if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
		throw new ApplicationContextException(
				"Fatal initialization error in servlet with name '" + getServletName() +
				"': custom WebApplicationContext class [" + contextClass.getName() +
				"] is not of type ConfigurableWebApplicationContext");
	}
	// 通过反射来创建 contextClass
	ConfigurableWebApplicationContext wac =
			(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

	wac.setEnvironment(getEnvironment());
	wac.setParent(parent);
	// 获取 contextConfigLocation 属性,配置在 servlet 初始化函数中
	String configLocation = getContextConfigLocation();
	if (configLocation != null) {
		wac.setConfigLocation(configLocation);
	}
	// 初始化 Spring 环境包括加载配置环境
	configureAndRefreshWebApplicationContext(wac);

	return wac;
}
 
Example #24
Source File: FreeMarkerViewTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void noFreeMarkerConfig() throws Exception {
	FreeMarkerView fv = new FreeMarkerView();

	WebApplicationContext wac = mock(WebApplicationContext.class);
	given(wac.getBeansOfType(FreeMarkerConfig.class, true, false)).willReturn(new HashMap<>());
	given(wac.getServletContext()).willReturn(new MockServletContext());

	fv.setUrl("anythingButNull");

	assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() ->
			fv.setApplicationContext(wac))
		.withMessageContaining("FreeMarkerConfig");
}
 
Example #25
Source File: ApiDocumentationJUnit5IntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeEach
public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
        .apply(documentationConfiguration(restDocumentation))
        .alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
        .build();
}
 
Example #26
Source File: DefaultMockMvcBuilderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * See SPR-12553 and SPR-13075.
 */
@Test
public void rootWacServletContainerAttributeNotPreviouslySet() {
	StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
	DefaultMockMvcBuilder builder = webAppContextSetup(root);
	WebApplicationContext wac = builder.initWebAppContext();
	assertSame(root, wac);
	assertSame(root, WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
 
Example #27
Source File: FrameworkExtensionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder,
		WebApplicationContext context) {
	return request -> {
		request.setUserPrincipal(mock(Principal.class));
		return request;
	};
}
 
Example #28
Source File: JPAWebConfigurer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent sce) {
    LOGGER.info("Destroying Web application");
    WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
    AnnotationConfigWebApplicationContext gwac = (AnnotationConfigWebApplicationContext) ac;
    gwac.close();
    LOGGER.debug("Web application destroyed");
}
 
Example #29
Source File: WebAppUtils.java    From Mykit with Apache License 2.0 5 votes vote down vote up
public static WebApplicationContext getInstance(){
	if(wac == null){
		synchronized (WebAppUtils.class) {
			if(wac == null){
				if(servletContext != null){
					  wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
				}
			}
		}
	}
	return wac;
}
 
Example #30
Source File: MockHttpServletRequestBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private FlashMapManager getFlashMapManager(MockHttpServletRequest request) {
	FlashMapManager flashMapManager = null;
	try {
		ServletContext servletContext = request.getServletContext();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		flashMapManager = wac.getBean(DispatcherServlet.FLASH_MAP_MANAGER_BEAN_NAME, FlashMapManager.class);
	}
	catch (IllegalStateException | NoSuchBeanDefinitionException ex) {
		// ignore
	}
	return (flashMapManager != null ? flashMapManager : new SessionFlashMapManager());
}