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