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