summaryrefslogtreecommitdiff
path: root/spring-test/src/main/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnection.java
blob: fd4ef702ba4f37e2b9a341c553ac2a1e5a6d9ef8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/*
 * Copyright 2002-2016 the original author or authors.
 *
 * 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.
 */

package org.springframework.test.web.servlet.htmlunit;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebConnection;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.util.Cookie;

import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.util.Assert;

/**
 * {@code MockMvcWebConnection} enables {@link MockMvc} to transform a
 * {@link WebRequest} into a {@link WebResponse}.
 * <p>This is the core integration with <a href="http://htmlunit.sourceforge.net/">HtmlUnit</a>.
 * <p>Example usage can be seen below.
 *
 * <pre class="code">
 * WebClient webClient = new WebClient();
 * MockMvc mockMvc = ...
 * MockMvcWebConnection webConnection = new MockMvcWebConnection(mockMvc, webClient);
 * webClient.setWebConnection(webConnection);
 *
 * // Use webClient as normal ...
 * </pre>
 *
 * @author Rob Winch
 * @author Sam Brannen
 * @since 4.2
 * @see org.springframework.test.web.servlet.htmlunit.webdriver.WebConnectionHtmlUnitDriver
 */
public final class MockMvcWebConnection implements WebConnection {

	private final Map<String, MockHttpSession> sessions = new HashMap<String, MockHttpSession>();

	private final MockMvc mockMvc;

	private final String contextPath;

	private WebClient webClient;


	/**
	 * Create a new instance that assumes the context path of the application
	 * is {@code ""} (i.e., the root context).
	 * <p>For example, the URL {@code http://localhost/test/this} would use
	 * {@code ""} as the context path.
	 * @param mockMvc the {@code MockMvc} instance to use; never {@code null}
	 * @param webClient the {@link WebClient} to use. never {@code null}
	 */
	public MockMvcWebConnection(MockMvc mockMvc, WebClient webClient) {
		this(mockMvc, webClient, "");
	}

	/**
	 * Create a new instance with the specified context path.
	 * <p>The path may be {@code null} in which case the first path segment
	 * of the URL is turned into the contextPath. Otherwise it must conform
	 * to {@link javax.servlet.http.HttpServletRequest#getContextPath()}
	 * which states that it can be an empty string and otherwise must start
	 * with a "/" character and not end with a "/" character.
	 * @param mockMvc the {@code MockMvc} instance to use; never {@code null}
	 * @param webClient  the {@link WebClient} to use. never {@code null}
	 * @param contextPath the contextPath to use
	 */
	public MockMvcWebConnection(MockMvc mockMvc, WebClient webClient, String contextPath) {
		Assert.notNull(mockMvc, "MockMvc must not be null");
		Assert.notNull(webClient, "WebClient must not be null");
		validateContextPath(contextPath);

		this.webClient = webClient;
		this.mockMvc = mockMvc;
		this.contextPath = contextPath;
	}

	/**
	 * Create a new instance that assumes the context path of the application
	 * is {@code ""} (i.e., the root context).
	 * <p>For example, the URL {@code http://localhost/test/this} would use
	 * {@code ""} as the context path.
	 * @param mockMvc the {@code MockMvc} instance to use; never {@code null}
	 * @deprecated Use {@link #MockMvcWebConnection(MockMvc, WebClient)}
	 */
	@Deprecated
	public MockMvcWebConnection(MockMvc mockMvc) {
		this(mockMvc, "");
	}

	/**
	 * Create a new instance with the specified context path.
	 * <p>The path may be {@code null} in which case the first path segment
	 * of the URL is turned into the contextPath. Otherwise it must conform
	 * to {@link javax.servlet.http.HttpServletRequest#getContextPath()}
	 * which states that it can be an empty string and otherwise must start
	 * with a "/" character and not end with a "/" character.
	 * @param mockMvc the {@code MockMvc} instance to use; never {@code null}
	 * @param contextPath the contextPath to use
	 * @deprecated use {@link #MockMvcWebConnection(MockMvc, WebClient, String)}
	 */
	@Deprecated
	public MockMvcWebConnection(MockMvc mockMvc, String contextPath) {
		this(mockMvc, new WebClient(), contextPath);
	}

	/**
	 * Validate the supplied {@code contextPath}.
	 * <p>If the value is not {@code null}, it must conform to
	 * {@link javax.servlet.http.HttpServletRequest#getContextPath()} which
	 * states that it can be an empty string and otherwise must start with
	 * a "/" character and not end with a "/" character.
	 * @param contextPath the path to validate
	 */
	static void validateContextPath(String contextPath) {
		if (contextPath == null || "".equals(contextPath)) {
			return;
		}
		if (!contextPath.startsWith("/")) {
			throw new IllegalArgumentException("contextPath '" + contextPath + "' must start with '/'.");
		}
		if (contextPath.endsWith("/")) {
			throw new IllegalArgumentException("contextPath '" + contextPath + "' must not end with '/'.");
		}
	}


	public void setWebClient(WebClient webClient) {
		Assert.notNull(webClient, "WebClient must not be null");
		this.webClient = webClient;
	}


	public WebResponse getResponse(WebRequest webRequest) throws IOException {
		long startTime = System.currentTimeMillis();
		HtmlUnitRequestBuilder requestBuilder = new HtmlUnitRequestBuilder(this.sessions, this.webClient, webRequest);
		requestBuilder.setContextPath(this.contextPath);

		MockHttpServletResponse httpServletResponse = getResponse(requestBuilder);
		String forwardedUrl = httpServletResponse.getForwardedUrl();
		while (forwardedUrl != null) {
			requestBuilder.setForwardPostProcessor(new ForwardRequestPostProcessor(forwardedUrl));
			httpServletResponse = getResponse(requestBuilder);
			forwardedUrl = httpServletResponse.getForwardedUrl();
		}
		storeCookies(webRequest, httpServletResponse.getCookies());

		return new MockWebResponseBuilder(startTime, webRequest, httpServletResponse).build();
	}

	private MockHttpServletResponse getResponse(RequestBuilder requestBuilder) throws IOException {
		ResultActions resultActions;
		try {
			resultActions = this.mockMvc.perform(requestBuilder);
		}
		catch (Exception ex) {
			throw new IOException(ex);
		}

		return resultActions.andReturn().getResponse();
	}

	private void storeCookies(WebRequest webRequest, javax.servlet.http.Cookie[] cookies) {
		if (cookies == null) {
			return;
		}
		Date now = new Date();
		CookieManager cookieManager = this.webClient.getCookieManager();
		for (javax.servlet.http.Cookie cookie : cookies) {
			if (cookie.getDomain() == null) {
				cookie.setDomain(webRequest.getUrl().getHost());
			}
			Cookie toManage = MockWebResponseBuilder.createCookie(cookie);
			Date expires = toManage.getExpires();
			if (expires == null || expires.after(now)) {
				cookieManager.addCookie(toManage);
			}
			else {
				cookieManager.removeCookie(toManage);
			}
		}
	}

	@Override
	public void close() {
	}

}