Path: blob/master/src/java.net.http/share/classes/java/net/http/HttpHeaders.java
41159 views
/*1* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.net.http;2627import java.util.ArrayList;28import java.util.List;29import java.util.Locale;30import java.util.Map;31import java.util.Optional;32import java.util.OptionalLong;33import java.util.TreeMap;34import java.util.TreeSet;35import java.util.function.BiPredicate;36import static java.lang.String.CASE_INSENSITIVE_ORDER;37import static java.util.Collections.unmodifiableMap;38import static java.util.Objects.requireNonNull;3940/**41* A read-only view of a set of HTTP headers.42*43* <p> An {@code HttpHeaders} is not typically created directly, but rather44* returned from an {@link HttpRequest#headers() HttpRequest} or an45* {@link HttpResponse#headers() HttpResponse}. Specific HTTP headers can be46* set for a {@linkplain HttpRequest request} through one of the request47* builder's {@link HttpRequest.Builder#header(String, String) headers} methods.48*49* <p> The methods of this class ( that accept a String header name ), and the50* {@code Map} returned by the {@link #map() map} method, operate without regard51* to case when retrieving the header value(s).52*53* <p> An HTTP header name may appear more than once in the HTTP protocol. As54* such, headers are represented as a name and a list of values. Each occurrence55* of a header value is added verbatim, to the appropriate header name list,56* without interpreting its value. In particular, {@code HttpHeaders} does not57* perform any splitting or joining of comma separated header value strings. The58* order of elements in a header value list is preserved when {@link59* HttpRequest.Builder#header(String, String) building} a request. For60* responses, the order of elements in a header value list is the order in which61* they were received. The {@code Map} returned by the {@code map} method,62* however, does not provide any guarantee with regard to the ordering of its63* entries.64*65* <p> {@code HttpHeaders} instances are immutable.66*67* @since 1168*/69public final class HttpHeaders {7071/**72* Returns an {@link Optional} containing the first header string value of73* the given named (and possibly multi-valued) header. If the header is not74* present, then the returned {@code Optional} is empty.75*76* @param name the header name77* @return an {@code Optional<String>} containing the first named header78* string value, if present79*/80public Optional<String> firstValue(String name) {81return allValues(name).stream().findFirst();82}8384/**85* Returns an {@link OptionalLong} containing the first header string value86* of the named header field. If the header is not present, then the87* Optional is empty. If the header is present but contains a value that88* does not parse as a {@code Long} value, then an exception is thrown.89*90* @param name the header name91* @return an {@code OptionalLong}92* @throws NumberFormatException if a value is found, but does not parse as93* a Long94*/95public OptionalLong firstValueAsLong(String name) {96return allValues(name).stream().mapToLong(Long::valueOf).findFirst();97}9899/**100* Returns an unmodifiable List of all of the header string values of the101* given named header. Always returns a List, which may be empty if the102* header is not present.103*104* @param name the header name105* @return a List of headers string values106*/107public List<String> allValues(String name) {108requireNonNull(name);109List<String> values = map().get(name);110// Making unmodifiable list out of empty in order to make a list which111// throws UOE unconditionally112return values != null ? values : List.of();113}114115/**116* Returns an unmodifiable multi Map view of this HttpHeaders.117*118* @return the Map119*/120public Map<String,List<String>> map() {121return headers;122}123124/**125* Tests this HTTP headers instance for equality with the given object.126*127* <p> If the given object is not an {@code HttpHeaders} then this128* method returns {@code false}. Two HTTP headers are equal if each129* of their corresponding {@linkplain #map() maps} are equal.130*131* <p> This method satisfies the general contract of the {@link132* Object#equals(Object) Object.equals} method.133*134* @param obj the object to which this object is to be compared135* @return {@code true} if, and only if, the given object is an {@code136* HttpHeaders} that is equal to this HTTP headers137*/138public final boolean equals(Object obj) {139if (!(obj instanceof HttpHeaders))140return false;141HttpHeaders that = (HttpHeaders)obj;142return this.map().equals(that.map());143}144145/**146* Computes a hash code for this HTTP headers instance.147*148* <p> The hash code is based upon the components of the HTTP headers149* {@link #map() map}, and satisfies the general contract of the150* {@link Object#hashCode Object.hashCode} method.151*152* @return the hash-code value for this HTTP headers153*/154public final int hashCode() {155int h = 0;156for (Map.Entry<String, List<String>> e : map().entrySet()) {157h += entryHash(e);158}159return h;160}161162/**163* Returns this HTTP headers as a string.164*165* @return a string describing the HTTP headers166*/167@Override168public String toString() {169StringBuilder sb = new StringBuilder();170sb.append(super.toString()).append(" { ");171sb.append(map());172sb.append(" }");173return sb.toString();174}175176/**177* Returns an HTTP headers from the given map. The given map's key178* represents the header name, and its value the list of string header179* values for that header name.180*181* <p> An HTTP header name may appear more than once in the HTTP protocol.182* Such, <i>multi-valued</i>, headers must be represented by a single entry183* in the given map, whose entry value is a list that represents the184* multiple header string values. Leading and trailing whitespaces are185* removed from all string values retrieved from the given map and its lists186* before processing. Only headers that, after filtering, contain at least187* one, possibly empty string, value will be added to the HTTP headers.188*189* @apiNote The primary purpose of this method is for testing frameworks.190* Per-request headers can be set through one of the {@code HttpRequest}191* {@link HttpRequest.Builder#header(String, String) headers} methods.192*193* @param headerMap the map containing the header names and values194* @param filter a filter that can be used to inspect each195* header-name-and-value pair in the given map to determine if196* it should, or should not, be added to the to the HTTP197* headers198* @return an HTTP headers instance containing the given headers199* @throws NullPointerException if any of: {@code headerMap}, a key or value200* in the given map, or an entry in the map's value list, or201* {@code filter}, is {@code null}202* @throws IllegalArgumentException if the given {@code headerMap} contains203* any two keys that are equal ( without regard to case ); or if the204* given map contains any key whose length, after trimming205* whitespaces, is {@code 0}206*/207public static HttpHeaders of(Map<String,List<String>> headerMap,208BiPredicate<String,String> filter) {209requireNonNull(headerMap);210requireNonNull(filter);211return headersOf(headerMap, filter);212}213214// --215216private static final HttpHeaders NO_HEADERS = new HttpHeaders(Map.of());217218private final Map<String,List<String>> headers;219220private HttpHeaders(Map<String,List<String>> headers) {221this.headers = headers;222}223224private static final int entryHash(Map.Entry<String, List<String>> e) {225String key = e.getKey();226List<String> value = e.getValue();227// we know that by construction key and values can't be null228int keyHash = key.toLowerCase(Locale.ROOT).hashCode();229int valueHash = value.hashCode();230return keyHash ^ valueHash;231}232233// Returns a new HTTP headers after performing a structural copy and filtering.234private static HttpHeaders headersOf(Map<String,List<String>> map,235BiPredicate<String,String> filter) {236TreeMap<String,List<String>> other = new TreeMap<>(CASE_INSENSITIVE_ORDER);237TreeSet<String> notAdded = new TreeSet<>(CASE_INSENSITIVE_ORDER);238ArrayList<String> tempList = new ArrayList<>();239map.forEach((key, value) -> {240String headerName = requireNonNull(key).trim();241if (headerName.isEmpty()) {242throw new IllegalArgumentException("empty key");243}244List<String> headerValues = requireNonNull(value);245headerValues.forEach(headerValue -> {246headerValue = requireNonNull(headerValue).trim();247if (filter.test(headerName, headerValue)) {248tempList.add(headerValue);249}250});251252if (tempList.isEmpty()) {253if (other.containsKey(headerName)254|| notAdded.contains(headerName.toLowerCase(Locale.ROOT)))255throw new IllegalArgumentException("duplicate key: " + headerName);256notAdded.add(headerName.toLowerCase(Locale.ROOT));257} else if (other.put(headerName, List.copyOf(tempList)) != null) {258throw new IllegalArgumentException("duplicate key: " + headerName);259}260tempList.clear();261});262return other.isEmpty() ? NO_HEADERS : new HttpHeaders(unmodifiableMap(other));263}264}265266267