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 = (o1, o2) -> { 120 // Compare q-values. 121 int qCompare = Float.compare(o2.getQValue(), o1.getQValue()); 122 if (qCompare != 0) 123 return qCompare; 124 125 // Compare media-types. 126 // Note that '*' comes alphabetically before letters, so just do a reverse-alphabetical comparison. 127 return o2.toString().compareTo(o1.toString()); 128 }; 129 130 /** 131 * Given a list of media types, returns the best match for this <c>Accept</c> header. 132 * 133 * <p> 134 * Note that fuzzy matching is allowed on the media types where the <c>Accept</c> header may 135 * contain additional subtype parts. 136 * <br>For example, given identical q-values and an <c>Accept</c> value of <js>"text/json+activity"</js>, 137 * the media type <js>"text/json"</js> will match if <js>"text/json+activity"</js> or <js>"text/activity+json"</js> 138 * isn't found. 139 * <br>The purpose for this is to allow serializers to match when artifacts such as <c>id</c> properties are 140 * present in the header. 141 * 142 * <p> 143 * See <a class="doclink" href="https://www.w3.org/TR/activitypub/#retrieving-objects">ActivityPub / Retrieving Objects</a> 144 * 145 * @param mediaTypes The media types to match against. 146 * @return The index into the array of the best match, or <c>-1</c> if no suitable matches could be found. 147 */ 148 public int match(List<? extends MediaType> mediaTypes) { 149 if (string.isEmpty() || mediaTypes == null) 150 return -1; 151 152 int matchQuant = 0, matchIndex = -1; 153 float q = 0f; 154 155 // Media ranges are ordered by 'q'. 156 // So we only need to search until we've found a match. 157 for (MediaRange mr : ranges) { 158 float q2 = mr.getQValue(); 159 160 if (q2 < q || q2 == 0) 161 break; 162 163 for (int i = 0; i < mediaTypes.size(); i++) { 164 MediaType mt = mediaTypes.get(i); 165 int matchQuant2 = mr.match(mt, false); 166 167 if (matchQuant2 > matchQuant) { 168 matchIndex = i; 169 matchQuant = matchQuant2; 170 q = q2; 171 } 172 } 173 } 174 175 return matchIndex; 176 } 177 178 /** 179 * Returns the {@link MediaRange} at the specified index. 180 * 181 * @param index The index position of the media range. 182 * @return The {@link MediaRange} at the specified index or <jk>null</jk> if the index is out of range. 183 */ 184 public MediaRange getRange(int index) { 185 if (index < 0 || index >= ranges.length) 186 return null; 187 return ranges[index]; 188 } 189 190 /** 191 * Convenience method for searching through all of the subtypes of all the media ranges in this header for the 192 * presence of a subtype fragment. 193 * 194 * <p> 195 * For example, given the header <js>"text/json+activity"</js>, calling 196 * <code>hasSubtypePart(<js>"activity"</js>)</code> returns <jk>true</jk>. 197 * 198 * @param part The media type subtype fragment. 199 * @return <jk>true</jk> if subtype fragment exists. 200 */ 201 public boolean hasSubtypePart(String part) { 202 203 for (MediaRange mr : ranges) 204 if (mr.getQValue() > 0 && mr.getSubTypes().indexOf(part) >= 0) 205 return true; 206 207 return false; 208 } 209 210 /** 211 * Returns the media ranges that make up this object. 212 * 213 * @return The media ranges that make up this object. 214 */ 215 public List<MediaRange> toList() { 216 return ulist(ranges); 217 } 218 219 /** 220 * Performs an action on the media ranges that make up this object. 221 * 222 * @param action The action to perform. 223 * @return This object. 224 */ 225 public MediaRanges forEachRange(Consumer<MediaRange> action) { 226 for (MediaRange r : ranges) 227 action.accept(r); 228 return this; 229 } 230 231 private static HeaderElement[] parse(String value) { 232 return BasicHeaderValueParser.parseElements(emptyIfNull(trim(value)), null); 233 } 234 235 @Override /* Object */ 236 public String toString() { 237 return string; 238 } 239}