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