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; 014 015import static org.apache.juneau.common.internal.StringUtils.*; 016import static org.apache.juneau.internal.CollectionUtils.*; 017 018import java.util.*; 019import java.util.function.*; 020 021import org.apache.http.*; 022import org.apache.http.message.*; 023import org.apache.juneau.annotation.*; 024import org.apache.juneau.common.internal.*; 025import org.apache.juneau.internal.*; 026 027/** 028 * A parsed <c>Accept</c> or similar header value. 029 * 030 * <p> 031 * The returned media ranges are sorted such that the most acceptable media is available at ordinal position 032 * <js>'0'</js>, and the least acceptable at position n-1. 033 * 034 * <p> 035 * The syntax expected to be found in the referenced <c>value</c> complies with the syntax described in 036 * RFC2616, Section 14.1, as described below: 037 * <p class='bcode'> 038 * Accept = "Accept" ":" 039 * #( media-range [ accept-params ] ) 040 * 041 * media-range = ( "*\/*" 042 * | ( type "/" "*" ) 043 * | ( type "/" subtype ) 044 * ) *( ";" parameter ) 045 * accept-params = ";" "q" "=" qvalue *( accept-extension ) 046 * accept-extension = ";" token [ "=" ( token | quoted-string ) ] 047 * </p> 048 * 049 * <h5 class='section'>See Also:</h5><ul> 050 * <li class='link'><a class="doclink" href="../../../index.html#juneau-rest-common">juneau-rest-common</a> 051 * <li class='extlink'><a class="doclink" href="https://www.w3.org/Protocols/rfc2616/rfc2616.html">Hypertext Transfer Protocol -- HTTP/1.1</a> 052 * </ul> 053 */ 054@BeanIgnore 055public class MediaRanges { 056 057 //----------------------------------------------------------------------------------------------------------------- 058 // Static 059 //----------------------------------------------------------------------------------------------------------------- 060 061 /** Represents an empty media ranges object. */ 062 public static final MediaRanges EMPTY = new MediaRanges(""); 063 064 private static final Cache<String,MediaRanges> CACHE = Cache.of(String.class, MediaRanges.class).build(); 065 066 private final MediaRange[] ranges; 067 private final String string; 068 069 /** 070 * Returns a parsed <c>Accept</c> header value. 071 * 072 * @param value The raw <c>Accept</c> header value. 073 * @return A parsed <c>Accept</c> header value. 074 */ 075 public static MediaRanges of(String value) { 076 return isEmpty(value) ? EMPTY : CACHE.get(value, ()->new MediaRanges(value)); 077 } 078 079 //----------------------------------------------------------------------------------------------------------------- 080 // Instance 081 //----------------------------------------------------------------------------------------------------------------- 082 083 /** 084 * Constructor. 085 * 086 * @param value The <c>Accept</c> header value. 087 */ 088 public MediaRanges(String value) { 089 this(parse(value)); 090 } 091 092 /** 093 * Constructor. 094 * 095 * @param e The parsed header value. 096 */ 097 public MediaRanges(HeaderElement[] e) { 098 099 ranges = new MediaRange[e.length]; 100 for (int i = 0; i < e.length; i++) 101 ranges[i] = new MediaRange(e[i]); 102 Arrays.sort(ranges, RANGE_COMPARATOR); 103 104 this.string = ranges.length == 1 ? ranges[0].toString() : StringUtils.join(ranges, ','); 105 } 106 107 /** 108 * Compares two MediaRanges for equality. 109 * 110 * <p> 111 * The values are first compared according to <c>qValue</c> values. 112 * Should those values be equal, the <c>type</c> is then lexicographically compared (case-insensitive) in 113 * ascending order, with the <js>"*"</js> type demoted last in that order. 114 * <c>MediaRanges</c> with the same type but different sub-types are compared - a more specific subtype is 115 * promoted over the 'wildcard' subtype. 116 * <c>MediaRanges</c> with the same types but with extensions are promoted over those same types with no 117 * extensions. 118 */ 119 private static final Comparator<MediaRange> RANGE_COMPARATOR = new Comparator<>() { 120 @Override 121 public int compare(MediaRange o1, MediaRange o2) { 122 // Compare q-values. 123 int qCompare = Float.compare(o2.getQValue(), o1.getQValue()); 124 if (qCompare != 0) 125 return qCompare; 126 127 // Compare media-types. 128 // Note that '*' comes alphabetically before letters, so just do a reverse-alphabetical comparison. 129 int i = o2.toString().compareTo(o1.toString()); 130 return i; 131 } 132 }; 133 134 /** 135 * Given a list of media types, returns the best match for this <c>Accept</c> header. 136 * 137 * <p> 138 * Note that fuzzy matching is allowed on the media types where the <c>Accept</c> header may 139 * contain additional subtype parts. 140 * <br>For example, given identical q-values and an <c>Accept</c> value of <js>"text/json+activity"</js>, 141 * the media type <js>"text/json"</js> will match if <js>"text/json+activity"</js> or <js>"text/activity+json"</js> 142 * isn't found. 143 * <br>The purpose for this is to allow serializers to match when artifacts such as <c>id</c> properties are 144 * present in the header. 145 * 146 * <p> 147 * See <a class="doclink" href="https://www.w3.org/TR/activitypub/#retrieving-objects">ActivityPub / Retrieving Objects</a> 148 * 149 * @param mediaTypes The media types to match against. 150 * @return The index into the array of the best match, or <c>-1</c> if no suitable matches could be found. 151 */ 152 public int match(List<? extends MediaType> mediaTypes) { 153 if (string.isEmpty() || mediaTypes == null) 154 return -1; 155 156 int matchQuant = 0, matchIndex = -1; 157 float q = 0f; 158 159 // Media ranges are ordered by 'q'. 160 // So we only need to search until we've found a match. 161 for (MediaRange mr : ranges) { 162 float q2 = mr.getQValue(); 163 164 if (q2 < q || q2 == 0) 165 break; 166 167 for (int i = 0; i < mediaTypes.size(); i++) { 168 MediaType mt = mediaTypes.get(i); 169 int matchQuant2 = mr.match(mt, false); 170 171 if (matchQuant2 > matchQuant) { 172 matchIndex = i; 173 matchQuant = matchQuant2; 174 q = q2; 175 } 176 } 177 } 178 179 return matchIndex; 180 } 181 182 /** 183 * Returns the {@link MediaRange} at the specified index. 184 * 185 * @param index The index position of the media range. 186 * @return The {@link MediaRange} at the specified index or <jk>null</jk> if the index is out of range. 187 */ 188 public MediaRange getRange(int index) { 189 if (index < 0 || index >= ranges.length) 190 return null; 191 return ranges[index]; 192 } 193 194 /** 195 * Convenience method for searching through all of the subtypes of all the media ranges in this header for the 196 * presence of a subtype fragment. 197 * 198 * <p> 199 * For example, given the header <js>"text/json+activity"</js>, calling 200 * <code>hasSubtypePart(<js>"activity"</js>)</code> returns <jk>true</jk>. 201 * 202 * @param part The media type subtype fragment. 203 * @return <jk>true</jk> if subtype fragment exists. 204 */ 205 public boolean hasSubtypePart(String part) { 206 207 for (MediaRange mr : ranges) 208 if (mr.getQValue() > 0 && mr.getSubTypes().indexOf(part) >= 0) 209 return true; 210 211 return false; 212 } 213 214 /** 215 * Returns the media ranges that make up this object. 216 * 217 * @return The media ranges that make up this object. 218 */ 219 public List<MediaRange> toList() { 220 return ulist(ranges); 221 } 222 223 /** 224 * Performs an action on the media ranges that make up this object. 225 * 226 * @param action The action to perform. 227 * @return This object. 228 */ 229 public MediaRanges forEachRange(Consumer<MediaRange> action) { 230 for (MediaRange r : ranges) 231 action.accept(r); 232 return this; 233 } 234 235 private static HeaderElement[] parse(String value) { 236 return BasicHeaderValueParser.parseElements(emptyIfNull(trim(value)), null); 237 } 238 239 @Override /* Object */ 240 public String toString() { 241 return string; 242 } 243}