001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance 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
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.net;
016
017import static com.google.common.base.CharMatcher.ascii;
018import static com.google.common.base.CharMatcher.javaIsoControl;
019import static com.google.common.base.MoreObjects.firstNonNull;
020import static com.google.common.base.Preconditions.checkArgument;
021import static com.google.common.base.Preconditions.checkNotNull;
022import static com.google.common.base.Preconditions.checkState;
023import static java.nio.charset.StandardCharsets.UTF_8;
024import static java.util.Objects.hash;
025
026import com.google.common.annotations.GwtCompatible;
027import com.google.common.base.Ascii;
028import com.google.common.base.CharMatcher;
029import com.google.common.base.Joiner;
030import com.google.common.base.Joiner.MapJoiner;
031import com.google.common.base.Optional;
032import com.google.common.collect.ImmutableListMultimap;
033import com.google.common.collect.ImmutableMultiset;
034import com.google.common.collect.ImmutableSet;
035import com.google.common.collect.Maps;
036import com.google.common.collect.Multimap;
037import com.google.common.collect.Multimaps;
038import com.google.errorprone.annotations.CanIgnoreReturnValue;
039import com.google.errorprone.annotations.Immutable;
040import com.google.errorprone.annotations.concurrent.LazyInit;
041import java.nio.charset.Charset;
042import java.nio.charset.IllegalCharsetNameException;
043import java.nio.charset.UnsupportedCharsetException;
044import java.util.Map;
045import java.util.Map.Entry;
046import org.jspecify.annotations.Nullable;
047
048/**
049 * Represents an <a href="http://en.wikipedia.org/wiki/Internet_media_type">Internet Media Type</a>
050 * (also known as a MIME Type or Content Type). This class also supports the concept of media ranges
051 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">defined by HTTP/1.1</a>.
052 * As such, the {@code *} character is treated as a wildcard and is used to represent any acceptable
053 * type or subtype value. A media type may not have wildcard type with a declared subtype. The
054 * {@code *} character has no special meaning as part of a parameter. All values for type, subtype,
055 * parameter attributes or parameter values must be valid according to RFCs <a
056 * href="https://tools.ietf.org/html/rfc2045">2045</a> and <a
057 * href="https://tools.ietf.org/html/rfc2046">2046</a>.
058 *
059 * <p>All portions of the media type that are case-insensitive (type, subtype, parameter attributes)
060 * are normalized to lowercase. The value of the {@code charset} parameter is normalized to
061 * lowercase, but all others are left as-is.
062 *
063 * <p>Note that this specifically does <strong>not</strong> represent the value of the MIME {@code
064 * Content-Type} header and as such has no support for header-specific considerations such as line
065 * folding and comments.
066 *
067 * <p>For media types that take a charset the predefined constants default to UTF-8 and have a
068 * "_UTF_8" suffix. To get a version without a character set, use {@link #withoutParameters}.
069 *
070 * @since 12.0
071 * @author Gregory Kick
072 */
073@GwtCompatible
074@Immutable
075public final class MediaType {
076  private static final String CHARSET_ATTRIBUTE = "charset";
077  private static final ImmutableListMultimap<String, String> UTF_8_CONSTANT_PARAMETERS =
078      ImmutableListMultimap.of(CHARSET_ATTRIBUTE, Ascii.toLowerCase(UTF_8.name()));
079
080  /** Matcher for type, subtype and attributes. */
081  private static final CharMatcher TOKEN_MATCHER =
082      ascii()
083          .and(javaIsoControl().negate())
084          .and(CharMatcher.isNot(' '))
085          .and(CharMatcher.noneOf("()<>@,;:\\\"/[]?="));
086
087  private static final CharMatcher QUOTED_TEXT_MATCHER = ascii().and(CharMatcher.noneOf("\"\\\r"));
088
089  /*
090   * This matches the same characters as linear-white-space from RFC 822, but we make no effort to
091   * enforce any particular rules with regards to line folding as stated in the class docs.
092   */
093  private static final CharMatcher LINEAR_WHITE_SPACE = CharMatcher.anyOf(" \t\r\n");
094
095  // TODO(gak): make these public?
096  private static final String APPLICATION_TYPE = "application";
097  private static final String AUDIO_TYPE = "audio";
098  private static final String IMAGE_TYPE = "image";
099  private static final String TEXT_TYPE = "text";
100  private static final String VIDEO_TYPE = "video";
101  private static final String FONT_TYPE = "font";
102
103  private static final String WILDCARD = "*";
104
105  private static final Map<MediaType, MediaType> knownTypes = Maps.newHashMap();
106
107  private static MediaType createConstant(String type, String subtype) {
108    MediaType mediaType =
109        addKnownType(new MediaType(type, subtype, ImmutableListMultimap.<String, String>of()));
110    mediaType.parsedCharset = Optional.absent();
111    return mediaType;
112  }
113
114  private static MediaType createConstantUtf8(String type, String subtype) {
115    MediaType mediaType = addKnownType(new MediaType(type, subtype, UTF_8_CONSTANT_PARAMETERS));
116    mediaType.parsedCharset = Optional.of(UTF_8);
117    return mediaType;
118  }
119
120  @CanIgnoreReturnValue
121  private static MediaType addKnownType(MediaType mediaType) {
122    knownTypes.put(mediaType, mediaType);
123    return mediaType;
124  }
125
126  /*
127   * The following constants are grouped by their type and ordered alphabetically by the constant
128   * name within that type. The constant name should be a sensible identifier that is closest to the
129   * "common name" of the media. This is often, but not necessarily the same as the subtype.
130   *
131   * Be sure to declare all constants with the type and subtype in all lowercase. For types that
132   * take a charset (e.g. all text/* types), default to UTF-8 and suffix the constant name with
133   * "_UTF_8".
134   */
135
136  public static final MediaType ANY_TYPE = createConstant(WILDCARD, WILDCARD);
137  public static final MediaType ANY_TEXT_TYPE = createConstant(TEXT_TYPE, WILDCARD);
138  public static final MediaType ANY_IMAGE_TYPE = createConstant(IMAGE_TYPE, WILDCARD);
139  public static final MediaType ANY_AUDIO_TYPE = createConstant(AUDIO_TYPE, WILDCARD);
140  public static final MediaType ANY_VIDEO_TYPE = createConstant(VIDEO_TYPE, WILDCARD);
141  public static final MediaType ANY_APPLICATION_TYPE = createConstant(APPLICATION_TYPE, WILDCARD);
142
143  /**
144   * Wildcard matching any "font" top-level media type.
145   *
146   * @since 30.0
147   */
148  public static final MediaType ANY_FONT_TYPE = createConstant(FONT_TYPE, WILDCARD);
149
150  /* text types */
151  public static final MediaType CACHE_MANIFEST_UTF_8 =
152      createConstantUtf8(TEXT_TYPE, "cache-manifest");
153  public static final MediaType CSS_UTF_8 = createConstantUtf8(TEXT_TYPE, "css");
154  public static final MediaType CSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "csv");
155  public static final MediaType HTML_UTF_8 = createConstantUtf8(TEXT_TYPE, "html");
156  public static final MediaType I_CALENDAR_UTF_8 = createConstantUtf8(TEXT_TYPE, "calendar");
157
158  /**
159   * As described in <a href="https://www.rfc-editor.org/rfc/rfc7763.html">RFC 7763</a>, this
160   * constant ({@code text/markdown}) is used for Markdown documents.
161   *
162   * @since 33.3.0
163   */
164  public static final MediaType MD_UTF_8 = createConstantUtf8(TEXT_TYPE, "markdown");
165
166  public static final MediaType PLAIN_TEXT_UTF_8 = createConstantUtf8(TEXT_TYPE, "plain");
167
168  /**
169   * <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares {@link
170   * #JAVASCRIPT_UTF_8 application/javascript} to be the correct media type for JavaScript, but this
171   * may be necessary in certain situations for compatibility.
172   */
173  public static final MediaType TEXT_JAVASCRIPT_UTF_8 = createConstantUtf8(TEXT_TYPE, "javascript");
174
175  /**
176   * <a href="http://www.iana.org/assignments/media-types/text/tab-separated-values">Tab separated
177   * values</a>.
178   *
179   * @since 15.0
180   */
181  public static final MediaType TSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "tab-separated-values");
182
183  public static final MediaType VCARD_UTF_8 = createConstantUtf8(TEXT_TYPE, "vcard");
184
185  /**
186   * UTF-8 encoded <a href="https://en.wikipedia.org/wiki/Wireless_Markup_Language">Wireless Markup
187   * Language</a>.
188   *
189   * @since 13.0
190   */
191  public static final MediaType WML_UTF_8 = createConstantUtf8(TEXT_TYPE, "vnd.wap.wml");
192
193  /**
194   * As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant
195   * ({@code text/xml}) is used for XML documents that are "readable by casual users." {@link
196   * #APPLICATION_XML_UTF_8} is provided for documents that are intended for applications.
197   */
198  public static final MediaType XML_UTF_8 = createConstantUtf8(TEXT_TYPE, "xml");
199
200  /**
201   * As described in <a href="https://w3c.github.io/webvtt/#iana-text-vtt">the VTT spec</a>, this is
202   * used for Web Video Text Tracks (WebVTT) files, used with the HTML5 track element.
203   *
204   * @since 20.0
205   */
206  public static final MediaType VTT_UTF_8 = createConstantUtf8(TEXT_TYPE, "vtt");
207
208  /* image types */
209  /**
210   * <a href="https://en.wikipedia.org/wiki/BMP_file_format">Bitmap file format</a> ({@code bmp}
211   * files).
212   *
213   * @since 13.0
214   */
215  public static final MediaType BMP = createConstant(IMAGE_TYPE, "bmp");
216
217  /**
218   * The <a href="https://en.wikipedia.org/wiki/Camera_Image_File_Format">Canon Image File
219   * Format</a> ({@code crw} files), a widely-used "raw image" format for cameras. It is found in
220   * {@code /etc/mime.types}, e.g. in <a href=
221   * "http://anonscm.debian.org/gitweb/?p=collab-maint/mime-support.git;a=blob;f=mime.types;hb=HEAD"
222   * >Debian 3.48-1</a>.
223   *
224   * @since 15.0
225   */
226  public static final MediaType CRW = createConstant(IMAGE_TYPE, "x-canon-crw");
227
228  public static final MediaType GIF = createConstant(IMAGE_TYPE, "gif");
229  public static final MediaType ICO = createConstant(IMAGE_TYPE, "vnd.microsoft.icon");
230  public static final MediaType JPEG = createConstant(IMAGE_TYPE, "jpeg");
231  public static final MediaType PNG = createConstant(IMAGE_TYPE, "png");
232
233  /**
234   * The Photoshop File Format ({@code psd} files) as defined by <a
235   * href="http://www.iana.org/assignments/media-types/image/vnd.adobe.photoshop">IANA</a>, and
236   * found in {@code /etc/mime.types}, e.g. <a
237   * href="http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types"></a> of the
238   * Apache <a href="http://httpd.apache.org/">HTTPD project</a>; for the specification, see <a
239   * href="http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/PhotoshopFileFormats.htm">
240   * Adobe Photoshop Document Format</a> and <a
241   * href="http://en.wikipedia.org/wiki/Adobe_Photoshop#File_format">Wikipedia</a>; this is the
242   * regular output/input of Photoshop (which can also export to various image formats; note that
243   * files with extension "PSB" are in a distinct but related format).
244   *
245   * <p>This is a more recent replacement for the older, experimental type {@code x-photoshop}: <a
246   * href="http://tools.ietf.org/html/rfc2046#section-6">RFC-2046.6</a>.
247   *
248   * @since 15.0
249   */
250  public static final MediaType PSD = createConstant(IMAGE_TYPE, "vnd.adobe.photoshop");
251
252  public static final MediaType SVG_UTF_8 = createConstantUtf8(IMAGE_TYPE, "svg+xml");
253  public static final MediaType TIFF = createConstant(IMAGE_TYPE, "tiff");
254
255  /**
256   * <a href="https://en.wikipedia.org/wiki/WebP">WebP image format</a>.
257   *
258   * @since 13.0
259   */
260  public static final MediaType WEBP = createConstant(IMAGE_TYPE, "webp");
261
262  /**
263   * <a href="https://www.iana.org/assignments/media-types/image/heif">HEIF image format</a>.
264   *
265   * @since 28.1
266   */
267  public static final MediaType HEIF = createConstant(IMAGE_TYPE, "heif");
268
269  /**
270   * <a href="https://tools.ietf.org/html/rfc3745">JP2K image format</a>.
271   *
272   * @since 28.1
273   */
274  public static final MediaType JP2K = createConstant(IMAGE_TYPE, "jp2");
275
276  /* audio types */
277  public static final MediaType MP4_AUDIO = createConstant(AUDIO_TYPE, "mp4");
278  public static final MediaType MPEG_AUDIO = createConstant(AUDIO_TYPE, "mpeg");
279  public static final MediaType OGG_AUDIO = createConstant(AUDIO_TYPE, "ogg");
280  public static final MediaType WEBM_AUDIO = createConstant(AUDIO_TYPE, "webm");
281
282  /**
283   * L16 audio, as defined by <a href="https://tools.ietf.org/html/rfc2586">RFC 2586</a>.
284   *
285   * @since 24.1
286   */
287  public static final MediaType L16_AUDIO = createConstant(AUDIO_TYPE, "l16");
288
289  /**
290   * L24 audio, as defined by <a href="https://tools.ietf.org/html/rfc3190">RFC 3190</a>.
291   *
292   * @since 20.0
293   */
294  public static final MediaType L24_AUDIO = createConstant(AUDIO_TYPE, "l24");
295
296  /**
297   * Basic Audio, as defined by <a href="http://tools.ietf.org/html/rfc2046#section-4.3">RFC
298   * 2046</a>.
299   *
300   * @since 20.0
301   */
302  public static final MediaType BASIC_AUDIO = createConstant(AUDIO_TYPE, "basic");
303
304  /**
305   * Advanced Audio Coding. For more information, see <a
306   * href="https://en.wikipedia.org/wiki/Advanced_Audio_Coding">Advanced Audio Coding</a>.
307   *
308   * @since 20.0
309   */
310  public static final MediaType AAC_AUDIO = createConstant(AUDIO_TYPE, "aac");
311
312  /**
313   * Vorbis Audio, as defined by <a href="http://tools.ietf.org/html/rfc5215">RFC 5215</a>.
314   *
315   * @since 20.0
316   */
317  public static final MediaType VORBIS_AUDIO = createConstant(AUDIO_TYPE, "vorbis");
318
319  /**
320   * Windows Media Audio. For more information, see <a
321   * href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd562994(v=vs.85).aspx">file
322   * name extensions for Windows Media metafiles</a>.
323   *
324   * @since 20.0
325   */
326  public static final MediaType WMA_AUDIO = createConstant(AUDIO_TYPE, "x-ms-wma");
327
328  /**
329   * Windows Media metafiles. For more information, see <a
330   * href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd562994(v=vs.85).aspx">file
331   * name extensions for Windows Media metafiles</a>.
332   *
333   * @since 20.0
334   */
335  public static final MediaType WAX_AUDIO = createConstant(AUDIO_TYPE, "x-ms-wax");
336
337  /**
338   * Real Audio. For more information, see <a
339   * href="http://service.real.com/help/faq/rp8/configrp8win.html">this link</a>.
340   *
341   * @since 20.0
342   */
343  public static final MediaType VND_REAL_AUDIO = createConstant(AUDIO_TYPE, "vnd.rn-realaudio");
344
345  /**
346   * WAVE format, as defined by <a href="https://tools.ietf.org/html/rfc2361">RFC 2361</a>.
347   *
348   * @since 20.0
349   */
350  public static final MediaType VND_WAVE_AUDIO = createConstant(AUDIO_TYPE, "vnd.wave");
351
352  /* video types */
353  public static final MediaType MP4_VIDEO = createConstant(VIDEO_TYPE, "mp4");
354  public static final MediaType MPEG_VIDEO = createConstant(VIDEO_TYPE, "mpeg");
355  public static final MediaType OGG_VIDEO = createConstant(VIDEO_TYPE, "ogg");
356  public static final MediaType QUICKTIME = createConstant(VIDEO_TYPE, "quicktime");
357  public static final MediaType WEBM_VIDEO = createConstant(VIDEO_TYPE, "webm");
358  public static final MediaType WMV = createConstant(VIDEO_TYPE, "x-ms-wmv");
359
360  /**
361   * Flash video. For more information, see <a href=
362   * "http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7d48.html"
363   * >this link</a>.
364   *
365   * @since 20.0
366   */
367  public static final MediaType FLV_VIDEO = createConstant(VIDEO_TYPE, "x-flv");
368
369  /**
370   * The 3GP multimedia container format. For more information, see <a
371   * href="ftp://www.3gpp.org/tsg_sa/TSG_SA/TSGS_23/Docs/PDF/SP-040065.pdf#page=10">3GPP TS
372   * 26.244</a>.
373   *
374   * @since 20.0
375   */
376  public static final MediaType THREE_GPP_VIDEO = createConstant(VIDEO_TYPE, "3gpp");
377
378  /**
379   * The 3G2 multimedia container format. For more information, see <a
380   * href="http://www.3gpp2.org/Public_html/specs/C.S0050-B_v1.0_070521.pdf#page=16">3GPP2
381   * C.S0050-B</a>.
382   *
383   * @since 20.0
384   */
385  public static final MediaType THREE_GPP2_VIDEO = createConstant(VIDEO_TYPE, "3gpp2");
386
387  /* application types */
388  /**
389   * As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant
390   * ({@code application/xml}) is used for XML documents that are "unreadable by casual users."
391   * {@link #XML_UTF_8} is provided for documents that may be read by users.
392   *
393   * @since 14.0
394   */
395  public static final MediaType APPLICATION_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xml");
396
397  public static final MediaType ATOM_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "atom+xml");
398  public static final MediaType BZIP2 = createConstant(APPLICATION_TYPE, "x-bzip2");
399
400  /**
401   * Files in the <a href="https://www.dartlang.org/articles/embedding-in-html/">dart</a>
402   * programming language.
403   *
404   * @since 19.0
405   */
406  public static final MediaType DART_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "dart");
407
408  /**
409   * <a
410   * href="https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/PassKit_PG/DistributingPasses.html">Apple
411   * Passbook</a>.
412   *
413   * @since 19.0
414   */
415  public static final MediaType APPLE_PASSBOOK =
416      createConstant(APPLICATION_TYPE, "vnd.apple.pkpass");
417
418  /**
419   * <a href="http://en.wikipedia.org/wiki/Embedded_OpenType">Embedded OpenType</a> fonts. This is
420   * <a href="http://www.iana.org/assignments/media-types/application/vnd.ms-fontobject">registered
421   * </a> with the IANA.
422   *
423   * @since 17.0
424   */
425  public static final MediaType EOT = createConstant(APPLICATION_TYPE, "vnd.ms-fontobject");
426
427  /**
428   * As described in the <a href="http://idpf.org/epub">International Digital Publishing Forum</a>
429   * EPUB is the distribution and interchange format standard for digital publications and
430   * documents. This media type is defined in the <a
431   * href="http://www.idpf.org/epub/30/spec/epub30-ocf.html">EPUB Open Container Format</a>
432   * specification.
433   *
434   * @since 15.0
435   */
436  public static final MediaType EPUB = createConstant(APPLICATION_TYPE, "epub+zip");
437
438  public static final MediaType FORM_DATA =
439      createConstant(APPLICATION_TYPE, "x-www-form-urlencoded");
440
441  /**
442   * As described in <a href="https://www.rsa.com/rsalabs/node.asp?id=2138">PKCS #12: Personal
443   * Information Exchange Syntax Standard</a>, PKCS #12 defines an archive file format for storing
444   * many cryptography objects as a single file.
445   *
446   * @since 15.0
447   */
448  public static final MediaType KEY_ARCHIVE = createConstant(APPLICATION_TYPE, "pkcs12");
449
450  /**
451   * This is a non-standard media type, but is commonly used in serving hosted binary files as it is
452   * <a href="http://code.google.com/p/browsersec/wiki/Part2#Survey_of_content_sniffing_behaviors">
453   * known not to trigger content sniffing in current browsers</a>. It <i>should not</i> be used in
454   * other situations as it is not specified by any RFC and does not appear in the <a
455   * href="http://www.iana.org/assignments/media-types">/IANA MIME Media Types</a> list. Consider
456   * {@link #OCTET_STREAM} for binary data that is not being served to a browser.
457   *
458   * @since 14.0
459   */
460  public static final MediaType APPLICATION_BINARY = createConstant(APPLICATION_TYPE, "binary");
461
462  /**
463   * As described in <a href="https://www.rfc-editor.org/rfc/rfc8949.html">RFC 8949</a>, this
464   * constant ({@code application/cbor}) is used for the Concise Binary Object Representation (CBOR)
465   * data format.
466   *
467   * @since 33.4.0
468   */
469  public static final MediaType CBOR = createConstant(APPLICATION_TYPE, "cbor");
470
471  /**
472   * Media type for the <a href="https://tools.ietf.org/html/rfc7946">GeoJSON Format</a>, a
473   * geospatial data interchange format based on JSON.
474   *
475   * @since 28.0
476   */
477  public static final MediaType GEO_JSON = createConstant(APPLICATION_TYPE, "geo+json");
478
479  public static final MediaType GZIP = createConstant(APPLICATION_TYPE, "x-gzip");
480
481  /**
482   * <a href="https://tools.ietf.org/html/draft-kelly-json-hal-08#section-3">JSON Hypertext
483   * Application Language (HAL) documents</a>.
484   *
485   * @since 26.0
486   */
487  public static final MediaType HAL_JSON = createConstant(APPLICATION_TYPE, "hal+json");
488
489  /**
490   * <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares this to be the
491   * correct media type for JavaScript, but {@link #TEXT_JAVASCRIPT_UTF_8 text/javascript} may be
492   * necessary in certain situations for compatibility.
493   */
494  public static final MediaType JAVASCRIPT_UTF_8 =
495      createConstantUtf8(APPLICATION_TYPE, "javascript");
496
497  /**
498   * For <a href="https://tools.ietf.org/html/rfc7515">JWS or JWE objects using the Compact
499   * Serialization</a>.
500   *
501   * @since 27.1
502   */
503  public static final MediaType JOSE = createConstant(APPLICATION_TYPE, "jose");
504
505  /**
506   * For <a href="https://tools.ietf.org/html/rfc7515">JWS or JWE objects using the JSON
507   * Serialization</a>.
508   *
509   * @since 27.1
510   */
511  public static final MediaType JOSE_JSON = createConstant(APPLICATION_TYPE, "jose+json");
512
513  public static final MediaType JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "json");
514
515  /**
516   * For <a href="https://tools.ietf.org/html/7519">JWT objects using the compact Serialization</a>.
517   *
518   * @since 32.0.0
519   */
520  public static final MediaType JWT = createConstant(APPLICATION_TYPE, "jwt");
521
522  /**
523   * The <a href="http://www.w3.org/TR/appmanifest/">Manifest for a web application</a>.
524   *
525   * @since 19.0
526   */
527  public static final MediaType MANIFEST_JSON_UTF_8 =
528      createConstantUtf8(APPLICATION_TYPE, "manifest+json");
529
530  /**
531   * <a href="http://www.opengeospatial.org/standards/kml/">OGC KML (Keyhole Markup Language)</a>.
532   */
533  public static final MediaType KML = createConstant(APPLICATION_TYPE, "vnd.google-earth.kml+xml");
534
535  /**
536   * <a href="http://www.opengeospatial.org/standards/kml/">OGC KML (Keyhole Markup Language)</a>,
537   * compressed using the ZIP format into KMZ archives.
538   */
539  public static final MediaType KMZ = createConstant(APPLICATION_TYPE, "vnd.google-earth.kmz");
540
541  /**
542   * The <a href="https://tools.ietf.org/html/rfc4155">mbox database format</a>.
543   *
544   * @since 13.0
545   */
546  public static final MediaType MBOX = createConstant(APPLICATION_TYPE, "mbox");
547
548  /**
549   * <a
550   * href="https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/iPhoneOTAConfiguration/profile-service/profile-service.html">Apple
551   * over-the-air mobile configuration profiles</a>.
552   *
553   * @since 18.0
554   */
555  public static final MediaType APPLE_MOBILE_CONFIG =
556      createConstant(APPLICATION_TYPE, "x-apple-aspen-config");
557
558  /**
559   * <a
560   * href="https://learn.microsoft.com/en-us/archive/blogs/vsofficedeveloper/office-2007-file-format-mime-types-for-http-content-streaming-2">Microsoft
561   * Excel</a> spreadsheets.
562   */
563  public static final MediaType MICROSOFT_EXCEL = createConstant(APPLICATION_TYPE, "vnd.ms-excel");
564
565  /**
566   * <a href="https://www.loc.gov/preservation/digital/formats/fdd/fdd000379.shtml">Microsoft
567   * Outlook</a> items.
568   *
569   * @since 27.1
570   */
571  public static final MediaType MICROSOFT_OUTLOOK =
572      createConstant(APPLICATION_TYPE, "vnd.ms-outlook");
573
574  /**
575   * <a
576   * href="https://learn.microsoft.com/en-us/archive/blogs/vsofficedeveloper/office-2007-file-format-mime-types-for-http-content-streaming-2">Microsoft
577   * Powerpoint</a> presentations.
578   */
579  public static final MediaType MICROSOFT_POWERPOINT =
580      createConstant(APPLICATION_TYPE, "vnd.ms-powerpoint");
581
582  /**
583   * <a
584   * href="https://learn.microsoft.com/en-us/archive/blogs/vsofficedeveloper/office-2007-file-format-mime-types-for-http-content-streaming-2">Microsoft
585   * Word</a> documents.
586   */
587  public static final MediaType MICROSOFT_WORD = createConstant(APPLICATION_TYPE, "msword");
588
589  /**
590   * Media type for <a
591   * href="https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP">Dynamic Adaptive
592   * Streaming over HTTP (DASH)</a>. This is <a
593   * href="https://www.iana.org/assignments/media-types/application/dash+xml">registered</a> with
594   * the IANA.
595   *
596   * @since 28.2
597   */
598  public static final MediaType MEDIA_PRESENTATION_DESCRIPTION =
599      createConstant(APPLICATION_TYPE, "dash+xml");
600
601  /**
602   * WASM applications. For more information see <a href="https://webassembly.org/">the Web Assembly
603   * overview</a>.
604   *
605   * @since 27.0
606   */
607  public static final MediaType WASM_APPLICATION = createConstant(APPLICATION_TYPE, "wasm");
608
609  /**
610   * NaCl applications. For more information see <a
611   * href="https://developer.chrome.com/native-client/devguide/coding/application-structure">the
612   * Developer Guide for Native Client Application Structure</a>.
613   *
614   * @since 20.0
615   */
616  public static final MediaType NACL_APPLICATION = createConstant(APPLICATION_TYPE, "x-nacl");
617
618  /**
619   * NaCl portable applications. For more information see <a
620   * href="https://developer.chrome.com/native-client/devguide/coding/application-structure">the
621   * Developer Guide for Native Client Application Structure</a>.
622   *
623   * @since 20.0
624   */
625  public static final MediaType NACL_PORTABLE_APPLICATION =
626      createConstant(APPLICATION_TYPE, "x-pnacl");
627
628  public static final MediaType OCTET_STREAM = createConstant(APPLICATION_TYPE, "octet-stream");
629
630  public static final MediaType OGG_CONTAINER = createConstant(APPLICATION_TYPE, "ogg");
631  public static final MediaType OOXML_DOCUMENT =
632      createConstant(
633          APPLICATION_TYPE, "vnd.openxmlformats-officedocument.wordprocessingml.document");
634  public static final MediaType OOXML_PRESENTATION =
635      createConstant(
636          APPLICATION_TYPE, "vnd.openxmlformats-officedocument.presentationml.presentation");
637  public static final MediaType OOXML_SHEET =
638      createConstant(APPLICATION_TYPE, "vnd.openxmlformats-officedocument.spreadsheetml.sheet");
639  public static final MediaType OPENDOCUMENT_GRAPHICS =
640      createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.graphics");
641  public static final MediaType OPENDOCUMENT_PRESENTATION =
642      createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.presentation");
643  public static final MediaType OPENDOCUMENT_SPREADSHEET =
644      createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.spreadsheet");
645  public static final MediaType OPENDOCUMENT_TEXT =
646      createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.text");
647
648  /**
649   * <a href="https://tools.ietf.org/id/draft-ellermann-opensearch-01.html">OpenSearch</a>
650   * Description files are XML files that describe how a website can be used as a search engine by
651   * consumers (e.g. web browsers).
652   *
653   * @since 28.2
654   */
655  public static final MediaType OPENSEARCH_DESCRIPTION_UTF_8 =
656      createConstantUtf8(APPLICATION_TYPE, "opensearchdescription+xml");
657
658  public static final MediaType PDF = createConstant(APPLICATION_TYPE, "pdf");
659  public static final MediaType POSTSCRIPT = createConstant(APPLICATION_TYPE, "postscript");
660
661  /**
662   * <a href="http://tools.ietf.org/html/draft-rfernando-protocol-buffers-00">Protocol buffers</a>
663   *
664   * @since 15.0
665   */
666  public static final MediaType PROTOBUF = createConstant(APPLICATION_TYPE, "protobuf");
667
668  /**
669   * <a href="https://en.wikipedia.org/wiki/RDF/XML">RDF/XML</a> documents, which are XML
670   * serializations of <a
671   * href="https://en.wikipedia.org/wiki/Resource_Description_Framework">Resource Description
672   * Framework</a> graphs.
673   *
674   * @since 14.0
675   */
676  public static final MediaType RDF_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rdf+xml");
677
678  public static final MediaType RTF_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rtf");
679
680  /**
681   * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares {@link #FONT_SFNT
682   * font/sfnt} to be the correct media type for SFNT, but this may be necessary in certain
683   * situations for compatibility.
684   *
685   * @since 17.0
686   */
687  public static final MediaType SFNT = createConstant(APPLICATION_TYPE, "font-sfnt");
688
689  public static final MediaType SHOCKWAVE_FLASH =
690      createConstant(APPLICATION_TYPE, "x-shockwave-flash");
691
692  /**
693   * {@code skp} files produced by the 3D Modeling software <a
694   * href="https://www.sketchup.com/">SketchUp</a>
695   *
696   * @since 13.0
697   */
698  public static final MediaType SKETCHUP = createConstant(APPLICATION_TYPE, "vnd.sketchup.skp");
699
700  /**
701   * As described in <a href="http://www.ietf.org/rfc/rfc3902.txt">RFC 3902</a>, this constant
702   * ({@code application/soap+xml}) is used to identify SOAP 1.2 message envelopes that have been
703   * serialized with XML 1.0.
704   *
705   * <p>For SOAP 1.1 messages, see {@code XML_UTF_8} per <a
706   * href="http://www.w3.org/TR/2000/NOTE-SOAP-20000508/">W3C Note on Simple Object Access Protocol
707   * (SOAP) 1.1</a>
708   *
709   * @since 20.0
710   */
711  public static final MediaType SOAP_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "soap+xml");
712
713  public static final MediaType TAR = createConstant(APPLICATION_TYPE, "x-tar");
714
715  /**
716   * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares {@link #FONT_WOFF
717   * font/woff} to be the correct media type for WOFF, but this may be necessary in certain
718   * situations for compatibility.
719   *
720   * @since 17.0
721   */
722  public static final MediaType WOFF = createConstant(APPLICATION_TYPE, "font-woff");
723
724  /**
725   * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares {@link #FONT_WOFF2
726   * font/woff2} to be the correct media type for WOFF2, but this may be necessary in certain
727   * situations for compatibility.
728   *
729   * @since 20.0
730   */
731  public static final MediaType WOFF2 = createConstant(APPLICATION_TYPE, "font-woff2");
732
733  public static final MediaType XHTML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xhtml+xml");
734
735  /**
736   * Extensible Resource Descriptors. This is not yet registered with the IANA, but it is specified
737   * by OASIS in the <a href="http://docs.oasis-open.org/xri/xrd/v1.0/cd02/xrd-1.0-cd02.html">XRD
738   * definition</a> and implemented in projects such as <a
739   * href="http://code.google.com/p/webfinger/">WebFinger</a>.
740   *
741   * @since 14.0
742   */
743  public static final MediaType XRD_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xrd+xml");
744
745  public static final MediaType ZIP = createConstant(APPLICATION_TYPE, "zip");
746
747  /* font types */
748
749  /**
750   * A collection of font outlines as defined by <a href="https://tools.ietf.org/html/rfc8081">RFC
751   * 8081</a>.
752   *
753   * @since 30.0
754   */
755  public static final MediaType FONT_COLLECTION = createConstant(FONT_TYPE, "collection");
756
757  /**
758   * <a href="https://en.wikipedia.org/wiki/OpenType">Open Type Font Format</a> (OTF) as defined by
759   * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a>.
760   *
761   * @since 30.0
762   */
763  public static final MediaType FONT_OTF = createConstant(FONT_TYPE, "otf");
764
765  /**
766   * <a href="https://en.wikipedia.org/wiki/SFNT">Spline or Scalable Font Format</a> (SFNT). <a
767   * href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares this to be the correct media
768   * type for SFNT, but {@link #SFNT application/font-sfnt} may be necessary in certain situations
769   * for compatibility.
770   *
771   * @since 30.0
772   */
773  public static final MediaType FONT_SFNT = createConstant(FONT_TYPE, "sfnt");
774
775  /**
776   * <a href="https://en.wikipedia.org/wiki/TrueType">True Type Font Format</a> (TTF) as defined by
777   * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a>.
778   *
779   * @since 30.0
780   */
781  public static final MediaType FONT_TTF = createConstant(FONT_TYPE, "ttf");
782
783  /**
784   * <a href="http://en.wikipedia.org/wiki/Web_Open_Font_Format">Web Open Font Format</a> (WOFF). <a
785   * href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares this to be the correct media
786   * type for SFNT, but {@link #WOFF application/font-woff} may be necessary in certain situations
787   * for compatibility.
788   *
789   * @since 30.0
790   */
791  public static final MediaType FONT_WOFF = createConstant(FONT_TYPE, "woff");
792
793  /**
794   * <a href="http://en.wikipedia.org/wiki/Web_Open_Font_Format">Web Open Font Format</a> (WOFF2).
795   * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares this to be the correct
796   * media type for SFNT, but {@link #WOFF2 application/font-woff2} may be necessary in certain
797   * situations for compatibility.
798   *
799   * @since 30.0
800   */
801  public static final MediaType FONT_WOFF2 = createConstant(FONT_TYPE, "woff2");
802
803  private final String type;
804  private final String subtype;
805  private final ImmutableListMultimap<String, String> parameters;
806
807  @LazyInit private @Nullable String toString;
808
809  @LazyInit private int hashCode;
810
811  // We need to differentiate between "not computed" and "computed to be absent."
812  @SuppressWarnings("NullableOptional")
813  @LazyInit
814  private @Nullable Optional<Charset> parsedCharset;
815
816  private MediaType(String type, String subtype, ImmutableListMultimap<String, String> parameters) {
817    this.type = type;
818    this.subtype = subtype;
819    this.parameters = parameters;
820  }
821
822  /** Returns the top-level media type. For example, {@code "text"} in {@code "text/plain"}. */
823  public String type() {
824    return type;
825  }
826
827  /** Returns the media subtype. For example, {@code "plain"} in {@code "text/plain"}. */
828  public String subtype() {
829    return subtype;
830  }
831
832  /** Returns a multimap containing the parameters of this media type. */
833  public ImmutableListMultimap<String, String> parameters() {
834    return parameters;
835  }
836
837  private Map<String, ImmutableMultiset<String>> parametersAsMap() {
838    return Maps.transformValues(parameters.asMap(), ImmutableMultiset::copyOf);
839  }
840
841  /**
842   * Returns an optional charset for the value of the charset parameter if it is specified.
843   *
844   * @throws IllegalStateException if multiple charset values have been set for this media type
845   * @throws IllegalCharsetNameException if a charset value is present, but illegal
846   * @throws UnsupportedCharsetException if a charset value is present, but no support is available
847   *     in this instance of the Java virtual machine
848   */
849  public Optional<Charset> charset() {
850    // racy single-check idiom, this is safe because Optional is immutable.
851    Optional<Charset> local = parsedCharset;
852    if (local == null) {
853      String value = null;
854      local = Optional.absent();
855      for (String currentValue : parameters.get(CHARSET_ATTRIBUTE)) {
856        if (value == null) {
857          value = currentValue;
858          local = Optional.of(Charset.forName(value));
859        } else if (!value.equals(currentValue)) {
860          throw new IllegalStateException(
861              "Multiple charset values defined: " + value + ", " + currentValue);
862        }
863      }
864      parsedCharset = local;
865    }
866    return local;
867  }
868
869  /**
870   * Returns a new instance with the same type and subtype as this instance, but without any
871   * parameters.
872   */
873  public MediaType withoutParameters() {
874    return parameters.isEmpty() ? this : create(type, subtype);
875  }
876
877  /**
878   * <em>Replaces</em> all parameters with the given parameters.
879   *
880   * @throws IllegalArgumentException if any parameter or value is invalid
881   */
882  public MediaType withParameters(Multimap<String, String> parameters) {
883    return create(type, subtype, parameters);
884  }
885
886  /**
887   * <em>Replaces</em> all parameters with the given attribute with parameters using the given
888   * values. If there are no values, any existing parameters with the given attribute are removed.
889   *
890   * @throws IllegalArgumentException if either {@code attribute} or {@code values} is invalid
891   * @since 24.0
892   */
893  public MediaType withParameters(String attribute, Iterable<String> values) {
894    checkNotNull(attribute);
895    checkNotNull(values);
896    String normalizedAttribute = normalizeToken(attribute);
897    ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
898    for (Entry<String, String> entry : parameters.entries()) {
899      String key = entry.getKey();
900      if (!normalizedAttribute.equals(key)) {
901        builder.put(key, entry.getValue());
902      }
903    }
904    for (String value : values) {
905      builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
906    }
907    MediaType mediaType = new MediaType(type, subtype, builder.build());
908    // if the attribute isn't charset, we can just inherit the current parsedCharset
909    if (!normalizedAttribute.equals(CHARSET_ATTRIBUTE)) {
910      mediaType.parsedCharset = this.parsedCharset;
911    }
912    // Return one of the constants if the media type is a known type.
913    @SuppressWarnings("GetOrDefaultNotNull") // getOrDefault requires API Level 24
914    MediaType result = firstNonNull(knownTypes.get(mediaType), mediaType);
915    return result;
916  }
917
918  /**
919   * <em>Replaces</em> all parameters with the given attribute with a single parameter with the
920   * given value. If multiple parameters with the same attributes are necessary use {@link
921   * #withParameters(String, Iterable)}. Prefer {@link #withCharset} for setting the {@code charset}
922   * parameter when using a {@link Charset} object.
923   *
924   * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
925   */
926  public MediaType withParameter(String attribute, String value) {
927    return withParameters(attribute, ImmutableSet.of(value));
928  }
929
930  /**
931   * Returns a new instance with the same type and subtype as this instance, with the {@code
932   * charset} parameter set to the {@link Charset#name name} of the given charset. Only one {@code
933   * charset} parameter will be present on the new instance regardless of the number set on this
934   * one.
935   *
936   * <p>If a charset must be specified that is not supported on this JVM (and thus is not
937   * representable as a {@link Charset} instance), use {@link #withParameter}.
938   */
939  public MediaType withCharset(Charset charset) {
940    checkNotNull(charset);
941    MediaType withCharset = withParameter(CHARSET_ATTRIBUTE, charset.name());
942    // precache the charset so we don't need to parse it
943    withCharset.parsedCharset = Optional.of(charset);
944    return withCharset;
945  }
946
947  /** Returns true if either the type or subtype is the wildcard. */
948  public boolean hasWildcard() {
949    return type.equals(WILDCARD) || subtype.equals(WILDCARD);
950  }
951
952  /**
953   * Returns {@code true} if this instance falls within the range (as defined by <a
954   * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">the HTTP Accept header</a>) given
955   * by the argument according to three criteria:
956   *
957   * <ol>
958   *   <li>The type of the argument is the wildcard or equal to the type of this instance.
959   *   <li>The subtype of the argument is the wildcard or equal to the subtype of this instance.
960   *   <li>All of the parameters present in the argument are present in this instance.
961   * </ol>
962   *
963   * <p>For example:
964   *
965   * {@snippet :
966   * PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8) // true
967   * PLAIN_TEXT_UTF_8.is(HTML_UTF_8) // false
968   * PLAIN_TEXT_UTF_8.is(ANY_TYPE) // true
969   * PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE) // true
970   * PLAIN_TEXT_UTF_8.is(ANY_IMAGE_TYPE) // false
971   * PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_8)) // true
972   * PLAIN_TEXT_UTF_8.withoutParameters().is(ANY_TEXT_TYPE.withCharset(UTF_8)) // false
973   * PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_16)) // false
974   * }
975   *
976   * <p>Note that while it is possible to have the same parameter declared multiple times within a
977   * media type this method does not consider the number of occurrences of a parameter. For example,
978   * {@code "text/plain; charset=UTF-8"} satisfies {@code "text/plain; charset=UTF-8;
979   * charset=UTF-8"}.
980   */
981  public boolean is(MediaType mediaTypeRange) {
982    return (mediaTypeRange.type.equals(WILDCARD) || mediaTypeRange.type.equals(this.type))
983        && (mediaTypeRange.subtype.equals(WILDCARD) || mediaTypeRange.subtype.equals(this.subtype))
984        && this.parameters.entries().containsAll(mediaTypeRange.parameters.entries());
985  }
986
987  /**
988   * Creates a new media type with the given type and subtype.
989   *
990   * @throws IllegalArgumentException if type or subtype is invalid or if a wildcard is used for the
991   *     type, but not the subtype.
992   */
993  public static MediaType create(String type, String subtype) {
994    MediaType mediaType = create(type, subtype, ImmutableListMultimap.<String, String>of());
995    mediaType.parsedCharset = Optional.absent();
996    return mediaType;
997  }
998
999  private static MediaType create(
1000      String type, String subtype, Multimap<String, String> parameters) {
1001    checkNotNull(type);
1002    checkNotNull(subtype);
1003    checkNotNull(parameters);
1004    String normalizedType = normalizeToken(type);
1005    String normalizedSubtype = normalizeToken(subtype);
1006    checkArgument(
1007        !normalizedType.equals(WILDCARD) || normalizedSubtype.equals(WILDCARD),
1008        "A wildcard type cannot be used with a non-wildcard subtype");
1009    ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
1010    for (Entry<String, String> entry : parameters.entries()) {
1011      String attribute = normalizeToken(entry.getKey());
1012      builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
1013    }
1014    MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
1015    // Return one of the constants if the media type is a known type.
1016    @SuppressWarnings("GetOrDefaultNotNull") // getOrDefault requires API Level 24
1017    MediaType result = firstNonNull(knownTypes.get(mediaType), mediaType);
1018    return result;
1019  }
1020
1021  /**
1022   * Creates a media type with the "application" type and the given subtype.
1023   *
1024   * @throws IllegalArgumentException if subtype is invalid
1025   */
1026  static MediaType createApplicationType(String subtype) {
1027    return create(APPLICATION_TYPE, subtype);
1028  }
1029
1030  /**
1031   * Creates a media type with the "audio" type and the given subtype.
1032   *
1033   * @throws IllegalArgumentException if subtype is invalid
1034   */
1035  static MediaType createAudioType(String subtype) {
1036    return create(AUDIO_TYPE, subtype);
1037  }
1038
1039  /**
1040   * Creates a media type with the "font" type and the given subtype.
1041   *
1042   * @throws IllegalArgumentException if subtype is invalid
1043   */
1044  static MediaType createFontType(String subtype) {
1045    return create(FONT_TYPE, subtype);
1046  }
1047
1048  /**
1049   * Creates a media type with the "image" type and the given subtype.
1050   *
1051   * @throws IllegalArgumentException if subtype is invalid
1052   */
1053  static MediaType createImageType(String subtype) {
1054    return create(IMAGE_TYPE, subtype);
1055  }
1056
1057  /**
1058   * Creates a media type with the "text" type and the given subtype.
1059   *
1060   * @throws IllegalArgumentException if subtype is invalid
1061   */
1062  static MediaType createTextType(String subtype) {
1063    return create(TEXT_TYPE, subtype);
1064  }
1065
1066  /**
1067   * Creates a media type with the "video" type and the given subtype.
1068   *
1069   * @throws IllegalArgumentException if subtype is invalid
1070   */
1071  static MediaType createVideoType(String subtype) {
1072    return create(VIDEO_TYPE, subtype);
1073  }
1074
1075  private static String normalizeToken(String token) {
1076    checkArgument(TOKEN_MATCHER.matchesAllOf(token));
1077    checkArgument(!token.isEmpty());
1078    return Ascii.toLowerCase(token);
1079  }
1080
1081  private static String normalizeParameterValue(String attribute, String value) {
1082    checkNotNull(value); // for GWT
1083    checkArgument(ascii().matchesAllOf(value), "parameter values must be ASCII: %s", value);
1084    return attribute.equals(CHARSET_ATTRIBUTE) ? Ascii.toLowerCase(value) : value;
1085  }
1086
1087  /**
1088   * Parses a media type from its string representation.
1089   *
1090   * @throws IllegalArgumentException if the input is not parsable
1091   */
1092  @CanIgnoreReturnValue // TODO(b/219820829): consider removing
1093  public static MediaType parse(String input) {
1094    checkNotNull(input);
1095    Tokenizer tokenizer = new Tokenizer(input);
1096    try {
1097      String type = tokenizer.consumeToken(TOKEN_MATCHER);
1098      consumeSeparator(tokenizer, '/');
1099      String subtype = tokenizer.consumeToken(TOKEN_MATCHER);
1100      ImmutableListMultimap.Builder<String, String> parameters = ImmutableListMultimap.builder();
1101      while (tokenizer.hasMore()) {
1102        consumeSeparator(tokenizer, ';');
1103        String attribute = tokenizer.consumeToken(TOKEN_MATCHER);
1104        consumeSeparator(tokenizer, '=');
1105        String value;
1106        if (tokenizer.previewChar() == '"') {
1107          tokenizer.consumeCharacter('"');
1108          StringBuilder valueBuilder = new StringBuilder();
1109          while (tokenizer.previewChar() != '"') {
1110            if (tokenizer.previewChar() == '\\') {
1111              tokenizer.consumeCharacter('\\');
1112              valueBuilder.append(tokenizer.consumeCharacter(ascii()));
1113            } else {
1114              valueBuilder.append(tokenizer.consumeToken(QUOTED_TEXT_MATCHER));
1115            }
1116          }
1117          value = valueBuilder.toString();
1118          tokenizer.consumeCharacter('"');
1119        } else {
1120          value = tokenizer.consumeToken(TOKEN_MATCHER);
1121        }
1122        parameters.put(attribute, value);
1123      }
1124      return create(type, subtype, parameters.build());
1125    } catch (IllegalStateException e) {
1126      throw new IllegalArgumentException("Could not parse '" + input + "'", e);
1127    }
1128  }
1129
1130  private static void consumeSeparator(Tokenizer tokenizer, char c) {
1131    tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE);
1132    tokenizer.consumeCharacter(c);
1133    tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE);
1134  }
1135
1136  private static final class Tokenizer {
1137    final String input;
1138    int position = 0;
1139
1140    Tokenizer(String input) {
1141      this.input = input;
1142    }
1143
1144    @CanIgnoreReturnValue
1145    String consumeTokenIfPresent(CharMatcher matcher) {
1146      checkState(hasMore());
1147      int startPosition = position;
1148      position = matcher.negate().indexIn(input, startPosition);
1149      return hasMore() ? input.substring(startPosition, position) : input.substring(startPosition);
1150    }
1151
1152    String consumeToken(CharMatcher matcher) {
1153      int startPosition = position;
1154      String token = consumeTokenIfPresent(matcher);
1155      checkState(position != startPosition);
1156      return token;
1157    }
1158
1159    char consumeCharacter(CharMatcher matcher) {
1160      checkState(hasMore());
1161      char c = previewChar();
1162      checkState(matcher.matches(c));
1163      position++;
1164      return c;
1165    }
1166
1167    @CanIgnoreReturnValue
1168    char consumeCharacter(char c) {
1169      checkState(hasMore());
1170      checkState(previewChar() == c);
1171      position++;
1172      return c;
1173    }
1174
1175    char previewChar() {
1176      checkState(hasMore());
1177      return input.charAt(position);
1178    }
1179
1180    boolean hasMore() {
1181      return (position >= 0) && (position < input.length());
1182    }
1183  }
1184
1185  @Override
1186  public boolean equals(@Nullable Object obj) {
1187    if (obj == this) {
1188      return true;
1189    } else if (obj instanceof MediaType) {
1190      MediaType that = (MediaType) obj;
1191      return this.type.equals(that.type)
1192          && this.subtype.equals(that.subtype)
1193          // compare parameters regardless of order
1194          && this.parametersAsMap().equals(that.parametersAsMap());
1195    } else {
1196      return false;
1197    }
1198  }
1199
1200  @Override
1201  public int hashCode() {
1202    // racy single-check idiom
1203    int h = hashCode;
1204    if (h == 0) {
1205      h = hash(type, subtype, parametersAsMap());
1206      hashCode = h;
1207    }
1208    return h;
1209  }
1210
1211  private static final MapJoiner PARAMETER_JOINER = Joiner.on("; ").withKeyValueSeparator("=");
1212
1213  /**
1214   * Returns the string representation of this media type in the format described in <a
1215   * href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
1216   */
1217  @Override
1218  public String toString() {
1219    // racy single-check idiom, safe because String is immutable
1220    String result = toString;
1221    if (result == null) {
1222      result = computeToString();
1223      toString = result;
1224    }
1225    return result;
1226  }
1227
1228  private String computeToString() {
1229    StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
1230    if (!parameters.isEmpty()) {
1231      builder.append("; ");
1232      Multimap<String, String> quotedParameters =
1233          Multimaps.transformValues(
1234              parameters,
1235              (String value) ->
1236                  (TOKEN_MATCHER.matchesAllOf(value) && !value.isEmpty())
1237                      ? value
1238                      : escapeAndQuote(value));
1239      PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
1240    }
1241    return builder.toString();
1242  }
1243
1244  private static String escapeAndQuote(String value) {
1245    StringBuilder escaped = new StringBuilder(value.length() + 16).append('"');
1246    for (int i = 0; i < value.length(); i++) {
1247      char ch = value.charAt(i);
1248      if (ch == '\r' || ch == '\\' || ch == '"') {
1249        escaped.append('\\');
1250      }
1251      escaped.append(ch);
1252    }
1253    return escaped.append('"').toString();
1254  }
1255}