Java Code Examples for org.springframework.web.context.WebApplicationContext#getServletContext()

The following examples show how to use org.springframework.web.context.WebApplicationContext#getServletContext() . 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: EurekaStore.java    From qconfig with MIT License 6 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    ApplicationContext applicationContext = event.getApplicationContext();
    if (applicationContext.getParent() != null) {
        return;
    }

    logger.info("init eureka store");
    try {
        context = (WebApplicationContext) applicationContext;

        initEurekaEnvironment();
        initEurekaServerContext();

        ServletContext sc = context.getServletContext();
        sc.setAttribute(EurekaServerContext.class.getName(), serverContext);
    } catch (Throwable e) {
        logger.error("Cannot bootstrap eureka server :", e);
        throw new RuntimeException("Cannot bootstrap eureka server :", e);
    }
}
 
Example 2
Source File: AbstractMockMvcBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Build a {@link org.springframework.test.web.servlet.MockMvc} instance.
 */
@Override
@SuppressWarnings("rawtypes")
public final MockMvc build() {
	WebApplicationContext wac = initWebAppContext();
	ServletContext servletContext = wac.getServletContext();
	MockServletConfig mockServletConfig = new MockServletConfig(servletContext);

	for (MockMvcConfigurer configurer : this.configurers) {
		RequestPostProcessor processor = configurer.beforeMockMvcCreated(this, wac);
		if (processor != null) {
			if (this.defaultRequestBuilder == null) {
				this.defaultRequestBuilder = MockMvcRequestBuilders.get("/");
			}
			if (this.defaultRequestBuilder instanceof ConfigurableSmartRequestBuilder) {
				((ConfigurableSmartRequestBuilder) this.defaultRequestBuilder).with(processor);
			}
		}
	}

	Filter[] filterArray = this.filters.toArray(new Filter[0]);

	return super.createMockMvc(filterArray, mockServletConfig, wac, this.defaultRequestBuilder,
			this.globalResultMatchers, this.globalResultHandlers, this.dispatcherServletCustomizers);
}
 
Example 3
Source File: MockMvcBuilderSupport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig,
		WebApplicationContext webAppContext, RequestBuilder defaultRequestBuilder,
		List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers,
		Boolean dispatchOptions) {

	ServletContext servletContext = webAppContext.getServletContext();

	TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext);
	dispatcherServlet.setDispatchOptionsRequest(dispatchOptions);
	try {
		dispatcherServlet.init(servletConfig);
	}
	catch (ServletException ex) {
		// should never happen..
		throw new MockMvcBuildException("Failed to initialize TestDispatcherServlet", ex);
	}

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

	return mockMvc;
}
 
Example 4
Source File: ControllerIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyRootWacSupport() {
	assertEquals("foo", foo);
	assertEquals("bar", bar);

	ApplicationContext parent = wac.getParent();
	assertNotNull(parent);
	assertTrue(parent instanceof WebApplicationContext);
	WebApplicationContext root = (WebApplicationContext) parent;
	assertFalse(root.getBeansOfType(String.class).containsKey("bar"));

	ServletContext childServletContext = wac.getServletContext();
	assertNotNull(childServletContext);
	ServletContext rootServletContext = root.getServletContext();
	assertNotNull(rootServletContext);
	assertSame(childServletContext, rootServletContext);

	assertSame(root, rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
	assertSame(root, childServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
}
 
Example 5
Source File: JavaConfigTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Verify that the breaking change introduced in <a
 * href="https://jira.spring.io/browse/SPR-12553">SPR-12553</a> has been reverted.
 *
 * <p>This code has been copied from
 * {@link org.springframework.test.context.hierarchies.web.ControllerIntegrationTests}.
 *
 * @see org.springframework.test.context.hierarchies.web.ControllerIntegrationTests#verifyRootWacSupport()
 */
private void verifyRootWacSupport() {
	assertNotNull(personDao);
	assertNotNull(personController);

	ApplicationContext parent = wac.getParent();
	assertNotNull(parent);
	assertTrue(parent instanceof WebApplicationContext);
	WebApplicationContext root = (WebApplicationContext) parent;

	ServletContext childServletContext = wac.getServletContext();
	assertNotNull(childServletContext);
	ServletContext rootServletContext = root.getServletContext();
	assertNotNull(rootServletContext);
	assertSame(childServletContext, rootServletContext);

	assertSame(root, rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
	assertSame(root, childServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
}
 
Example 6
Source File: ControllerIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void verifyRootWacSupport() {
	assertEquals("foo", foo);
	assertEquals("bar", bar);

	ApplicationContext parent = wac.getParent();
	assertNotNull(parent);
	assertTrue(parent instanceof WebApplicationContext);
	WebApplicationContext root = (WebApplicationContext) parent;
	assertFalse(root.getBeansOfType(String.class).containsKey("bar"));

	ServletContext childServletContext = wac.getServletContext();
	assertNotNull(childServletContext);
	ServletContext rootServletContext = root.getServletContext();
	assertNotNull(rootServletContext);
	assertSame(childServletContext, rootServletContext);

	assertSame(root, rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
	assertSame(root, childServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
}
 
Example 7
Source File: JavaConfigTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that the breaking change introduced in <a
 * href="https://jira.spring.io/browse/SPR-12553">SPR-12553</a> has been reverted.
 *
 * <p>This code has been copied from
 * {@link org.springframework.test.context.hierarchies.web.ControllerIntegrationTests}.
 *
 * @see org.springframework.test.context.hierarchies.web.ControllerIntegrationTests#verifyRootWacSupport()
 */
private void verifyRootWacSupport() {
	assertNotNull(personDao);
	assertNotNull(personController);

	ApplicationContext parent = wac.getParent();
	assertNotNull(parent);
	assertTrue(parent instanceof WebApplicationContext);
	WebApplicationContext root = (WebApplicationContext) parent;

	ServletContext childServletContext = wac.getServletContext();
	assertNotNull(childServletContext);
	ServletContext rootServletContext = root.getServletContext();
	assertNotNull(rootServletContext);
	assertSame(childServletContext, rootServletContext);

	assertSame(root, rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
	assertSame(root, childServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
}
 
Example 8
Source File: MVCConfig.java    From convergent-ui with Apache License 2.0 5 votes vote down vote up
@Bean
public ThymeleafViewResolver thymeleafViewResolver(WebApplicationContext wac) {
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(wac.getServletContext());
    templateResolver.setPrefix("/WEB-INF/templates/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("HTML");
    templateResolver.setCharacterEncoding("UTF-8");
    templateEngine.setTemplateResolver(templateResolver);
    resolver.setTemplateEngine(templateEngine);
    resolver.setOrder(2);
    resolver.setApplicationContext(wac);
    resolver.setCharacterEncoding("UTF-8");

    //Enable the Spring Security Thymeleaf integration
    templateEngine.addDialect(new LayoutDialect());

    // caching
    String[] activeProfiles = env.getActiveProfiles();
    if (Arrays.asList(activeProfiles).contains("dev")) {
        log.info("DEV Profile is active. Disabling template caching.");
        templateResolver.setCacheable(false);
        templateEngine.setCacheManager(null);
        resolver.setCache(false);
    }
    return resolver;
}
 
Example 9
Source File: VSCrawlerManager.java    From vscrawler with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
    webApplicationContext = (WebApplicationContext) applicationContext;
    ServletContext servletContext = webApplicationContext.getServletContext();
    webAppPath = servletContext.getRealPath("/");
    init();
}
 
Example 10
Source File: AbstractMockMvcBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Build a {@link org.springframework.test.web.servlet.MockMvc} instance.
 */
@Override
@SuppressWarnings("rawtypes")
public final MockMvc build() {

	WebApplicationContext wac = initWebAppContext();

	ServletContext servletContext = wac.getServletContext();
	MockServletConfig mockServletConfig = new MockServletConfig(servletContext);

	for (MockMvcConfigurer configurer : this.configurers) {
		RequestPostProcessor processor = configurer.beforeMockMvcCreated(this, wac);
		if (processor != null) {
			if (this.defaultRequestBuilder == null) {
				this.defaultRequestBuilder = MockMvcRequestBuilders.get("/");
			}
			if (this.defaultRequestBuilder instanceof ConfigurableSmartRequestBuilder) {
				((ConfigurableSmartRequestBuilder) this.defaultRequestBuilder).with(processor);
			}
		}
	}

	Filter[] filterArray = this.filters.toArray(new Filter[this.filters.size()]);

	return super.createMockMvc(filterArray, mockServletConfig, wac, this.defaultRequestBuilder,
			this.globalResultMatchers, this.globalResultHandlers, this.dispatchOptions);
}
 
Example 11
Source File: CacheUtil.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public static void cacheSessionAndToken(WebApplicationContext webApplicationContext,String authenticationResult) {
    JSONObject jsonObj=JSONUtils.string2JSON(authenticationResult);
    String sessionID=(String) jsonObj.get("sessionID");
    String token=(String) jsonObj.get("token");
    MockServletContext application = (MockServletContext) webApplicationContext.getServletContext();
    application.setAttribute("sessionID", sessionID);
    application.setAttribute("token", token);
}
 
Example 12
Source File: MockServerContainerContextCustomizer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
	if (context instanceof WebApplicationContext) {
		WebApplicationContext wac = (WebApplicationContext) context;
		ServletContext sc = wac.getServletContext();
		if (sc != null) {
			sc.setAttribute("javax.websocket.server.ServerContainer", new MockServerContainer());
		}
	}
}
 
Example 13
Source File: MockServerContainerContextCustomizer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
	if (context instanceof WebApplicationContext) {
		WebApplicationContext wac = (WebApplicationContext) context;
		ServletContext sc = wac.getServletContext();
		if (sc != null) {
			sc.setAttribute("javax.websocket.server.ServerContainer", new MockServerContainer());
		}
	}
}
 
Example 14
Source File: RequestUtil.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public static HttpHeaders getHeaders(WebApplicationContext webApplicationContext) {
    MockServletContext application = (MockServletContext) webApplicationContext.getServletContext();
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("sessionID", (String) application.getAttribute("sessionID"));
    httpHeaders.add("token", (String) application.getAttribute("token"));
    return httpHeaders;
}
 
Example 15
Source File: ServletTestExecutionListener.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void setUpRequestContextIfNecessary(TestContext testContext) {
	if (!isActivated(testContext) || alreadyPopulatedRequestContextHolder(testContext)) {
		return;
	}

	ApplicationContext context = testContext.getApplicationContext();

	if (context instanceof WebApplicationContext) {
		WebApplicationContext wac = (WebApplicationContext) context;
		ServletContext servletContext = wac.getServletContext();
		Assert.state(servletContext instanceof MockServletContext, () -> String.format(
					"The WebApplicationContext for test context %s must be configured with a MockServletContext.",
					testContext));

		if (logger.isDebugEnabled()) {
			logger.debug(String.format(
					"Setting up MockHttpServletRequest, MockHttpServletResponse, ServletWebRequest, and RequestContextHolder for test context %s.",
					testContext));
		}

		MockServletContext mockServletContext = (MockServletContext) servletContext;
		MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
		request.setAttribute(CREATED_BY_THE_TESTCONTEXT_FRAMEWORK, Boolean.TRUE);
		MockHttpServletResponse response = new MockHttpServletResponse();
		ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);

		RequestContextHolder.setRequestAttributes(servletWebRequest);
		testContext.setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
		testContext.setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);

		if (wac instanceof ConfigurableApplicationContext) {
			@SuppressWarnings("resource")
			ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) wac;
			ConfigurableListableBeanFactory bf = configurableApplicationContext.getBeanFactory();
			bf.registerResolvableDependency(MockHttpServletResponse.class, response);
			bf.registerResolvableDependency(ServletWebRequest.class, servletWebRequest);
		}
	}
}
 
Example 16
Source File: Tools.java    From ApiManager with GNU Affero General Public License v3.0 4 votes vote down vote up
public static ServletContext getServletContext() {
    WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
    return webApplicationContext.getServletContext();
}
 
Example 17
Source File: SpringServiceNameInstrumentation.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class)
public static void afterInitPropertySources(@Advice.This WebApplicationContext applicationContext) {
    if (tracer != null && applicationContext.getServletContext() != null) {
        tracer.overrideServiceNameForClassLoader(applicationContext.getServletContext().getClassLoader(), applicationContext.getEnvironment().getProperty("spring.application.name"));
    }
}
 
Example 18
Source File: RequestUtil.java    From singleton with Eclipse Public License 2.0 4 votes vote down vote up
public static MockHttpSession getSession(WebApplicationContext webApplicationContext) {
    MockServletContext application = (MockServletContext) webApplicationContext.getServletContext();
    MockHttpSession session=new MockHttpSession();
    session.setAttribute("token", application.getAttribute("token"));
    return session;
}
 
Example 19
Source File: RequestUtil.java    From singleton with Eclipse Public License 2.0 4 votes vote down vote up
public static Cookie getCookies(WebApplicationContext webApplicationContext) {
    MockServletContext application = (MockServletContext) webApplicationContext.getServletContext();
    Cookie cookies = new Cookie("JSESSIONID",(String) application.getAttribute("sessionID"));
    return cookies;
}
 
Example 20
Source File: RequestUtil.java    From singleton with Eclipse Public License 2.0 4 votes vote down vote up
public static MockHttpSession getSession(WebApplicationContext webApplicationContext) {
    MockServletContext application = (MockServletContext) webApplicationContext.getServletContext();
    MockHttpSession session=new MockHttpSession();
    session.setAttribute("token", application.getAttribute("token"));
    return session;
}