ServletServerHttpResponse.java 2.4 KB
Newer Older
1
/*
2
 * Copyright 2002-2010 the original author or authors.
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.http.server;
18 19 20 21 22 23 24

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

25 26
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
27
import org.springframework.util.Assert;
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

/**
 * {@link ServerHttpResponse} implementation that is based on a {@link HttpServletResponse}.
 *
 * @author Arjen Poutsma
 * @since 3.0
 */
public class ServletServerHttpResponse implements ServerHttpResponse {

	private final HttpServletResponse servletResponse;

	private final HttpHeaders headers = new HttpHeaders();

	private boolean headersWritten = false;

43

44
	/**
45
	 * Construct a new instance of the ServletServerHttpResponse based on the given {@link HttpServletResponse}.
46 47 48 49 50 51 52
	 * @param servletResponse the HTTP Servlet response
	 */
	public ServletServerHttpResponse(HttpServletResponse servletResponse) {
		Assert.notNull(servletResponse, "'servletResponse' must not be null");
		this.servletResponse = servletResponse;
	}

53

54
	public void setStatusCode(HttpStatus status) {
55
		this.servletResponse.setStatus(status.value());
56 57 58
	}

	public HttpHeaders getHeaders() {
59
		return headersWritten ? HttpHeaders.readOnlyHttpHeaders(headers) : this.headers;
60 61 62 63
	}

	public OutputStream getBody() throws IOException {
		writeHeaders();
64 65 66 67 68
		return this.servletResponse.getOutputStream();
	}

	public void close() {
		writeHeaders();
69 70 71
	}

	private void writeHeaders() {
72 73
		if (!this.headersWritten) {
			for (Map.Entry<String, List<String>> entry : this.headers.entrySet()) {
74 75
				String headerName = entry.getKey();
				for (String headerValue : entry.getValue()) {
76
					this.servletResponse.addHeader(headerName, headerValue);
77 78
				}
			}
79
			this.headersWritten = true;
80 81 82 83
		}
	}

}