HttpHeaders.java 18.5 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;
18 19

import java.net.URI;
20
import java.nio.charset.Charset;
A
Arjen Poutsma 已提交
21 22
import java.text.ParseException;
import java.text.SimpleDateFormat;
23 24 25
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
A
Arjen Poutsma 已提交
26
import java.util.Date;
27
import java.util.EnumSet;
28
import java.util.Iterator;
29
import java.util.LinkedHashMap;
30 31
import java.util.LinkedList;
import java.util.List;
32
import java.util.Locale;
33 34
import java.util.Map;
import java.util.Set;
A
Arjen Poutsma 已提交
35
import java.util.TimeZone;
36 37

import org.springframework.util.Assert;
38
import org.springframework.util.LinkedCaseInsensitiveMap;
A
Arjen Poutsma 已提交
39
import org.springframework.util.MultiValueMap;
40 41 42 43 44 45
import org.springframework.util.StringUtils;

/**
 * Represents HTTP request and response headers, mapping string header names to list of string values.
 *
 * <p>In addition to the normal methods defined by {@link Map}, this class offers the following convenience methods:
46 47 48 49 50
 * <ul>
 * <li>{@link #getFirst(String)} returns the first value associated with a given header name</li>
 * <li>{@link #add(String, String)} adds a header value to the list of values for a header name</li>
 * <li>{@link #set(String, String)} sets the header value to a single string value</li>
 * </ul>
51 52 53 54 55 56
 *
 * <p>Inspired by {@link com.sun.net.httpserver.Headers}.
 *
 * @author Arjen Poutsma
 * @since 3.0
 */
57
public class HttpHeaders implements MultiValueMap<String, String> {
58

A
Arjen Poutsma 已提交
59
	private static final String ACCEPT = "Accept";
60

A
Arjen Poutsma 已提交
61
	private static final String ACCEPT_CHARSET = "Accept-Charset";
62

A
Arjen Poutsma 已提交
63
	private static final String ALLOW = "Allow";
64

A
Arjen Poutsma 已提交
65 66
	private static final String CACHE_CONTROL = "Cache-Control";

67 68
	private static final String CONTENT_DISPOSITION = "Content-Disposition";

A
Arjen Poutsma 已提交
69
	private static final String CONTENT_LENGTH = "Content-Length";
70

A
Arjen Poutsma 已提交
71
	private static final String CONTENT_TYPE = "Content-Type";
72

A
Arjen Poutsma 已提交
73 74 75 76 77 78
	private static final String DATE = "Date";

	private static final String ETAG = "ETag";

	private static final String EXPIRES = "Expires";

A
Arjen Poutsma 已提交
79 80
	private static final String IF_MODIFIED_SINCE = "If-Modified-Since";

A
Arjen Poutsma 已提交
81 82 83 84 85 86
	private static final String IF_NONE_MATCH = "If-None-Match";

	private static final String LAST_MODIFIED = "Last-Modified";

	private static final String LOCATION = "Location";

A
Arjen Poutsma 已提交
87 88
	private static final String PRAGMA = "Pragma";

A
Arjen Poutsma 已提交
89 90 91 92 93 94 95 96

	private static final String[] DATE_FORMATS = new String[] {
		"EEE, dd MMM yyyy HH:mm:ss zzz",
        "EEE, dd-MMM-yy HH:mm:ss zzz",
        "EEE MMM dd HH:mm:ss yyyy"
	};

	private static TimeZone GMT = TimeZone.getTimeZone("GMT");
97

98 99
	private final Map<String, List<String>> headers;

100

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
	/**
	 * Private constructor that can create read-only {@code HttpHeader} instances.
	 */
	private HttpHeaders(Map<String, List<String>> headers, boolean readOnly) {
		Assert.notNull(headers, "'headers' must not be null");
		if (readOnly) {
			Map<String, List<String>> map =
					new LinkedCaseInsensitiveMap<List<String>>(headers.size(), Locale.ENGLISH);
			for (Entry<String, List<String>> entry : headers.entrySet()) {
				List<String> values = Collections.unmodifiableList(entry.getValue());
				map.put(entry.getKey(), values);
			}
			this.headers = Collections.unmodifiableMap(map);
		}
		else {
			this.headers = headers;
		}
	}
119

120 121 122 123 124 125
	/**
	 * Constructs a new instance of the {@code HttpHeaders} object.
	 */
	public HttpHeaders() {
		this(new LinkedCaseInsensitiveMap<List<String>>(8, Locale.ENGLISH), false);
	}
126

127 128 129 130 131 132
	/**
	 * Returns {@code HttpHeaders} object that can only be read, not written to.
	 */
	public static HttpHeaders readOnlyHttpHeaders(HttpHeaders headers) {
		return new HttpHeaders(headers, true);
	}
133 134

	/**
A
Arjen Poutsma 已提交
135
	 * Set the list of acceptable {@linkplain MediaType media types}, as specified by the {@code Accept} header.
136 137 138 139 140
	 * @param acceptableMediaTypes the acceptable media types
	 */
	public void setAccept(List<MediaType> acceptableMediaTypes) {
		set(ACCEPT, MediaType.toString(acceptableMediaTypes));
	}
141 142

	/**
A
Arjen Poutsma 已提交
143
	 * Return the list of acceptable {@linkplain MediaType media types}, as specified by the {@code Accept} header.
144
	 * <p>Returns an empty list when the acceptable media types are unspecified.
145 146 147 148
	 * @return the acceptable media types
	 */
	public List<MediaType> getAccept() {
		String value = getFirst(ACCEPT);
149
		return (value != null ? MediaType.parseMediaTypes(value) : Collections.<MediaType>emptyList());
150 151 152
	}

	/**
A
Arjen Poutsma 已提交
153
	 * Set the list of acceptable {@linkplain Charset charsets}, as specified by the {@code Accept-Charset} header.
154
	 * @param acceptableCharsets the acceptable charsets
155
	 */
156 157 158 159 160 161 162 163 164 165
	public void setAcceptCharset(List<Charset> acceptableCharsets) {
		StringBuilder builder = new StringBuilder();
		for (Iterator<Charset> iterator = acceptableCharsets.iterator(); iterator.hasNext();) {
			Charset charset = iterator.next();
			builder.append(charset.name().toLowerCase(Locale.ENGLISH));
			if (iterator.hasNext()) {
				builder.append(", ");
			}
		}
		set(ACCEPT_CHARSET, builder.toString());
166 167
	}

168
	/**
A
Arjen Poutsma 已提交
169
	 * Return the list of acceptable {@linkplain Charset charsets}, as specified by the {@code Accept-Charset}
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
	 * header.
	 * @return the acceptable charsets
	 */
	public List<Charset> getAcceptCharset() {
		List<Charset> result = new ArrayList<Charset>();
		String value = getFirst(ACCEPT_CHARSET);
		if (value != null) {
			String[] tokens = value.split(",\\s*");
			for (String token : tokens) {
				int paramIdx = token.indexOf(';');
				if (paramIdx == -1) {
					result.add(Charset.forName(token));
				}
				else {
					result.add(Charset.forName(token.substring(0, paramIdx)));
				}
			}
		}
		return result;
	}

	/**
A
Arjen Poutsma 已提交
192
	 * Set the set of allowed {@link HttpMethod HTTP methods}, as specified by the {@code Allow} header.
193
	 * @param allowedMethods the allowed methods
194
	 */
195 196
	public void setAllow(Set<HttpMethod> allowedMethods) {
		set(ALLOW, StringUtils.collectionToCommaDelimitedString(allowedMethods));
197 198
	}

199
	/**
A
Arjen Poutsma 已提交
200
	 * Return the set of allowed {@link HttpMethod HTTP methods}, as specified by the {@code Allow} header.
201
	 * <p>Returns an empty set when the allowed methods are unspecified.
202 203
	 * @return the allowed methods
	 */
204
	public Set<HttpMethod> getAllow() {
205 206 207 208 209 210 211 212 213 214 215 216 217 218
		String value = getFirst(ALLOW);
		if (value != null) {
			List<HttpMethod> allowedMethod = new ArrayList<HttpMethod>(5);
			String[] tokens = value.split(",\\s*");
			for (String token : tokens) {
				allowedMethod.add(HttpMethod.valueOf(token));
			}
			return EnumSet.copyOf(allowedMethod);
		}
		else {
			return EnumSet.noneOf(HttpMethod.class);
		}
	}

A
Arjen Poutsma 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
	/**
	 * Sets the (new) value of the {@code Cache-Control} header.
	 * @param cacheControl the value of the header
	 */
	public void setCacheControl(String cacheControl) {
		set(CACHE_CONTROL, cacheControl);
	}

	/**
	 * Returns the value of the {@code Cache-Control} header.
	 * @return the value of the header
	 */
	public String getCacheControl() {
		return getFirst(CACHE_CONTROL);
	}

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
	/**
	 * Sets the (new) value of the {@code Content-Disposition} header for {@code form-data}.
	 * @param name the control name
	 * @param filename the filename, may be {@code null}
	 */
	public void setContentDispositionFormData(String name, String filename) {
		Assert.notNull(name, "'name' must not be null");
		StringBuilder builder = new StringBuilder("form-data; name=\"");
		builder.append(name).append('\"');
		if (filename != null) {
			builder.append("; filename=\"");
			builder.append(filename).append('\"');
		}
		set(CONTENT_DISPOSITION, builder.toString());
	}

251
	/**
A
Arjen Poutsma 已提交
252
	 * Set the length of the body in bytes, as specified by the {@code Content-Length} header.
253
	 * @param contentLength the content length
254
	 */
255 256
	public void setContentLength(long contentLength) {
		set(CONTENT_LENGTH, Long.toString(contentLength));
257 258 259
	}

	/**
A
Arjen Poutsma 已提交
260
	 * Return the length of the body in bytes, as specified by the {@code Content-Length} header.
261
	 * <p>Returns -1 when the content-length is unknown.
262 263 264 265
	 * @return the content length
	 */
	public long getContentLength() {
		String value = getFirst(CONTENT_LENGTH);
266
		return (value != null ? Long.parseLong(value) : -1);
267 268 269
	}

	/**
A
Arjen Poutsma 已提交
270
	 * Set the {@linkplain MediaType media type} of the body, as specified by the {@code Content-Type} header.
271
	 * @param mediaType the media type
272
	 */
273 274 275 276
	public void setContentType(MediaType mediaType) {
		Assert.isTrue(!mediaType.isWildcardType(), "'Content-Type' cannot contain wildcard type '*'");
		Assert.isTrue(!mediaType.isWildcardSubtype(), "'Content-Type' cannot contain wildcard subtype '*'");
		set(CONTENT_TYPE, mediaType.toString());
277 278 279
	}

	/**
A
Arjen Poutsma 已提交
280 281
	 * Return the {@linkplain MediaType media type} of the body, as specified by the {@code Content-Type} header.
	 * <p>Returns {@code null} when the content-type is unknown.
282 283 284 285
	 * @return the content type
	 */
	public MediaType getContentType() {
		String value = getFirst(CONTENT_TYPE);
286
		return (value != null ? MediaType.parseMediaType(value) : null);
287 288 289
	}

	/**
A
Arjen Poutsma 已提交
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 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
	 * Sets the date and time at which the message was created, as specified by the {@code Date} header.
	 * <p>The date should be specified as the number of milliseconds since January 1, 1970 GMT.
	 * @param date the date
	 */
	public void setDate(long date) {
		setDate(DATE, date);
	}

	/**
	 * Returns the date and time at which the message was created, as specified by the {@code Date} header.
	 * <p>The date is returned as the number of milliseconds since January 1, 1970 GMT. Returns -1 when the date is unknown.
	 * @return the creation date/time
	 * @throws IllegalArgumentException if the value can't be converted to a date
	 */
	public long getDate() {
		return getFirstDate(DATE);
	}

	/**
	 * Sets the (new) entity tag of the body, as specified by the {@code ETag} header.
	 * @param eTag the new entity tag
	 */
	public void setETag(String eTag) {
		set(ETAG, quote(eTag));
	}

	/**
	 * Returns the entity tag of the body, as specified by the {@code ETag} header.
	 * @return the entity tag
	 */
	public String getETag() {
		return unquote(getFirst(ETAG));
	}

	/**
	 * Sets the date and time at which the message is no longer valid, as specified by the {@code Expires} header.
	 * <p>The date should be specified as the number of milliseconds since January 1, 1970 GMT.
	 * @param expires the new expires header value
	 */
	public void setExpires(long expires) {
		setDate(EXPIRES, expires);
	}

	/**
	 * Returns the date and time at which the message is no longer valid, as specified by the {@code Expires} header.
	 * <p>The date is returned as the number of milliseconds since January 1, 1970 GMT. Returns -1 when the date is unknown.
	 * @return the expires value
	 */
	public long getExpires() {
		return getFirstDate(EXPIRES);
	}

A
Arjen Poutsma 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
	/**
	 * Sets the (new) value of the {@code If-Modified-Since} header.
	 * <p>The date should be specified as the number of milliseconds since January 1, 1970 GMT.
	 * @param ifModifiedSince the new value of the header
	 */
	public void setIfModifiedSince(long ifModifiedSince) {
		setDate(IF_MODIFIED_SINCE, ifModifiedSince);
	}

	/**
	 * Returns the value of the {@code IfModifiedSince} header.
	 * <p>The date is returned as the number of milliseconds since January 1, 1970 GMT. Returns -1 when the date is unknown.
	 * @return the header value
	 */
	public long getIfNotModifiedSince() {
		return getFirstDate(IF_MODIFIED_SINCE);
	}

A
Arjen Poutsma 已提交
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 409 410 411 412 413 414 415 416 417 418 419 420
	/**
	 * Sets the (new) value of the {@code If-None-Match} header.
	 * @param ifNoneMatch the new value of the header
	 */
	public void setIfNoneMatch(String ifNoneMatch) {
		set(IF_NONE_MATCH, quote(ifNoneMatch));
	}

	/**
	 * Sets the (new) values of the {@code If-None-Match} header.
	 * @param ifNoneMatchList the new value of the header
	 */
	public void setIfNoneMatch(List<String> ifNoneMatchList) {
		StringBuilder builder = new StringBuilder();
		for (Iterator<String> iterator = ifNoneMatchList.iterator(); iterator.hasNext();) {
			String ifNoneMatch = iterator.next();
			builder.append(quote(ifNoneMatch));
			if (iterator.hasNext()) {
				builder.append(", ");
			}
		}
		set(IF_NONE_MATCH, builder.toString());
	}

	/**
	 * Returns the value of the {@code If-None-Match} header.
	 * @return the header value
	 */
	public List<String> getIfNoneMatch() {
		List<String> result = new ArrayList<String>();

		String value = getFirst(IF_NONE_MATCH);
		if (value != null) {
			String[] tokens = value.split(",\\s*");
			for (String token : tokens) {
				result.add(unquote(token));
			}
		}
		return result;
	}

	/**
	 * Sets the time the resource was last changed, as specified by the {@code Last-Modified} header.
	 * <p>The date should be specified as the number of milliseconds since January 1, 1970 GMT.
	 * @param lastModified the last modified date
	 */
	public void setLastModified(long lastModified) {
		setDate(LAST_MODIFIED, lastModified);
	}

	/**
	 * Returns the time the resource was last changed, as specified by the {@code Last-Modified} header.
	 * <p>The date is returned as the number of milliseconds since January 1, 1970 GMT. Returns -1 when the date is unknown.
	 * @return the last modified date
	 */
	public long getLastModified() {
		return getFirstDate(LAST_MODIFIED);
	}

	/**
	 * Set the (new) location of a resource, as specified by the {@code Location} header.
421
	 * @param location the location
422
	 */
423 424
	public void setLocation(URI location) {
		set(LOCATION, location.toASCIIString());
425 426 427
	}

	/**
A
Arjen Poutsma 已提交
428 429
	 * Return the (new) location of a resource, as specified by the {@code Location} header.
	 * <p>Returns {@code null} when the location is unknown.
430 431 432 433
	 * @return the location
	 */
	public URI getLocation() {
		String value = getFirst(LOCATION);
434
		return (value != null ? URI.create(value) : null);
435 436
	}

A
Arjen Poutsma 已提交
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
	/**
	 * Sets the (new) value of the {@code Pragma} header.
	 * @param pragma the value of the header
	 */
	public void setPragma(String pragma) {
		set(PRAGMA, pragma);
	}

	/**
	 * Returns the value of the {@code Pragma} header.
	 * @return the value of the header
	 */
	public String getPragma() {
		return getFirst(PRAGMA);
	}

A
Arjen Poutsma 已提交
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
	// Utility methods

	private String quote(String s) {
		Assert.notNull(s);
		if (!s.startsWith("\"")) {
			s = "\"" + s;
		}
		if (!s.endsWith("\"")) {
			s = s + "\"";
		}
		return s;
	}

	private String unquote(String s) {
		if (s == null) {
			return null;
		}
		if (s.startsWith("\"")) {
			s = s.substring(1);
		}
		if (s.endsWith("\"")) {
			s = s.substring(0, s.length() - 1);
		}
		return s;
	}


	private long getFirstDate(String headerName) {
		String headerValue = getFirst(headerName);
		if (headerValue == null) {
			return -1;
		}
		for (String dateFormat : DATE_FORMATS) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
			simpleDateFormat.setTimeZone(GMT);
			try {
				return simpleDateFormat.parse(headerValue).getTime();
			}
			catch (ParseException e) {
				// ignore
			}
		}
		throw new IllegalArgumentException("Cannot parse date value \"" + headerValue +
				"\" for \"" + headerName + "\" header");
	}

	private void setDate(String headerName, long date) {
500
		SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMATS[0], Locale.US);
A
Arjen Poutsma 已提交
501 502 503
		dateFormat.setTimeZone(GMT);
		set(headerName, dateFormat.format(new Date(date)));
	}
504

505
	// Single string methods
506 507

	/**
508
	 * Return the first header value for the given header name, if any.
509
	 * @param headerName the header name
A
Arjen Poutsma 已提交
510
	 * @return the first header value; or {@code null}
511 512 513 514 515 516 517
	 */
	public String getFirst(String headerName) {
		List<String> headerValues = headers.get(headerName);
		return headerValues != null ? headerValues.get(0) : null;
	}

	/**
518
	 * Add the given, single header value under the given name.
519 520 521 522 523 524 525 526 527 528
	 * @param headerName  the header name
	 * @param headerValue the header value
	 * @throws UnsupportedOperationException if adding headers is not supported
	 * @see #put(String, List)
	 * @see #set(String, String)
	 */
	public void add(String headerName, String headerValue) {
		List<String> headerValues = headers.get(headerName);
		if (headerValues == null) {
			headerValues = new LinkedList<String>();
529
			this.headers.put(headerName, headerValues);
530 531 532 533 534
		}
		headerValues.add(headerValue);
	}

	/**
535
	 * Set the given, single header value under the given name.
536 537 538 539 540 541 542 543 544 545 546 547
	 * @param headerName  the header name
	 * @param headerValue the header value
	 * @throws UnsupportedOperationException if adding headers is not supported
	 * @see #put(String, List)
	 * @see #add(String, String)
	 */
	public void set(String headerName, String headerValue) {
		List<String> headerValues = new LinkedList<String>();
		headerValues.add(headerValue);
		headers.put(headerName, headerValues);
	}

548 549 550 551 552 553 554 555 556 557 558 559 560
	public void setAll(Map<String, String> values) {
		for (Entry<String, String> entry : values.entrySet()) {
			set(entry.getKey(), entry.getValue());
		}
	}

	public Map<String, String> toSingleValueMap() {
		LinkedHashMap<String, String> singleValueMap = new LinkedHashMap<String,String>(this.headers.size());
		for (Entry<String, List<String>> entry : headers.entrySet()) {
			singleValueMap.put(entry.getKey(), entry.getValue().get(0));
		}
		return singleValueMap;
	}
561 562

	// Map implementation
563 564

	public int size() {
565
		return this.headers.size();
566 567 568
	}

	public boolean isEmpty() {
569
		return this.headers.isEmpty();
570 571 572
	}

	public boolean containsKey(Object key) {
573
		return this.headers.containsKey(key);
574 575 576
	}

	public boolean containsValue(Object value) {
577
		return this.headers.containsValue(value);
578 579 580
	}

	public List<String> get(Object key) {
581
		return this.headers.get(key);
582 583 584
	}

	public List<String> put(String key, List<String> value) {
585
		return this.headers.put(key, value);
586 587 588
	}

	public List<String> remove(Object key) {
589
		return this.headers.remove(key);
590 591 592
	}

	public void putAll(Map<? extends String, ? extends List<String>> m) {
593
		this.headers.putAll(m);
594 595 596
	}

	public void clear() {
597
		this.headers.clear();
598 599 600
	}

	public Set<String> keySet() {
601
		return this.headers.keySet();
602 603 604
	}

	public Collection<List<String>> values() {
605
		return this.headers.values();
606 607 608
	}

	public Set<Entry<String, List<String>>> entrySet() {
609
		return this.headers.entrySet();
610 611
	}

612

613
	@Override
614 615
	public boolean equals(Object other) {
		if (this == other) {
616 617
			return true;
		}
618 619
		if (!(other instanceof HttpHeaders)) {
			return false;
620
		}
621 622 623 624 625 626 627
		HttpHeaders otherHeaders = (HttpHeaders) other;
		return this.headers.equals(otherHeaders.headers);
	}

	@Override
	public int hashCode() {
		return this.headers.hashCode();
628 629 630 631
	}

	@Override
	public String toString() {
632
		return this.headers.toString();
633
	}
634

635
}