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