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