001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.http; 014 015import static org.apache.juneau.http.Constants.*; 016import static org.apache.juneau.internal.CollectionUtils.*; 017import static org.apache.juneau.internal.StringUtils.*; 018 019import java.util.*; 020 021import org.apache.juneau.http.annotation.*; 022import org.apache.juneau.internal.*; 023 024/** 025 * Represents a parsed <l>Accept</l> HTTP request header. 026 * 027 * <p> 028 * Content-Types that are acceptable for the response. 029 * 030 * <h5 class='figure'>Example</h5> 031 * <p class='bcode w800'> 032 * Accept: text/plain 033 * </p> 034 * 035 * <h5 class='topic'>RFC2616 Specification</h5> 036 * 037 * The Accept request-header field can be used to specify certain media types which are acceptable for the response. 038 * Accept headers can be used to indicate that the request is specifically limited to a small set of desired types, as 039 * in the case of a request for an in-line image. 040 * 041 * <p class='bcode w800'> 042 * Accept = "Accept" ": 043 * #( media-range [ accept-params ] ) 044 * 045 * media-range = ( "* /*" 046 * | ( type "/" "*" ) 047 * | ( type "/" subtype ) 048 * ) *( ";" parameter ) 049 * accept-params = ";" "q" "=" qvalue *( accept-extension ) 050 * accept-extension = ";" token [ "=" ( token | quoted-string ) ] 051 * </p> 052 * 053 * <p> 054 * The asterisk "*" character is used to group media types into ranges, with "* /*" indicating all media types and 055 * "type/*" indicating all subtypes of that type. 056 * The media-range MAY include media type parameters that are applicable to that range. 057 * 058 * <p> 059 * Each media-range MAY be followed by one or more accept-params, beginning with the "q" parameter for indicating a 060 * relative quality factor. 061 * The first "q" parameter (if any) separates the media-range parameter(s) from the accept-params. 062 * Quality factors allow the user or user agent to indicate the relative degree of preference for that media-range, 063 * using the qvalue scale from 0 to 1 (section 3.9). 064 * The default value is q=1. 065 * 066 * <p> 067 * Note: Use of the "q" parameter name to separate media type parameters from Accept extension parameters is due to 068 * historical practice. 069 * Although this prevents any media type parameter named "q" from being used with a media range, such an event is 070 * believed to be unlikely given the lack of any "q" parameters in the IANA 071 * media type registry and the rare usage of any media type parameters in Accept. 072 * Future media types are discouraged from registering any parameter named "q". 073 * 074 * <p> 075 * The example 076 * <p class='bcode w800'> 077 * Accept: audio/*; q=0.2, audio/basic 078 * </p> 079 * <p> 080 * SHOULD be interpreted as "I prefer audio/basic, but send me any audio type if it is the best available after an 80% 081 * mark-down in quality." 082 * 083 * <p> 084 * If no Accept header field is present, then it is assumed that the client accepts all media types. 085 * 086 * <p> 087 * If an Accept header field is present, and if the server cannot send a response which is acceptable according to the 088 * combined Accept field value, then the server SHOULD send a 406 (not acceptable) response. 089 * 090 * <p> 091 * A more elaborate example is 092 * <p class='bcode w800'> 093 * Accept: text/plain; q=0.5, text/html, 094 * text/x-dvi; q=0.8, text/x-c 095 * </p> 096 * 097 * <p> 098 * Verbally, this would be interpreted as "text/html and text/x-c are the preferred media types, but if they do not 099 * exist, then send the 100 * text/x-dvi entity, and if that does not exist, send the text/plain entity." 101 * 102 * <p> 103 * Media ranges can be overridden by more specific media ranges or specific media types. 104 * If more than one media range applies to a given type, the most specific reference has precedence. 105 * For example, 106 * <p class='bcode w800'> 107 * Accept: text/ *, text/html, text/html;level=1, * /* 108 * </p> 109 * <p> 110 * have the following precedence: 111 * <ol> 112 * <li>text/html;level=1 113 * <li>text/html 114 * <li>text/* 115 * <li>* /* 116 * </ol> 117 * 118 * <p> 119 * The media type quality factor associated with a given type is determined by finding the media range with the highest 120 * precedence which matches that type. 121 * For example, 122 * <p class='bcode w800'> 123 * Accept: text/*;q=0.3, text/html;q=0.7, text/html;level=1, 124 * text/html;level=2;q=0.4, * /*;q=0.5 125 * </p> 126 * <p> 127 * would cause the following values to be associated: 128 * <p class='bcode w800'> 129 * text/html;level=1 = 1 130 * text/html = 0.7 131 * text/plain = 0.3 132 * image/jpeg = 0.5 133 * text/html;level=2 = 0.4 134 * text/html;level=3 = 0.7 135 * </p> 136 * 137 * <p> 138 * Note: A user agent might be provided with a default set of quality values for certain media ranges. 139 * However, unless the user agent is a closed system which cannot interact with other rendering agents, this default 140 * set ought to be configurable by the user. 141 * 142 * <h5 class='section'>See Also:</h5> 143 * <ul class='doctree'> 144 * <li class='extlink'>{@doc RFC2616} 145 * </ul> 146 */ 147@Header("Accept") 148public final class Accept { 149 150 private static final Cache<String,Accept> cache = new Cache<>(NOCACHE, CACHE_MAX_SIZE); 151 152 /** 153 * Returns a parsed <code>Accept</code> header. 154 * 155 * @param value The <code>Accept</code> header string. 156 * @return The parsed <code>Accept</code> header, or <jk>null</jk> if the string was null. 157 */ 158 public static Accept forString(String value) { 159 if (value == null) 160 return null; 161 Accept a = cache.get(value); 162 if (a == null) 163 a = cache.put(value, new Accept(value)); 164 return a; 165 } 166 167 168 private final MediaTypeRange[] mediaRanges; 169 private final List<MediaTypeRange> mediaRangesList; 170 171 private Accept(String value) { 172 this.mediaRanges = MediaTypeRange.parse(value); 173 this.mediaRangesList = immutableList(mediaRanges); 174 } 175 176 /** 177 * Returns the list of the media ranges that make up this header. 178 * 179 * <p> 180 * The media ranges in the list are sorted by their q-value in descending order. 181 * 182 * @return An unmodifiable list of media ranges. 183 */ 184 public List<MediaTypeRange> asRanges() { 185 return mediaRangesList; 186 } 187 188 /** 189 * Given a list of media types, returns the best match for this <code>Accept</code> header. 190 * 191 * <p> 192 * Note that fuzzy matching is allowed on the media types where the <code>Accept</code> header may 193 * contain additional subtype parts. 194 * <br>For example, given identical q-values and an <code>Accept</code> value of <js>"text/json+activity"</js>, 195 * the media type <js>"text/json"</js> will match if <js>"text/json+activity"</js> or <js>"text/activity+json"</js> 196 * isn't found. 197 * <br>The purpose for this is to allow serializers to match when artifacts such as <code>id</code> properties are 198 * present in the header. 199 * 200 * <p> 201 * See {@doc https://www.w3.org/TR/activitypub/#retrieving-objects ActivityPub / Retrieving Objects} 202 * 203 * @param mediaTypes The media types to match against. 204 * @return The index into the array of the best match, or <code>-1</code> if no suitable matches could be found. 205 */ 206 public int findMatch(MediaType[] mediaTypes) { 207 int matchQuant = 0, matchIndex = -1; 208 float q = 0f; 209 210 // Media ranges are ordered by 'q'. 211 // So we only need to search until we've found a match. 212 for (MediaTypeRange mr : mediaRanges) { 213 float q2 = mr.getQValue(); 214 215 if (q2 < q || q2 == 0) 216 break; 217 218 for (int i = 0; i < mediaTypes.length; i++) { 219 MediaType mt = mediaTypes[i]; 220 int matchQuant2 = mr.getMediaType().match(mt, false); 221 222 if (matchQuant2 > matchQuant) { 223 matchIndex = i; 224 matchQuant = matchQuant2; 225 q = q2; 226 } 227 } 228 } 229 230 return matchIndex; 231 } 232 233 /** 234 * Same as {@link #findMatch(MediaType[])} but matching against media type ranges. 235 * 236 * <p> 237 * Note that the q-types on both the <code>mediaTypeRanges</code> parameter and this header 238 * are taken into account when trying to find the best match. 239 * <br>When both this header and the matching range have q-values, the q-value for the match is the result of multiplying them. 240 * <br>(e.g. Accept=<js>"text/html;q=0.9"</js> and mediaTypeRange=<js>"text/html;q=0.9"</js> ==>, q-value=<code>0.81</code>). 241 * 242 * @param mediaTypeRanges The media type ranges to match against. 243 * @return The index into the array of the best match, or <code>-1</code> if no suitable matches could be found. 244 */ 245 public int findMatch(MediaTypeRange[] mediaTypeRanges) { 246 float matchQuant = 0; 247 int matchIndex = -1; 248 float q = 0f; 249 250 // Media ranges are ordered by 'q'. 251 // So we only need to search until we've found a match. 252 for (MediaTypeRange mr : mediaRanges) { 253 float q2 = mr.getQValue(); 254 255 if (q2 < q || q2 == 0) 256 break; 257 258 for (int i = 0; i < mediaTypeRanges.length; i++) { 259 MediaTypeRange mt = mediaTypeRanges[i]; 260 float matchQuant2 = mr.getMediaType().match(mt.getMediaType(), false) * mt.getQValue(); 261 262 if (matchQuant2 > matchQuant) { 263 matchIndex = i; 264 matchQuant = matchQuant2; 265 q = q2; 266 } 267 } 268 } 269 270 return matchIndex; 271 } 272 273 274 /** 275 * Convenience method for searching through all of the subtypes of all the media ranges in this header for the 276 * presence of a subtype fragment. 277 * 278 * <p> 279 * For example, given the header <js>"text/json+activity"</js>, calling 280 * <code>hasSubtypePart(<js>"activity"</js>)</code> returns <jk>true</jk>. 281 * 282 * @param part The media type subtype fragment. 283 * @return <jk>true</jk> if subtype fragment exists. 284 */ 285 public boolean hasSubtypePart(String part) { 286 287 for (MediaTypeRange mr : this.mediaRanges) 288 if (mr.getQValue() > 0 && mr.getMediaType().getSubTypes().indexOf(part) >= 0) 289 return true; 290 291 return false; 292 } 293 294 @Override /* Object */ 295 public String toString() { 296 return join(mediaRanges, ','); 297 } 298}