MockHttpServletRequestBuilder.java 25.0 KB
Newer Older
R
Rob Winch 已提交
1
/*
2
 * Copyright 2002-2016 the original author or authors.
R
Rob Winch 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17
package org.springframework.test.web.servlet.request;
R
Rob Winch 已提交
18

19 20 21
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
R
Rossen Stoyanchev 已提交
22
import java.io.UnsupportedEncodingException;
23
import java.net.URI;
24
import java.nio.charset.StandardCharsets;
R
Rob Winch 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;

import org.springframework.beans.Mergeable;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.http.HttpHeaders;
40
import org.springframework.http.HttpInputMessage;
R
Rob Winch 已提交
41 42
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
43
import org.springframework.http.converter.FormHttpMessageConverter;
R
Rob Winch 已提交
44 45 46
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
47
import org.springframework.test.web.servlet.MockMvc;
R
Rob Winch 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ValueConstants;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.FlashMapManager;
import org.springframework.web.servlet.support.SessionFlashMapManager;
import org.springframework.web.util.UriComponentsBuilder;
R
Rossen Stoyanchev 已提交
61
import org.springframework.web.util.UriUtils;
R
Rob Winch 已提交
62 63

/**
J
Juergen Hoeller 已提交
64 65
 * Default builder for {@link MockHttpServletRequest} required as input to perform
 * requests in {@link MockMvc}.
R
Rob Winch 已提交
66
 *
J
Juergen Hoeller 已提交
67
 * <p>Application tests will typically access this builder through the static factory
68
 * methods in {@link MockMvcRequestBuilders}.
J
Juergen Hoeller 已提交
69 70 71
 *
 * <p>Although this class cannot be extended, additional ways to initialize the
 * {@code MockHttpServletRequest} can be plugged in via {@link #with(RequestPostProcessor)}.
R
Rob Winch 已提交
72 73 74
 *
 * @author Rossen Stoyanchev
 * @author Arjen Poutsma
75
 * @author Sam Brannen
76
 * @author Kamill Sokol
77 78
 * @since 3.2
 */
79 80 81
public class MockHttpServletRequestBuilder
		implements ConfigurableSmartRequestBuilder<MockHttpServletRequestBuilder>, Mergeable {

82
	private final String method;
R
Rob Winch 已提交
83

84
	private final URI url;
J
Juergen Hoeller 已提交
85

86
	private final MultiValueMap<String, Object> headers = new LinkedMultiValueMap<>();
R
Rob Winch 已提交
87 88 89 90 91

	private String contentType;

	private byte[] content;

92
	private final MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
R
Rob Winch 已提交
93

94
	private final List<Cookie> cookies = new ArrayList<>();
R
Rob Winch 已提交
95 96 97 98 99 100 101

	private Locale locale;

	private String characterEncoding;

	private Boolean secure;

J
Juergen Hoeller 已提交
102 103
	private Principal principal;

104
	private final Map<String, Object> attributes = new LinkedHashMap<>();
R
Rob Winch 已提交
105 106 107

	private MockHttpSession session;

108
	private final Map<String, Object> sessionAttributes = new LinkedHashMap<>();
R
Rob Winch 已提交
109

110
	private final Map<String, Object> flashAttributes = new LinkedHashMap<>();
R
Rob Winch 已提交
111 112 113 114 115 116 117

	private String contextPath = "";

	private String servletPath = "";

	private String pathInfo = ValueConstants.DEFAULT_NONE;

118
	private final List<RequestPostProcessor> postProcessors = new ArrayList<>();
R
Rob Winch 已提交
119 120 121


	/**
122 123 124 125 126
	 * Package private constructor. To get an instance, use static factory
	 * methods in {@link MockMvcRequestBuilders}.
	 * <p>Although this class cannot be extended, additional ways to initialize
	 * the {@code MockHttpServletRequest} can be plugged in via
	 * {@link #with(RequestPostProcessor)}.
127
	 * @param httpMethod the HTTP method (GET, POST, etc)
128
	 * @param url a URL template; the resulting URL will be encoded
129
	 * @param vars zero or more URI variables
R
Rob Winch 已提交
130
	 */
131
	MockHttpServletRequestBuilder(HttpMethod httpMethod, String url, Object... vars) {
132 133 134 135
		this(httpMethod.name(), UriComponentsBuilder.fromUriString(url).buildAndExpand(vars).encode().toUri());
	}

	/**
136 137
	 * Alternative to {@link #MockHttpServletRequestBuilder(HttpMethod, String, Object...)}
	 * with a pre-built URI.
138
	 * @param httpMethod the HTTP method (GET, POST, etc)
139
	 * @param url the URL
140 141
	 * @since 4.0.3
	 */
142
	MockHttpServletRequestBuilder(HttpMethod httpMethod, URI url) {
143
		this(httpMethod.name(), url);
144 145 146
	}

	/**
147
	 * Alternative constructor for custom HTTP methods.
148 149 150 151 152
	 * @param httpMethod the HTTP method (GET, POST, etc)
	 * @param url the URL
	 * @since 4.3
	 */
	MockHttpServletRequestBuilder(String httpMethod, URI url) {
J
Juergen Hoeller 已提交
153 154
		Assert.notNull(httpMethod, "'httpMethod' is required");
		Assert.notNull(url, "'url' is required");
155
		this.method = httpMethod;
156
		this.url = url;
157 158
	}

J
Juergen Hoeller 已提交
159

R
Rob Winch 已提交
160 161
	/**
	 * Add a request parameter to the {@link MockHttpServletRequest}.
J
Juergen Hoeller 已提交
162
	 * <p>If called more than once, new values get added to existing ones.
R
Rob Winch 已提交
163 164 165 166 167 168 169 170
	 * @param name the parameter name
	 * @param values one or more values
	 */
	public MockHttpServletRequestBuilder param(String name, String... values) {
		addToMultiValueMap(this.parameters, name, values);
		return this;
	}

171
	/**
J
Juergen Hoeller 已提交
172 173 174
	 * Add a map of request parameters to the {@link MockHttpServletRequest},
	 * for example when testing a form submission.
	 * <p>If called more than once, new values get added to existing ones.
175
	 * @param params the parameters to add
J
Juergen Hoeller 已提交
176
	 * @since 4.2.4
177 178 179 180 181 182 183 184 185 186
	 */
	public MockHttpServletRequestBuilder params(MultiValueMap<String, String> params) {
		for (String name : params.keySet()) {
			for (String value : params.get(name)) {
				this.parameters.add(name, value);
			}
		}
		return this;
	}

R
Rob Winch 已提交
187 188 189 190 191 192
	/**
	 * Add a header to the request. Values are always added.
	 * @param name the header name
	 * @param values one or more header values
	 */
	public MockHttpServletRequestBuilder header(String name, Object... values) {
193 194 195 196
		if ("Content-Type".equalsIgnoreCase(name)) {
			List<MediaType> mediaTypes = MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(values));
			this.contentType = MediaType.toString(mediaTypes);
		}
R
Rob Winch 已提交
197 198 199 200 201 202 203 204 205
		addToMultiValueMap(this.headers, name, values);
		return this;
	}

	/**
	 * Add all headers to the request. Values are always added.
	 * @param httpHeaders the headers and values to add
	 */
	public MockHttpServletRequestBuilder headers(HttpHeaders httpHeaders) {
206 207 208 209
		MediaType mediaType = httpHeaders.getContentType();
		if (mediaType != null) {
			this.contentType = mediaType.toString();
		}
R
Rob Winch 已提交
210 211 212 213 214 215 216 217 218
		for (String name : httpHeaders.keySet()) {
			Object[] values = ObjectUtils.toObjectArray(httpHeaders.get(name).toArray());
			addToMultiValueMap(this.headers, name, values);
		}
		return this;
	}

	/**
	 * Set the 'Content-Type' header of the request.
219
	 * @param contentType the content type
R
Rob Winch 已提交
220
	 */
221 222 223 224 225 226 227 228 229 230 231 232 233 234
	public MockHttpServletRequestBuilder contentType(MediaType contentType) {
		Assert.notNull(contentType, "'contentType' must not be null");
		this.contentType = contentType.toString();
		this.headers.set("Content-Type", this.contentType);
		return this;
	}

	/**
	 * Set the 'Content-Type' header of the request.
	 * @param contentType the content type
	 * @since 4.1.2
	 */
	public MockHttpServletRequestBuilder contentType(String contentType) {
		this.contentType = MediaType.parseMediaType(contentType).toString();
R
Rob Winch 已提交
235 236 237 238 239 240 241 242 243
		this.headers.set("Content-Type", this.contentType);
		return this;
	}

	/**
	 * Set the 'Accept' header to the given media type(s).
	 * @param mediaTypes one or more media types
	 */
	public MockHttpServletRequestBuilder accept(MediaType... mediaTypes) {
J
Juergen Hoeller 已提交
244
		Assert.notEmpty(mediaTypes, "'mediaTypes' must not be empty");
R
Rob Winch 已提交
245 246 247 248
		this.headers.set("Accept", MediaType.toString(Arrays.asList(mediaTypes)));
		return this;
	}

249 250 251 252 253
	/**
	 * Set the 'Accept' header to the given media type(s).
	 * @param mediaTypes one or more media types
	 */
	public MockHttpServletRequestBuilder accept(String... mediaTypes) {
J
Juergen Hoeller 已提交
254 255
		Assert.notEmpty(mediaTypes, "'mediaTypes' must not be empty");
		List<MediaType> result = new ArrayList<MediaType>(mediaTypes.length);
256 257 258 259 260 261 262
		for (String mediaType : mediaTypes) {
			result.add(MediaType.parseMediaType(mediaType));
		}
		this.headers.set("Accept", MediaType.toString(result));
		return this;
	}

R
Rob Winch 已提交
263 264 265 266
	/**
	 * Set the request body.
	 * @param content the body content
	 */
R
Rossen Stoyanchev 已提交
267
	public MockHttpServletRequestBuilder content(byte[] content) {
R
Rob Winch 已提交
268 269 270 271
		this.content = content;
		return this;
	}

272 273 274 275 276
	/**
	 * Set the request body as a UTF-8 String.
	 * @param content the body content
	 */
	public MockHttpServletRequestBuilder content(String content) {
277
		this.content = content.getBytes(StandardCharsets.UTF_8);
278 279 280
		return this;
	}

R
Rob Winch 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
	/**
	 * Add the given cookies to the request. Cookies are always added.
	 * @param cookies the cookies to add
	 */
	public MockHttpServletRequestBuilder cookie(Cookie... cookies) {
		Assert.notEmpty(cookies, "'cookies' must not be empty");
		this.cookies.addAll(Arrays.asList(cookies));
		return this;
	}

	/**
	 * Set the locale of the request.
	 * @param locale the locale
	 */
	public MockHttpServletRequestBuilder locale(Locale locale) {
		this.locale = locale;
		return this;
	}

	/**
	 * Set the character encoding of the request.
	 * @param encoding the character encoding
	 */
	public MockHttpServletRequestBuilder characterEncoding(String encoding) {
		this.characterEncoding = encoding;
		return this;
	}

	/**
	 * Set a request attribute.
	 * @param name the attribute name
	 * @param value the attribute value
	 */
	public MockHttpServletRequestBuilder requestAttr(String name, Object value) {
J
Juergen Hoeller 已提交
315
		addToMap(this.attributes, name, value);
R
Rob Winch 已提交
316 317 318 319 320 321 322 323 324
		return this;
	}

	/**
	 * Set a session attribute.
	 * @param name the session attribute name
	 * @param value the session attribute value
	 */
	public MockHttpServletRequestBuilder sessionAttr(String name, Object value) {
J
Juergen Hoeller 已提交
325
		addToMap(this.sessionAttributes, name, value);
R
Rob Winch 已提交
326 327 328 329 330 331 332 333
		return this;
	}

	/**
	 * Set session attributes.
	 * @param sessionAttributes the session attributes
	 */
	public MockHttpServletRequestBuilder sessionAttrs(Map<String, Object> sessionAttributes) {
S
Sam Brannen 已提交
334
		Assert.notEmpty(sessionAttributes, "'sessionAttributes' must not be empty");
R
Rob Winch 已提交
335 336 337 338 339 340 341 342 343 344 345 346
		for (String name : sessionAttributes.keySet()) {
			sessionAttr(name, sessionAttributes.get(name));
		}
		return this;
	}

	/**
	 * Set an "input" flash attribute.
	 * @param name the flash attribute name
	 * @param value the flash attribute value
	 */
	public MockHttpServletRequestBuilder flashAttr(String name, Object value) {
J
Juergen Hoeller 已提交
347
		addToMap(this.flashAttributes, name, value);
R
Rob Winch 已提交
348 349 350 351 352 353 354 355
		return this;
	}

	/**
	 * Set flash attributes.
	 * @param flashAttributes the flash attributes
	 */
	public MockHttpServletRequestBuilder flashAttrs(Map<String, Object> flashAttributes) {
S
Sam Brannen 已提交
356
		Assert.notEmpty(flashAttributes, "'flashAttributes' must not be empty");
R
Rob Winch 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
		for (String name : flashAttributes.keySet()) {
			flashAttr(name, flashAttributes.get(name));
		}
		return this;
	}

	/**
	 * Set the HTTP session to use, possibly re-used across requests.
	 * <p>Individual attributes provided via {@link #sessionAttr(String, Object)}
	 * override the content of the session provided here.
	 * @param session the HTTP session
	 */
	public MockHttpServletRequestBuilder session(MockHttpSession session) {
		Assert.notNull(session, "'session' must not be null");
		this.session = session;
		return this;
	}

	/**
	 * Set the principal of the request.
	 * @param principal the principal
	 */
	public MockHttpServletRequestBuilder principal(Principal principal) {
		Assert.notNull(principal, "'principal' must not be null");
		this.principal = principal;
		return this;
	}

	/**
	 * Specify the portion of the requestURI that represents the context path.
J
Juergen Hoeller 已提交
387
	 * The context path, if specified, must match to the start of the request URI.
R
Rob Winch 已提交
388 389 390 391
	 * <p>In most cases, tests can be written by omitting the context path from
	 * the requestURI. This is because most applications don't actually depend
	 * on the name under which they're deployed. If specified here, the context
	 * path must start with a "/" and must not end with a "/".
J
Juergen Hoeller 已提交
392
	 * @see <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getContextPath%28%29">HttpServletRequest.getContextPath()</a>
R
Rob Winch 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
	 */
	public MockHttpServletRequestBuilder contextPath(String contextPath) {
		if (StringUtils.hasText(contextPath)) {
			Assert.isTrue(contextPath.startsWith("/"), "Context path must start with a '/'");
			Assert.isTrue(!contextPath.endsWith("/"), "Context path must not end with a '/'");
		}
		this.contextPath = (contextPath != null) ? contextPath : "";
		return this;
	}

	/**
	 * Specify the portion of the requestURI that represents the path to which
	 * the Servlet is mapped. This is typically a portion of the requestURI
	 * after the context path.
	 * <p>In most cases, tests can be written by omitting the servlet path from
	 * the requestURI. This is because most applications don't actually depend
	 * on the prefix to which a servlet is mapped. For example if a Servlet is
	 * mapped to {@code "/main/*"}, tests can be written with the requestURI
	 * {@code "/accounts/1"} as opposed to {@code "/main/accounts/1"}.
	 * If specified here, the servletPath must start with a "/" and must not
	 * end with a "/".
J
Juergen Hoeller 已提交
414
	 * @see <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getServletPath%28%29">HttpServletRequest.getServletPath()</a>
R
Rob Winch 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
	 */
	public MockHttpServletRequestBuilder servletPath(String servletPath) {
		if (StringUtils.hasText(servletPath)) {
			Assert.isTrue(servletPath.startsWith("/"), "Servlet path must start with a '/'");
			Assert.isTrue(!servletPath.endsWith("/"), "Servlet path must not end with a '/'");
		}
		this.servletPath = (servletPath != null) ? servletPath : "";
		return this;
	}

	/**
	 * Specify the portion of the requestURI that represents the pathInfo.
	 * <p>If left unspecified (recommended), the pathInfo will be automatically
	 * derived by removing the contextPath and the servletPath from the
	 * requestURI and using any remaining part. If specified here, the pathInfo
	 * must start with a "/".
	 * <p>If specified, the pathInfo will be used as is.
J
Juergen Hoeller 已提交
432
	 * @see <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getPathInfo%28%29">HttpServletRequest.getServletPath()</a>
R
Rob Winch 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
	 */
	public MockHttpServletRequestBuilder pathInfo(String pathInfo) {
		if (StringUtils.hasText(pathInfo)) {
			Assert.isTrue(pathInfo.startsWith("/"), "pathInfo must start with a '/'");
		}
		this.pathInfo = pathInfo;
		return this;
	}

	/**
	 * Set the secure property of the {@link ServletRequest} indicating use of a
	 * secure channel, such as HTTPS.
	 * @param secure whether the request is using a secure channel
	 */
	public MockHttpServletRequestBuilder secure(boolean secure){
		this.secure = secure;
		return this;
	}

	/**
	 * An extension point for further initialization of {@link MockHttpServletRequest}
	 * in ways not built directly into the {@code MockHttpServletRequestBuilder}.
	 * Implementation of this interface can have builder-style methods themselves
	 * and be made accessible through static factory methods.
	 * @param postProcessor a post-processor to add
	 */
459
	@Override
R
Rob Winch 已提交
460 461 462 463 464 465
	public MockHttpServletRequestBuilder with(RequestPostProcessor postProcessor) {
		Assert.notNull(postProcessor, "postProcessor is required");
		this.postProcessors.add(postProcessor);
		return this;
	}

J
Juergen Hoeller 已提交
466

R
Rob Winch 已提交
467 468 469 470
	/**
	 * {@inheritDoc}
	 * @return always returns {@code true}.
	 */
471
	@Override
R
Rob Winch 已提交
472 473 474 475 476 477 478 479 480 481
	public boolean isMergeEnabled() {
		return true;
	}

	/**
	 * Merges the properties of the "parent" RequestBuilder accepting values
	 * only if not already set in "this" instance.
	 * @param parent the parent {@code RequestBuilder} to inherit properties from
	 * @return the result of the merge
	 */
482
	@Override
R
Rob Winch 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
	public Object merge(Object parent) {
		if (parent == null) {
			return this;
		}
		if (!(parent instanceof MockHttpServletRequestBuilder)) {
			throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]");
		}
		MockHttpServletRequestBuilder parentBuilder = (MockHttpServletRequestBuilder) parent;

		for (String headerName : parentBuilder.headers.keySet()) {
			if (!this.headers.containsKey(headerName)) {
				this.headers.put(headerName, parentBuilder.headers.get(headerName));
			}
		}

		if (this.contentType == null) {
			this.contentType = parentBuilder.contentType;
		}
		if (this.content == null) {
			this.content = parentBuilder.content;
		}

		for (String paramName : parentBuilder.parameters.keySet()) {
			if (!this.parameters.containsKey(paramName)) {
				this.parameters.put(paramName, parentBuilder.parameters.get(paramName));
			}
		}
		for (Cookie cookie : parentBuilder.cookies) {
			if (!containsCookie(cookie)) {
				this.cookies.add(cookie);
			}
		}

		if (this.locale == null) {
			this.locale = parentBuilder.locale;
		}
		if (this.characterEncoding == null) {
			this.characterEncoding = parentBuilder.characterEncoding;
		}

J
Juergen Hoeller 已提交
523 524 525
		if (this.secure == null) {
			this.secure = parentBuilder.secure;
		}
R
Rob Winch 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
		if (this.principal == null) {
			this.principal = parentBuilder.principal;
		}

		for (String attributeName : parentBuilder.attributes.keySet()) {
			if (!this.attributes.containsKey(attributeName)) {
				this.attributes.put(attributeName, parentBuilder.attributes.get(attributeName));
			}
		}

		if (this.session == null) {
			this.session = parentBuilder.session;
		}

		for (String sessionAttributeName : parentBuilder.sessionAttributes.keySet()) {
			if (!this.sessionAttributes.containsKey(sessionAttributeName)) {
				this.sessionAttributes.put(sessionAttributeName, parentBuilder.sessionAttributes.get(sessionAttributeName));
			}
		}

		for (String flashAttributeName : parentBuilder.flashAttributes.keySet()) {
			if (!this.flashAttributes.containsKey(flashAttributeName)) {
				this.flashAttributes.put(flashAttributeName, parentBuilder.flashAttributes.get(flashAttributeName));
			}
		}

		if (!StringUtils.hasText(this.contextPath)) {
			this.contextPath = parentBuilder.contextPath;
		}

		if (!StringUtils.hasText(this.servletPath)) {
			this.servletPath = parentBuilder.servletPath;
		}

		if (ValueConstants.DEFAULT_NONE.equals(this.pathInfo)) {
			this.pathInfo = parentBuilder.pathInfo;
		}

564
		this.postProcessors.addAll(0, parentBuilder.postProcessors);
R
Rob Winch 已提交
565 566 567 568 569

		return this;
	}

	private boolean containsCookie(Cookie cookie) {
J
Juergen Hoeller 已提交
570 571
		for (Cookie cookieToCheck : this.cookies) {
			if (ObjectUtils.nullSafeEquals(cookieToCheck.getName(), cookie.getName())) {
R
Rob Winch 已提交
572 573 574 575 576 577 578 579 580
				return true;
			}
		}
		return false;
	}

	/**
	 * Build a {@link MockHttpServletRequest}.
	 */
581
	@Override
R
Rob Winch 已提交
582 583 584
	public final MockHttpServletRequest buildRequest(ServletContext servletContext) {
		MockHttpServletRequest request = createServletRequest(servletContext);

585
		String requestUri = this.url.getRawPath();
R
Rob Winch 已提交
586 587 588
		request.setRequestURI(requestUri);
		updatePathRequestProperties(request, requestUri);

589 590
		if (this.url.getScheme() != null) {
			request.setScheme(this.url.getScheme());
R
Rob Winch 已提交
591
		}
592 593
		if (this.url.getHost() != null) {
			request.setServerName(this.url.getHost());
R
Rob Winch 已提交
594
		}
595 596
		if (this.url.getPort() != -1) {
			request.setServerPort(this.url.getPort());
R
Rob Winch 已提交
597 598
		}

599
		request.setMethod(this.method);
600

R
Rob Winch 已提交
601 602 603 604 605 606
		for (String name : this.headers.keySet()) {
			for (Object value : this.headers.get(name)) {
				request.addHeader(name, value);
			}
		}

607 608
		if (this.url.getRawQuery() != null) {
			request.setQueryString(this.url.getRawQuery());
R
Rossen Stoyanchev 已提交
609
		}
610
		addRequestParams(request, UriComponentsBuilder.fromUri(this.url).build().getQueryParams());
R
Rob Winch 已提交
611 612 613 614 615 616 617 618 619

		for (String name : this.parameters.keySet()) {
			for (String value : this.parameters.get(name)) {
				request.addParameter(name, value);
			}
		}

		request.setContentType(this.contentType);
		request.setContent(this.content);
620 621
		request.setCharacterEncoding(this.characterEncoding);

622 623 624 625 626 627 628
		if (this.content != null && this.contentType != null) {
			MediaType mediaType = MediaType.parseMediaType(this.contentType);
			if (MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType)) {
				addRequestParams(request, parseFormData(mediaType));
			}
		}

629 630 631
		if (!ObjectUtils.isEmpty(this.cookies)) {
			request.setCookies(this.cookies.toArray(new Cookie[this.cookies.size()]));
		}
R
Rob Winch 已提交
632 633 634 635 636 637 638 639

		if (this.locale != null) {
			request.addPreferredLocale(this.locale);
		}

		if (this.secure != null) {
			request.setSecure(this.secure);
		}
640

J
Juergen Hoeller 已提交
641
		request.setUserPrincipal(this.principal);
R
Rob Winch 已提交
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660

		for (String name : this.attributes.keySet()) {
			request.setAttribute(name, this.attributes.get(name));
		}

		// Set session before session and flash attributes
		if (this.session != null) {
			request.setSession(this.session);
		}
		for (String name : this.sessionAttributes.keySet()) {
			request.getSession().setAttribute(name, this.sessionAttributes.get(name));
		}

		FlashMap flashMap = new FlashMap();
		flashMap.putAll(this.flashAttributes);

		FlashMapManager flashMapManager = getFlashMapManager(request);
		flashMapManager.saveOutputFlashMap(flashMap, request, new MockHttpServletResponse());

661 662
		request.setAsyncSupported(true);

R
Rob Winch 已提交
663 664 665 666
		return request;
	}

	/**
667 668
	 * Create a new {@link MockHttpServletRequest} based on the supplied
	 * {@code ServletContext}.
669
	 * <p>Can be overridden in subclasses.
R
Rob Winch 已提交
670 671
	 */
	protected MockHttpServletRequest createServletRequest(ServletContext servletContext) {
672
		return new MockHttpServletRequest(servletContext);
R
Rob Winch 已提交
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
	}

	/**
	 * Update the contextPath, servletPath, and pathInfo of the request.
	 */
	private void updatePathRequestProperties(MockHttpServletRequest request, String requestUri) {
		Assert.isTrue(requestUri.startsWith(this.contextPath),
				"requestURI [" + requestUri + "] does not start with contextPath [" + this.contextPath + "]");
		request.setContextPath(this.contextPath);
		request.setServletPath(this.servletPath);
		if (ValueConstants.DEFAULT_NONE.equals(this.pathInfo)) {
			Assert.isTrue(requestUri.startsWith(this.contextPath + this.servletPath),
					"Invalid servletPath [" + this.servletPath + "] for requestURI [" + requestUri + "]");
			String extraPath = requestUri.substring(this.contextPath.length() + this.servletPath.length());
			this.pathInfo = (StringUtils.hasText(extraPath)) ? extraPath : null;
		}
		request.setPathInfo(this.pathInfo);
	}

692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
	private void addRequestParams(MockHttpServletRequest request, MultiValueMap<String, String> map) {
		try {
			for (Entry<String, List<String>> entry : map.entrySet()) {
				for (String value : entry.getValue()) {
					value = (value != null) ? UriUtils.decode(value, "UTF-8") : null;
					request.addParameter(UriUtils.decode(entry.getKey(), "UTF-8"), value);
				}
			}
		}
		catch (UnsupportedEncodingException ex) {
			// shouldn't happen
		}
	}

	private MultiValueMap<String, String> parseFormData(final MediaType mediaType) {
S
Sam Brannen 已提交
707 708
		MultiValueMap<String, String> map;
		HttpInputMessage message = new HttpInputMessage() {
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
			@Override
			public InputStream getBody() throws IOException {
				return new ByteArrayInputStream(content);
			}

			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers = new HttpHeaders();
				headers.setContentType(mediaType);
				return headers;
			}
		};
		try {
			map = new FormHttpMessageConverter().read(null, message);
		}
		catch (IOException ex) {
S
Sam Brannen 已提交
725
			throw new IllegalStateException("Failed to parse form data in request body", ex);
726 727 728 729
		}
		return map;
	}

R
Rob Winch 已提交
730 731 732 733 734 735 736 737
	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 ex) {
J
Juergen Hoeller 已提交
738
			// ignore
R
Rob Winch 已提交
739 740
		}
		catch (NoSuchBeanDefinitionException ex) {
J
Juergen Hoeller 已提交
741
			// ignore
R
Rob Winch 已提交
742
		}
J
Juergen Hoeller 已提交
743
		return (flashMapManager != null ? flashMapManager : new SessionFlashMapManager());
R
Rob Winch 已提交
744 745
	}

746 747 748 749
	@Override
	public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
		for (RequestPostProcessor postProcessor : this.postProcessors) {
			request = postProcessor.postProcessRequest(request);
750 751
			Assert.state(request != null,
					() -> "Post-processor [" + postProcessor.getClass().getName() + "] returned null");
752 753 754 755
		}
		return request;
	}

J
Juergen Hoeller 已提交
756 757 758 759 760 761 762

	private static void addToMap(Map<String, Object> map, String name, Object value) {
		Assert.hasLength(name, "'name' must not be empty");
		Assert.notNull(value, "'value' must not be null");
		map.put(name, value);
	}

R
Rob Winch 已提交
763 764 765 766 767 768 769 770 771
	private static <T> void addToMultiValueMap(MultiValueMap<String, T> map, String name, T[] values) {
		Assert.hasLength(name, "'name' must not be empty");
		Assert.notEmpty(values, "'values' must not be empty");
		for (T value : values) {
			map.add(name, value);
		}
	}

}