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