Java Code Examples for org.springframework.web.util.WebUtils

The following examples show how to use org.springframework.web.util.WebUtils. These examples are extracted from open source projects. 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 Project: spring4-understanding   Source File: HtmlEscapeTagTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void htmlEscapeTagWithContextParamTrue() throws JspException {
	PageContext pc = createPageContext();
	MockServletContext sc = (MockServletContext) pc.getServletContext();
	sc.addInitParameter(WebUtils.HTML_ESCAPE_CONTEXT_PARAM, "true");
	HtmlEscapeTag tag = new HtmlEscapeTag();
	tag.setDefaultHtmlEscape(false);
	tag.setPageContext(pc);
	tag.doStartTag();

	assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape());
	tag.setDefaultHtmlEscape(true);
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape());
	tag.setDefaultHtmlEscape(false);
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape());
}
 
Example 2
Source Project: jpetstore-kubernetes   Source File: ViewCartController.java    License: Apache License 2.0 6 votes vote down vote up
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
	UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
	Cart cart = (Cart) WebUtils.getOrCreateSessionAttribute(request.getSession(), "sessionCart", Cart.class);
	String page = request.getParameter("page");
	if (userSession != null) {
		if ("next".equals(page)) {
			userSession.getMyList().nextPage();
		}
		else if ("previous".equals(page)) {
			userSession.getMyList().previousPage();
		}
	}
	if ("nextCart".equals(page)) {
		cart.getCartItemList().nextPage();
	}
	else if ("previousCart".equals(page)) {
		cart.getCartItemList().previousPage();
	}
	return new ModelAndView(this.successView, "cart", cart);
}
 
Example 3
Source Project: spring-analysis-note   Source File: XsltView.java    License: MIT License 6 votes vote down vote up
/**
 * Configure the supplied {@link HttpServletResponse}.
 * <p>The default implementation of this method sets the
 * {@link HttpServletResponse#setContentType content type} and
 * {@link HttpServletResponse#setCharacterEncoding encoding}
 * from the "media-type" and "encoding" output properties
 * specified in the {@link Transformer}.
 * @param model merged output Map (never {@code null})
 * @param response current HTTP response
 * @param transformer the target transformer
 */
protected void configureResponse(Map<String, Object> model, HttpServletResponse response, Transformer transformer) {
	String contentType = getContentType();
	String mediaType = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
	String encoding = transformer.getOutputProperty(OutputKeys.ENCODING);
	if (StringUtils.hasText(mediaType)) {
		contentType = mediaType;
	}
	if (StringUtils.hasText(encoding)) {
		// Only apply encoding if content type is specified but does not contain charset clause already.
		if (contentType != null && !contentType.toLowerCase().contains(WebUtils.CONTENT_TYPE_CHARSET_PREFIX)) {
			contentType = contentType + WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding;
		}
	}
	response.setContentType(contentType);
}
 
Example 4
@Test
public void encodingIfEmptyAndNotForced() throws Exception {
	HttpServletRequest request = mock(HttpServletRequest.class);
	given(request.getCharacterEncoding()).willReturn(null);
	given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
	given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);

	MockHttpServletResponse response = new MockHttpServletResponse();

	FilterChain filterChain = mock(FilterChain.class);

	CharacterEncodingFilter filter = new CharacterEncodingFilter(ENCODING);
	filter.init(new MockFilterConfig(FILTER_NAME));
	filter.doFilter(request, response, filterChain);

	verify(request).setCharacterEncoding(ENCODING);
	verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
	verify(request).removeAttribute(filteredName(FILTER_NAME));
	verify(filterChain).doFilter(request, response);
}
 
Example 5
Source Project: onetwo   Source File: RedisSecurityContextRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
	SaveToSessionResponseWrapper responseWrapper = WebUtils.getNativeResponse(response, SaveToSessionResponseWrapper.class);
	if (responseWrapper == null) {
		throw new IllegalStateException(
				"Cannot invoke saveContext on response "
						+ response
						+ ". You must use the HttpRequestResponseHolder.response after invoking loadContext");
	}
	// saveContext() might already be called by the response wrapper
	// if something in the chain called sendError() or sendRedirect(). This ensures we
	// only call it
	// once per request.
	if (!responseWrapper.isContextSaved()) {
		responseWrapper.saveContext(context);
	}
}
 
Example 6
@RequestMapping("/logout")
public String logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
    session.invalidate();
    Cookie cookie = WebUtils.getCookie(request, SocialSignInAdapter.AUTH_TOKEN_COOKIE_NAME);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setDomain(".computoser.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    cookie = WebUtils.getCookie(request, SocialSignInAdapter.AUTH_TOKEN_SERIES_COOKIE_NAME);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setDomain(".computoser.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    return "redirect:/";
}
 
Example 7
@Test
public void cleanupAfterIncludeWithRemove() throws ServletException, IOException {
	MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
	MockHttpServletResponse response = new MockHttpServletResponse();

	request.setAttribute("test1", "value1");
	request.setAttribute("test2", "value2");
	WebApplicationContext wac = new StaticWebApplicationContext();
	request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

	request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/form.do");
	simpleDispatcherServlet.service(request, response);

	assertEquals("value1", request.getAttribute("test1"));
	assertEquals("value2", request.getAttribute("test2"));
	assertEquals(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE));
	assertNull(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
	assertNull(request.getAttribute("command"));
}
 
Example 8
Source Project: spring-analysis-note   Source File: SessionLocaleResolver.java    License: MIT License 6 votes vote down vote up
@Override
public LocaleContext resolveLocaleContext(final HttpServletRequest request) {
	return new TimeZoneAwareLocaleContext() {
		@Override
		public Locale getLocale() {
			Locale locale = (Locale) WebUtils.getSessionAttribute(request, localeAttributeName);
			if (locale == null) {
				locale = determineDefaultLocale(request);
			}
			return locale;
		}
		@Override
		@Nullable
		public TimeZone getTimeZone() {
			TimeZone timeZone = (TimeZone) WebUtils.getSessionAttribute(request, timeZoneAttributeName);
			if (timeZone == null) {
				timeZone = determineDefaultTimeZone(request);
			}
			return timeZone;
		}
	};
}
 
Example 9
@Test
public void withIncompleteInitialization() throws Exception {
	HttpServletRequest request = mock(HttpServletRequest.class);
	given(request.getCharacterEncoding()).willReturn(null);
	given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
	given(request.getAttribute(filteredName(CharacterEncodingFilter.class.getName()))).willReturn(null);

	MockHttpServletResponse response = new MockHttpServletResponse();

	FilterChain filterChain = mock(FilterChain.class);

	CharacterEncodingFilter filter = new CharacterEncodingFilter(ENCODING);
	filter.doFilter(request, response, filterChain);

	verify(request).setCharacterEncoding(ENCODING);
	verify(request).setAttribute(filteredName(CharacterEncodingFilter.class.getName()), Boolean.TRUE);
	verify(request).removeAttribute(filteredName(CharacterEncodingFilter.class.getName()));
	verify(filterChain).doFilter(request, response);
}
 
Example 10
Source Project: spring4-understanding   Source File: AbstractController.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws Exception {

	// Delegate to WebContentGenerator for checking and preparing.
	checkRequest(request);
	prepareResponse(response);

	// Execute handleRequestInternal in synchronized block if required.
	if (this.synchronizeOnSession) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			Object mutex = WebUtils.getSessionMutex(session);
			synchronized (mutex) {
				return handleRequestInternal(request, response);
			}
		}
	}

	return handleRequestInternal(request, response);
}
 
Example 11
@Test
public void setForceEncodingOnRequestOnly() throws Exception {
	HttpServletRequest request = mock(HttpServletRequest.class);
	request.setCharacterEncoding(ENCODING);
	given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
	given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);

	HttpServletResponse response = mock(HttpServletResponse.class);
	FilterChain filterChain = mock(FilterChain.class);

	CharacterEncodingFilter filter = new CharacterEncodingFilter(ENCODING, true, false);
	filter.init(new MockFilterConfig(FILTER_NAME));
	filter.doFilter(request, response, filterChain);

	verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
	verify(request).removeAttribute(filteredName(FILTER_NAME));
	verify(request, times(2)).setCharacterEncoding(ENCODING);
	verify(response, never()).setCharacterEncoding(ENCODING);
	verify(filterChain).doFilter(request, response);
}
 
Example 12
Source Project: spring-analysis-note   Source File: CookieLocaleResolverTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testResolveLocaleContextWithInvalidLocaleOnErrorDispatch() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addPreferredLocale(Locale.GERMAN);
	request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, new ServletException());
	Cookie cookie = new Cookie("LanguageKoekje", "++ GMT+1");
	request.setCookies(cookie);

	CookieLocaleResolver resolver = new CookieLocaleResolver();
	resolver.setDefaultTimeZone(TimeZone.getTimeZone("GMT+2"));
	resolver.setCookieName("LanguageKoekje");
	LocaleContext loc = resolver.resolveLocaleContext(request);
	assertEquals(Locale.GERMAN, loc.getLocale());
	assertTrue(loc instanceof TimeZoneAwareLocaleContext);
	assertEquals(TimeZone.getTimeZone("GMT+2"), ((TimeZoneAwareLocaleContext) loc).getTimeZone());
}
 
Example 13
Source Project: spring-analysis-note   Source File: AbstractSockJsService.java    License: MIT License 6 votes vote down vote up
protected boolean checkOrigin(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods)
		throws IOException {

	if (WebUtils.isSameOrigin(request)) {
		return true;
	}

	if (!WebUtils.isValidOrigin(request, this.allowedOrigins)) {
		if (logger.isWarnEnabled()) {
			logger.warn("Origin header value '" + request.getHeaders().getOrigin() + "' not allowed.");
		}
		response.setStatusCode(HttpStatus.FORBIDDEN);
		return false;
	}

	return true;
}
 
Example 14
Source Project: spring4-understanding   Source File: CookieThemeResolver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String resolveThemeName(HttpServletRequest request) {
	// Check request for preparsed or preset theme.
	String themeName = (String) request.getAttribute(THEME_REQUEST_ATTRIBUTE_NAME);
	if (themeName != null) {
		return themeName;
	}

	// Retrieve cookie value from request.
	Cookie cookie = WebUtils.getCookie(request, getCookieName());
	if (cookie != null) {
		String value = cookie.getValue();
		if (StringUtils.hasText(value)) {
			themeName = value;
		}
	}

	// Fall back to default theme.
	if (themeName == null) {
		themeName = getDefaultThemeName();
	}
	request.setAttribute(THEME_REQUEST_ATTRIBUTE_NAME, themeName);
	return themeName;
}
 
Example 15
Source Project: java-technology-stack   Source File: HtmlEscapeTagTests.java    License: MIT License 6 votes vote down vote up
@Test
public void htmlEscapeTagWithContextParamFalse() throws JspException {
	PageContext pc = createPageContext();
	MockServletContext sc = (MockServletContext) pc.getServletContext();
	HtmlEscapeTag tag = new HtmlEscapeTag();
	tag.setPageContext(pc);
	tag.doStartTag();

	sc.addInitParameter(WebUtils.HTML_ESCAPE_CONTEXT_PARAM, "false");
	assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape());
	tag.setDefaultHtmlEscape(true);
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape());
	tag.setDefaultHtmlEscape(false);
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape());
}
 
Example 16
Source Project: java-technology-stack   Source File: DispatcherServletTests.java    License: MIT License 6 votes vote down vote up
@Test
public void noCleanupAfterInclude() throws ServletException, IOException {
	MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
	MockHttpServletResponse response = new MockHttpServletResponse();

	request.setAttribute("test1", "value1");
	request.setAttribute("test2", "value2");
	WebApplicationContext wac = new StaticWebApplicationContext();
	request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	TestBean command = new TestBean();
	request.setAttribute("command", command);

	request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/form.do");
	simpleDispatcherServlet.setCleanupAfterInclude(false);
	simpleDispatcherServlet.service(request, response);

	assertEquals("value1", request.getAttribute("test1"));
	assertEquals("value2", request.getAttribute("test2"));
	assertSame(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE));
}
 
Example 17
Source Project: java-technology-stack   Source File: FlashMapManagerTests.java    License: MIT License 6 votes vote down vote up
@Test // SPR-15505
public void retrieveAndUpdateMatchByOriginatingPathAndQueryString() {
	FlashMap flashMap = new FlashMap();
	flashMap.put("key", "value");
	flashMap.setTargetRequestPath("/accounts");
	flashMap.addTargetRequestParam("a", "b");

	this.flashMapManager.setFlashMaps(Collections.singletonList(flashMap));

	this.request.setAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE, "/accounts");
	this.request.setAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE, "a=b");
	this.request.setRequestURI("/mvc/accounts");
	this.request.setQueryString("x=y");
	FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response);

	assertEquals(flashMap, inputFlashMap);
	assertEquals("Input FlashMap should have been removed", 0, this.flashMapManager.getFlashMaps().size());
}
 
Example 18
/**
 * Encodes a string path suing the  httpServletRequest Character Encoding
 * @param pathSegment
 * @param httpServletRequest
 * @return
 */
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 19
Source Project: java-technology-stack   Source File: SessionLocaleResolver.java    License: MIT License 5 votes vote down vote up
@Override
public void setLocaleContext(HttpServletRequest request, @Nullable HttpServletResponse response,
		@Nullable LocaleContext localeContext) {

	Locale locale = null;
	TimeZone timeZone = null;
	if (localeContext != null) {
		locale = localeContext.getLocale();
		if (localeContext instanceof TimeZoneAwareLocaleContext) {
			timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone();
		}
	}
	WebUtils.setSessionAttribute(request, this.localeAttributeName, locale);
	WebUtils.setSessionAttribute(request, this.timeZoneAttributeName, timeZone);
}
 
Example 20
public static HttpServletResponse wrapIfNecessary(HttpServletResponse response,
		HttpStatus redirectStatus) {

	RelativeRedirectResponseWrapper wrapper =
			WebUtils.getNativeResponse(response, RelativeRedirectResponseWrapper.class);

	return (wrapper != null ? response :
			new RelativeRedirectResponseWrapper(response, redirectStatus));
}
 
Example 21
Source Project: spring4-understanding   Source File: MockServletContext.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@code MockServletContext} using the supplied resource base
 * path and resource loader.
 * <p>Registers a {@link MockRequestDispatcher} for the Servlet named
 * {@literal 'default'}.
 * @param resourceBasePath the root directory of the WAR (should not end with a slash)
 * @param resourceLoader the ResourceLoader to use (or null for the default)
 * @see #registerNamedDispatcher
 */
public MockServletContext(String resourceBasePath, ResourceLoader resourceLoader) {
	this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
	this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");

	// Use JVM temp dir as ServletContext temp dir.
	String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
	if (tempDir != null) {
		this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
	}

	registerNamedDispatcher(this.defaultServletName, new MockRequestDispatcher(this.defaultServletName));
}
 
Example 22
@Override
protected ModelAndView handleInternal(HttpServletRequest request,
		HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
	// 注释 10. 调用适配器方法
	ModelAndView mav;
	checkRequest(request);

	// Execute invokeHandlerMethod in synchronized block if required.
	// 判断 synchronizeOnSession 是否开启,开启的话,同一个 session 的请求将会串行执行
	if (this.synchronizeOnSession) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			Object mutex = WebUtils.getSessionMutex(session);
			synchronized (mutex) {
				mav = invokeHandlerMethod(request, response, handlerMethod);
			}
		}
		else {
			// No HttpSession available -> no mutex necessary
			mav = invokeHandlerMethod(request, response, handlerMethod);
		}
	}
	else {
		// No synchronization on session demanded at all...
		// 执行适配中真正的方法
		mav = invokeHandlerMethod(request, response, handlerMethod);
	}

	if (!response.containsHeader(HEADER_CACHE_CONTROL)) {
		if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
			applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);
		}
		else {
			prepareResponse(response);
		}
	}

	return mav;
}
 
Example 23
private Map<String, MultiValueMap<String, String>> extractMatrixVariables(
		HttpServletRequest request, Map<String, String> uriVariables) {

	Map<String, MultiValueMap<String, String>> result = new LinkedHashMap<>();
	uriVariables.forEach((uriVarKey, uriVarValue) -> {

		int equalsIndex = uriVarValue.indexOf('=');
		if (equalsIndex == -1) {
			return;
		}

		int semicolonIndex = uriVarValue.indexOf(';');
		if (semicolonIndex != -1 && semicolonIndex != 0) {
			uriVariables.put(uriVarKey, uriVarValue.substring(0, semicolonIndex));
		}

		String matrixVariables;
		if (semicolonIndex == -1 || semicolonIndex == 0 || equalsIndex < semicolonIndex) {
			matrixVariables = uriVarValue;
		}
		else {
			matrixVariables = uriVarValue.substring(semicolonIndex + 1);
		}

		MultiValueMap<String, String> vars = WebUtils.parseMatrixVariables(matrixVariables);
		result.put(uriVarKey, getUrlPathHelper().decodeMatrixVariables(request, vars));
	});
	return result;
}
 
Example 24
Source Project: spring-analysis-note   Source File: AbstractController.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws Exception {

	if (HttpMethod.OPTIONS.matches(request.getMethod())) {
		response.setHeader("Allow", getAllowHeader());
		return null;
	}

	// Delegate to WebContentGenerator for checking and preparing.
	checkRequest(request);
	prepareResponse(response);

	// Execute handleRequestInternal in synchronized block if required.
	if (this.synchronizeOnSession) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			Object mutex = WebUtils.getSessionMutex(session);
			synchronized (mutex) {
				return handleRequestInternal(request, response);
			}
		}
	}

	return handleRequestInternal(request, response);
}
 
Example 25
private static MultipartHttpServletRequest asMultipartRequest(HttpServletRequest request) {
	MultipartHttpServletRequest unwrapped = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
	if (unwrapped != null) {
		return unwrapped;
	}
	else if (ClassUtils.hasMethod(HttpServletRequest.class, "getParts")) {
		// Servlet 3.0 available ..
		return new StandardMultipartHttpServletRequest(request);
	}
	throw new IllegalArgumentException("Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
}
 
Example 26
Source Project: lams   Source File: DispatcherServlet.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convert the request into a multipart request, and make multipart resolver available.
 * <p>If no multipart resolver is set, simply use the existing request.
 * @param request current HTTP request
 * @return the processed request (multipart wrapper if necessary)
 * @see MultipartResolver#resolveMultipart
 */
protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {
	if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
		if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) != null) {
			logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " +
					"this typically results from an additional MultipartFilter in web.xml");
		}
		else if (hasMultipartException(request) ) {
			logger.debug("Multipart resolution failed for current request before - " +
					"skipping re-resolution for undisturbed error rendering");
		}
		else {
			try {
				return this.multipartResolver.resolveMultipart(request);
			}
			catch (MultipartException ex) {
				if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null) {
					logger.debug("Multipart resolution failed for error dispatch", ex);
					// Keep processing error dispatch with regular request handle below
				}
				else {
					throw ex;
				}
			}
		}
	}
	// If not returned before: return original request.
	return request;
}
 
Example 27
Source Project: java-technology-stack   Source File: RequestLoggingFilterTests.java    License: MIT License 5 votes vote down vote up
@Test
public void payloadMaxLength() throws Exception {
	filter.setIncludePayload(true);
	filter.setMaxPayloadLength(3);

	final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] requestBody = "Hello World".getBytes("UTF-8");
	request.setContent(requestBody);

	FilterChain filterChain = new FilterChain() {
		@Override
		public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
				throws IOException, ServletException {
			((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
			byte[] buf = FileCopyUtils.copyToByteArray(filterRequest.getInputStream());
			assertArrayEquals(requestBody, buf);
			ContentCachingRequestWrapper wrapper =
					WebUtils.getNativeRequest(filterRequest, ContentCachingRequestWrapper.class);
			assertArrayEquals("Hel".getBytes("UTF-8"), wrapper.getContentAsByteArray());
		}
	};

	filter.doFilter(request, response, filterChain);

	assertNotNull(filter.afterRequestMessage);
	assertTrue(filter.afterRequestMessage.contains("Hel"));
	assertFalse(filter.afterRequestMessage.contains("Hello World"));
}
 
Example 28
@Test
public void contentTypeHeader() {
	String contentType = "test/plain";
	response.addHeader("Content-Type", contentType);
	assertEquals(contentType, response.getContentType());
	assertEquals(contentType, response.getHeader("Content-Type"));
	assertEquals(WebUtils.DEFAULT_CHARACTER_ENCODING, response.getCharacterEncoding());

	response = new MockHttpServletResponse();
	response.setHeader("Content-Type", contentType);
	assertEquals(contentType, response.getContentType());
	assertEquals(contentType, response.getHeader("Content-Type"));
	assertEquals(WebUtils.DEFAULT_CHARACTER_ENCODING, response.getCharacterEncoding());
}
 
Example 29
@Test
public void withServletContextAndFilter() throws Exception {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(new MockServletContext());
	wac.registerSingleton("filterMultipartResolver", MockCommonsMultipartResolver.class, new MutablePropertyValues());
	wac.getServletContext().setAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File("mytemp"));
	wac.refresh();
	wac.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	CommonsMultipartResolver resolver = new CommonsMultipartResolver(wac.getServletContext());
	assertTrue(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp"));

	MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
	filterConfig.addInitParameter("class", "notWritable");
	filterConfig.addInitParameter("unknownParam", "someValue");
	final MultipartFilter filter = new MultipartFilter();
	filter.init(filterConfig);

	final List<MultipartFile> files = new ArrayList<MultipartFile>();
	final FilterChain filterChain = new FilterChain() {
		@Override
		public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
			MultipartHttpServletRequest request = (MultipartHttpServletRequest) servletRequest;
			files.addAll(request.getFileMap().values());
		}
	};

	FilterChain filterChain2 = new PassThroughFilterChain(filter, filterChain);

	MockHttpServletRequest originalRequest = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	originalRequest.setMethod("POST");
	originalRequest.setContentType("multipart/form-data");
	originalRequest.addHeader("Content-type", "multipart/form-data");
	filter.doFilter(originalRequest, response, filterChain2);

	CommonsMultipartFile file1 = (CommonsMultipartFile) files.get(0);
	CommonsMultipartFile file2 = (CommonsMultipartFile) files.get(1);
	assertTrue(((MockFileItem) file1.getFileItem()).deleted);
	assertTrue(((MockFileItem) file2.getFileItem()).deleted);
}
 
Example 30
Source Project: spring4-understanding   Source File: PortletUtilsTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSessionMutexWithExistingSessionMutexReturnsTheExistingSessionMutex() throws Exception {
	MockPortletSession session = new MockPortletSession();
	Object expectSessionMutex = new Object();
	session.setAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE, expectSessionMutex, PortletSession.APPLICATION_SCOPE);
	Object actualSessionMutex = PortletUtils.getSessionMutex(session);
	assertNotNull("PortletUtils.getSessionMutex(..) must never return a null mutex", actualSessionMutex);
	assertSame("PortletUtils.getSessionMutex(..) must return the bound mutex attribute if a mutex has been bound as a Session attribute beforehand",
			expectSessionMutex, actualSessionMutex);
}