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