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