DefaultServerResponseBuilder.java 11.9 KB
Newer Older
A
Arjen Poutsma 已提交
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
/*
 * Copyright 2002-2019 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.web.servlet.function;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

A
Arjen Poutsma 已提交
40
import org.springframework.core.ParameterizedTypeReference;
A
Arjen Poutsma 已提交
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
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * Default {@link ServerResponse.BodyBuilder} implementation.
 * @author Arjen Poutsma
 * @since 5.2
 */
class DefaultServerResponseBuilder implements ServerResponse.BodyBuilder {

	private final int statusCode;

	private final HttpHeaders headers = new HttpHeaders();

	private final MultiValueMap<String, Cookie> cookies = new LinkedMultiValueMap<>();


	public DefaultServerResponseBuilder(ServerResponse other) {
		Assert.notNull(other, "ServerResponse must not be null");
		this.statusCode = (other instanceof AbstractServerResponse ?
				((AbstractServerResponse) other).statusCode : other.statusCode().value());
		this.headers.addAll(other.headers());
	}

	public DefaultServerResponseBuilder(HttpStatus status) {
		Assert.notNull(status, "HttpStatus must not be null");
		this.statusCode = status.value();
	}

	public DefaultServerResponseBuilder(int statusCode) {
		this.statusCode = statusCode;
	}

	@Override
	public ServerResponse.BodyBuilder header(String headerName, String... headerValues) {
		for (String headerValue : headerValues) {
			this.headers.add(headerName, headerValue);
		}
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder headers(Consumer<HttpHeaders> headersConsumer) {
		headersConsumer.accept(this.headers);
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder cookie(Cookie cookie) {
		Assert.notNull(cookie, "Cookie must not be null");
		this.cookies.add(cookie.getName(), cookie);
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder cookies(Consumer<MultiValueMap<String, Cookie>> cookiesConsumer) {
		cookiesConsumer.accept(this.cookies);
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder allow(HttpMethod... allowedMethods) {
		this.headers.setAllow(new LinkedHashSet<>(Arrays.asList(allowedMethods)));
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder allow(Set<HttpMethod> allowedMethods) {
		this.headers.setAllow(allowedMethods);
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder contentLength(long contentLength) {
		this.headers.setContentLength(contentLength);
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder contentType(MediaType contentType) {
		this.headers.setContentType(contentType);
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder eTag(String etag) {
		if (!etag.startsWith("\"") && !etag.startsWith("W/\"")) {
			etag = "\"" + etag;
		}
		if (!etag.endsWith("\"")) {
			etag = etag + "\"";
		}
		this.headers.setETag(etag);
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder lastModified(ZonedDateTime lastModified) {
		this.headers.setLastModified(lastModified);
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder lastModified(Instant lastModified) {
		this.headers.setLastModified(lastModified);
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder location(URI location) {
		this.headers.setLocation(location);
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder cacheControl(CacheControl cacheControl) {
		this.headers.setCacheControl(cacheControl);
		return this;
	}

	@Override
	public ServerResponse.BodyBuilder varyBy(String... requestHeaders) {
		this.headers.setVary(Arrays.asList(requestHeaders));
		return this;
	}

	@Override
	public ServerResponse build() {
		return build((request, response) -> null);
	}

	@Override
	public ServerResponse build(
			BiFunction<HttpServletRequest, HttpServletResponse, ModelAndView> writeFunction) {
		return new WriterFunctionResponse(this.statusCode, this.headers, this.cookies, writeFunction);
	}

	@Override
	public ServerResponse body(Object body) {
		return DefaultEntityResponseBuilder.fromObject(body)
				.headers(this.headers)
				.status(this.statusCode)
				.build();
	}

	@Override
A
Arjen Poutsma 已提交
197 198
	public <T> ServerResponse body(T body, ParameterizedTypeReference<T> bodyType) {
		return DefaultEntityResponseBuilder.fromObject(body, bodyType)
A
Arjen Poutsma 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
				.headers(this.headers)
				.status(this.statusCode)
				.build();
	}

	@Override
	public ServerResponse render(String name, Object... modelAttributes) {
		return new DefaultRenderingResponseBuilder(name)
				.headers(this.headers)
				.status(this.statusCode)
				.modelAttributes(modelAttributes)
				.build();
	}

	@Override
	public ServerResponse render(String name, Map<String, ?> model) {
		return new DefaultRenderingResponseBuilder(name)
				.headers(this.headers)
				.status(this.statusCode)
				.modelAttributes(model)
				.build();
	}


	/**
	 * Abstract base class for {@link ServerResponse} implementations.
	 */
	abstract static class AbstractServerResponse implements ServerResponse {

		private static final Set<HttpMethod> SAFE_METHODS =	EnumSet.of(HttpMethod.GET, HttpMethod.HEAD);

		final int statusCode;

		private final HttpHeaders headers;

		private final MultiValueMap<String, Cookie> cookies;

		private final List<ErrorHandler<?>> errorHandlers = new ArrayList<>();


		protected AbstractServerResponse(
				int statusCode, HttpHeaders headers, MultiValueMap<String, Cookie> cookies) {

			this.statusCode = statusCode;
			this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
			this.cookies =
					CollectionUtils.unmodifiableMultiValueMap(new LinkedMultiValueMap<>(cookies));
		}

		protected <T extends ServerResponse> void addErrorHandler(Predicate<Throwable> predicate,
				BiFunction<Throwable, ServerRequest, T> errorHandler) {

			Assert.notNull(predicate, "Predicate must not be null");
			Assert.notNull(errorHandler, "ErrorHandler must not be null");
			this.errorHandlers.add(new ErrorHandler<>(predicate, errorHandler));
		}


		@Override
		public final HttpStatus statusCode() {
			return HttpStatus.valueOf(this.statusCode);
		}

		@Override
		public final HttpHeaders headers() {
			return this.headers;
		}

		@Override
		public MultiValueMap<String, Cookie> cookies() {
			return this.cookies;
		}

		@Override
		public ModelAndView writeTo(HttpServletRequest request, HttpServletResponse response,
				Context context) throws ServletException, IOException {

			try {
				writeStatusAndHeaders(response);

				long lastModified = headers().getLastModified();
				ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
				HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
				if (SAFE_METHODS.contains(httpMethod) &&
						servletWebRequest.checkNotModified(headers().getETag(), lastModified)) {
					return null;
				}
				else {
					return writeToInternal(request, response, context);
				}
A
Arjen Poutsma 已提交
289 290 291
			}
			catch (Throwable throwable) {
				return handleError(throwable, request, response, context);
A
Arjen Poutsma 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 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 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
			}
		}

		private void writeStatusAndHeaders(HttpServletResponse response) {
			response.setStatus(this.statusCode);
			writeHeaders(response);
			writeCookies(response);
		}

		private void writeHeaders(HttpServletResponse servletResponse) {
			this.headers.forEach((headerName, headerValues) -> {
				for (String headerValue : headerValues) {
					servletResponse.addHeader(headerName, headerValue);
				}
			});
			// HttpServletResponse exposes some headers as properties: we should include those if not already present
			if (servletResponse.getContentType() == null && this.headers.getContentType() != null) {
				servletResponse.setContentType(this.headers.getContentType().toString());
			}
			if (servletResponse.getCharacterEncoding() == null &&
					this.headers.getContentType() != null &&
					this.headers.getContentType().getCharset() != null) {
				servletResponse
						.setCharacterEncoding(this.headers.getContentType().getCharset().name());
			}
		}

		private void writeCookies(HttpServletResponse servletResponse) {
			this.cookies.values().stream()
					.flatMap(Collection::stream)
					.forEach(servletResponse::addCookie);
		}

		@Nullable
		protected abstract ModelAndView writeToInternal(HttpServletRequest request,
				HttpServletResponse response, Context context)
		throws ServletException, IOException;

		@Nullable
		protected ModelAndView handleError(Throwable t, HttpServletRequest servletRequest,
				HttpServletResponse servletResponse, Context context) {

			return this.errorHandlers.stream()
					.filter(errorHandler -> errorHandler.test(t))
					.findFirst()
					.map(errorHandler -> {
						ServerRequest serverRequest =
								(ServerRequest) servletRequest
										.getAttribute(RouterFunctions.REQUEST_ATTRIBUTE);
						ServerResponse serverResponse = errorHandler.handle(t, serverRequest);
						try {
							return serverResponse.writeTo(servletRequest, servletResponse, context);
						}
						catch (ServletException ex) {
							throw new RuntimeException(ex);
						}
						catch (IOException ex) {
							throw new UncheckedIOException(ex);
						}
					})
					.orElseThrow(() -> new RuntimeException(t));
		}


		private static class ErrorHandler<T extends ServerResponse> {

			private final Predicate<Throwable> predicate;

			private final BiFunction<Throwable, ServerRequest, T>
					responseProvider;

			public ErrorHandler(Predicate<Throwable> predicate,
					BiFunction<Throwable, ServerRequest, T> responseProvider) {
				Assert.notNull(predicate, "Predicate must not be null");
				Assert.notNull(responseProvider, "ResponseProvider must not be null");
				this.predicate = predicate;
				this.responseProvider = responseProvider;
			}

			public boolean test(Throwable t) {
				return this.predicate.test(t);
			}

			public T handle(Throwable t, ServerRequest serverRequest) {
				return this.responseProvider.apply(t, serverRequest);
			}
		}


	}


	private static class WriterFunctionResponse extends AbstractServerResponse {

		private final BiFunction<HttpServletRequest, HttpServletResponse, ModelAndView> writeFunction;


		public WriterFunctionResponse(int statusCode, HttpHeaders headers,
				MultiValueMap<String, Cookie> cookies,
				BiFunction<HttpServletRequest, HttpServletResponse, ModelAndView> writeFunction) {
			super(statusCode, headers, cookies);
			Assert.notNull(writeFunction, "WriteFunction must not be null");
			this.writeFunction = writeFunction;
		}

		@Override
		protected ModelAndView writeToInternal(HttpServletRequest request,
				HttpServletResponse response, Context context) {
			return this.writeFunction.apply(request, response);
		}
	}





}